index-49qrvi2a.js 4.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686
  1. function Zoe(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const a in r)if(a!=="default"&&!(a in t)){const s=Object.getOwnPropertyDescriptor(r,a);s&&Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:()=>r[a]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(a){if(a.ep)return;a.ep=!0;const s=n(a);fetch(a.href,s)}})();var eS=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function nc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var kM={exports:{}},Yx={};var UU;function Joe(){if(UU)return Yx;UU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,a,s){var o=null;if(s!==void 0&&(o=""+s),a.key!==void 0&&(o=""+a.key),"key"in a){s={};for(var l in a)l!=="key"&&(s[l]=a[l])}else s=a;return a=s.ref,{$$typeof:t,type:r,key:o,ref:a!==void 0?a:null,props:s}}return Yx.Fragment=e,Yx.jsx=n,Yx.jsxs=n,Yx}var BU;function ele(){return BU||(BU=1,kM.exports=Joe()),kM.exports}var i=ele(),AM={exports:{}},An={};var HU;function tle(){if(HU)return An;HU=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),f=Symbol.iterator;function p(H){return H===null||typeof H!="object"?null:(H=f&&H[f]||H["@@iterator"],typeof H=="function"?H:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,g={};function y(H,K,te){this.props=H,this.context=K,this.refs=g,this.updater=te||x}y.prototype.isReactComponent={},y.prototype.setState=function(H,K){if(typeof H!="object"&&typeof H!="function"&&H!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,H,K,"setState")},y.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function _(){}_.prototype=y.prototype;function N(H,K,te){this.props=H,this.context=K,this.refs=g,this.updater=te||x}var k=N.prototype=new _;k.constructor=N,v(k,y.prototype),k.isPureReactComponent=!0;var A=Array.isArray;function M(){}var C={H:null,A:null,T:null,S:null},j=Object.prototype.hasOwnProperty;function P(H,K,te){var Z=te.ref;return{$$typeof:t,type:H,key:K,ref:Z!==void 0?Z:null,props:te}}function E(H,K){return P(H.type,K,H.props)}function U(H){return typeof H=="object"&&H!==null&&H.$$typeof===t}function L(H){var K={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(te){return K[te]})}var B=/\/+/g;function D(H,K){return typeof H=="object"&&H!==null&&H.key!=null?L(""+H.key):K.toString(36)}function $(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(M,M):(H.status="pending",H.then(function(K){H.status==="pending"&&(H.status="fulfilled",H.value=K)},function(K){H.status==="pending"&&(H.status="rejected",H.reason=K)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function G(H,K,te,Z,ve){var ce=typeof H;(ce==="undefined"||ce==="boolean")&&(H=null);var ee=!1;if(H===null)ee=!0;else switch(ce){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(H.$$typeof){case t:case e:ee=!0;break;case d:return ee=H._init,G(ee(H._payload),K,te,Z,ve)}}if(ee)return ve=ve(H),ee=Z===""?"."+D(H,0):Z,A(ve)?(te="",ee!=null&&(te=ee.replace(B,"$&/")+"/"),G(ve,K,te,"",function(oe){return oe})):ve!=null&&(U(ve)&&(ve=E(ve,te+(ve.key==null||H&&H.key===ve.key?"":(""+ve.key).replace(B,"$&/")+"/")+ee)),K.push(ve)),1;ee=0;var je=Z===""?".":Z+":";if(A(H))for(var he=0;he<H.length;he++)Z=H[he],ce=je+D(Z,he),ee+=G(Z,K,te,ce,ve);else if(he=p(H),typeof he=="function")for(H=he.call(H),he=0;!(Z=H.next()).done;)Z=Z.value,ce=je+D(Z,he++),ee+=G(Z,K,te,ce,ve);else if(ce==="object"){if(typeof H.then=="function")return G($(H),K,te,Z,ve);throw K=String(H),Error("Objects are not valid as a React child (found: "+(K==="[object Object]"?"object with keys {"+Object.keys(H).join(", ")+"}":K)+"). If you meant to render a collection of children, use an array instead.")}return ee}function z(H,K,te){if(H==null)return H;var Z=[],ve=0;return G(H,Z,"","",function(ce){return K.call(te,ce,ve++)}),Z}function W(H){if(H._status===-1){var K=H._result;K=K(),K.then(function(te){(H._status===0||H._status===-1)&&(H._status=1,H._result=te)},function(te){(H._status===0||H._status===-1)&&(H._status=2,H._result=te)}),H._status===-1&&(H._status=0,H._result=K)}if(H._status===1)return H._result.default;throw H._result}var X=typeof reportError=="function"?reportError:function(H){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var K=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof H=="object"&&H!==null&&typeof H.message=="string"?String(H.message):String(H),error:H});if(!window.dispatchEvent(K))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",H);return}console.error(H)},ae={map:z,forEach:function(H,K,te){z(H,function(){K.apply(this,arguments)},te)},count:function(H){var K=0;return z(H,function(){K++}),K},toArray:function(H){return z(H,function(K){return K})||[]},only:function(H){if(!U(H))throw Error("React.Children.only expected to receive a single React element child.");return H}};return An.Activity=h,An.Children=ae,An.Component=y,An.Fragment=n,An.Profiler=a,An.PureComponent=N,An.StrictMode=r,An.Suspense=c,An.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C,An.__COMPILER_RUNTIME={__proto__:null,c:function(H){return C.H.useMemoCache(H)}},An.cache=function(H){return function(){return H.apply(null,arguments)}},An.cacheSignal=function(){return null},An.cloneElement=function(H,K,te){if(H==null)throw Error("The argument must be a React element, but you passed "+H+".");var Z=v({},H.props),ve=H.key;if(K!=null)for(ce in K.key!==void 0&&(ve=""+K.key),K)!j.call(K,ce)||ce==="key"||ce==="__self"||ce==="__source"||ce==="ref"&&K.ref===void 0||(Z[ce]=K[ce]);var ce=arguments.length-2;if(ce===1)Z.children=te;else if(1<ce){for(var ee=Array(ce),je=0;je<ce;je++)ee[je]=arguments[je+2];Z.children=ee}return P(H.type,ve,Z)},An.createContext=function(H){return H={$$typeof:o,_currentValue:H,_currentValue2:H,_threadCount:0,Provider:null,Consumer:null},H.Provider=H,H.Consumer={$$typeof:s,_context:H},H},An.createElement=function(H,K,te){var Z,ve={},ce=null;if(K!=null)for(Z in K.key!==void 0&&(ce=""+K.key),K)j.call(K,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(ve[Z]=K[Z]);var ee=arguments.length-2;if(ee===1)ve.children=te;else if(1<ee){for(var je=Array(ee),he=0;he<ee;he++)je[he]=arguments[he+2];ve.children=je}if(H&&H.defaultProps)for(Z in ee=H.defaultProps,ee)ve[Z]===void 0&&(ve[Z]=ee[Z]);return P(H,ce,ve)},An.createRef=function(){return{current:null}},An.forwardRef=function(H){return{$$typeof:l,render:H}},An.isValidElement=U,An.lazy=function(H){return{$$typeof:d,_payload:{_status:-1,_result:H},_init:W}},An.memo=function(H,K){return{$$typeof:u,type:H,compare:K===void 0?null:K}},An.startTransition=function(H){var K=C.T,te={};C.T=te;try{var Z=H(),ve=C.S;ve!==null&&ve(te,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(M,X)}catch(ce){X(ce)}finally{K!==null&&te.types!==null&&(K.types=te.types),C.T=K}},An.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()},An.use=function(H){return C.H.use(H)},An.useActionState=function(H,K,te){return C.H.useActionState(H,K,te)},An.useCallback=function(H,K){return C.H.useCallback(H,K)},An.useContext=function(H){return C.H.useContext(H)},An.useDebugValue=function(){},An.useDeferredValue=function(H,K){return C.H.useDeferredValue(H,K)},An.useEffect=function(H,K){return C.H.useEffect(H,K)},An.useEffectEvent=function(H){return C.H.useEffectEvent(H)},An.useId=function(){return C.H.useId()},An.useImperativeHandle=function(H,K,te){return C.H.useImperativeHandle(H,K,te)},An.useInsertionEffect=function(H,K){return C.H.useInsertionEffect(H,K)},An.useLayoutEffect=function(H,K){return C.H.useLayoutEffect(H,K)},An.useMemo=function(H,K){return C.H.useMemo(H,K)},An.useOptimistic=function(H,K){return C.H.useOptimistic(H,K)},An.useReducer=function(H,K,te){return C.H.useReducer(H,K,te)},An.useRef=function(H){return C.H.useRef(H)},An.useState=function(H){return C.H.useState(H)},An.useSyncExternalStore=function(H,K,te){return C.H.useSyncExternalStore(H,K,te)},An.useTransition=function(){return C.H.useTransition()},An.version="19.2.4",An}var $U;function zb(){return $U||($U=1,AM.exports=tle()),AM.exports}var w=zb();const Hr=nc(w),nle=Zoe({__proto__:null,default:Hr},[w]);var TM={exports:{}},Qx={},MM={exports:{}},PM={};var VU;function rle(){return VU||(VU=1,(function(t){function e(G,z){var W=G.length;G.push(z);e:for(;0<W;){var X=W-1>>>1,ae=G[X];if(0<a(ae,z))G[X]=z,G[W]=ae,W=X;else break e}}function n(G){return G.length===0?null:G[0]}function r(G){if(G.length===0)return null;var z=G[0],W=G.pop();if(W!==z){G[0]=W;e:for(var X=0,ae=G.length,H=ae>>>1;X<H;){var K=2*(X+1)-1,te=G[K],Z=K+1,ve=G[Z];if(0>a(te,W))Z<ae&&0>a(ve,te)?(G[X]=ve,G[Z]=W,X=Z):(G[X]=te,G[K]=W,X=K);else if(Z<ae&&0>a(ve,W))G[X]=ve,G[Z]=W,X=Z;else break e}}return z}function a(G,z){var W=G.sortIndex-z.sortIndex;return W!==0?W:G.id-z.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],u=[],d=1,h=null,f=3,p=!1,x=!1,v=!1,g=!1,y=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,N=typeof setImmediate<"u"?setImmediate:null;function k(G){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=G)r(u),z.sortIndex=z.expirationTime,e(c,z);else break;z=n(u)}}function A(G){if(v=!1,k(G),!x)if(n(c)!==null)x=!0,M||(M=!0,L());else{var z=n(u);z!==null&&$(A,z.startTime-G)}}var M=!1,C=-1,j=5,P=-1;function E(){return g?!0:!(t.unstable_now()-P<j)}function U(){if(g=!1,M){var G=t.unstable_now();P=G;var z=!0;try{e:{x=!1,v&&(v=!1,_(C),C=-1),p=!0;var W=f;try{t:{for(k(G),h=n(c);h!==null&&!(h.expirationTime>G&&E());){var X=h.callback;if(typeof X=="function"){h.callback=null,f=h.priorityLevel;var ae=X(h.expirationTime<=G);if(G=t.unstable_now(),typeof ae=="function"){h.callback=ae,k(G),z=!0;break t}h===n(c)&&r(c),k(G)}else r(c);h=n(c)}if(h!==null)z=!0;else{var H=n(u);H!==null&&$(A,H.startTime-G),z=!1}}break e}finally{h=null,f=W,p=!1}z=void 0}}finally{z?L():M=!1}}}var L;if(typeof N=="function")L=function(){N(U)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,D=B.port2;B.port1.onmessage=U,L=function(){D.postMessage(null)}}else L=function(){y(U,0)};function $(G,z){C=y(function(){G(t.unstable_now())},z)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(G){G.callback=null},t.unstable_forceFrameRate=function(G){0>G||125<G?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):j=0<G?Math.floor(1e3/G):5},t.unstable_getCurrentPriorityLevel=function(){return f},t.unstable_next=function(G){switch(f){case 1:case 2:case 3:var z=3;break;default:z=f}var W=f;f=z;try{return G()}finally{f=W}},t.unstable_requestPaint=function(){g=!0},t.unstable_runWithPriority=function(G,z){switch(G){case 1:case 2:case 3:case 4:case 5:break;default:G=3}var W=f;f=G;try{return z()}finally{f=W}},t.unstable_scheduleCallback=function(G,z,W){var X=t.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?X+W:X):W=X,G){case 1:var ae=-1;break;case 2:ae=250;break;case 5:ae=1073741823;break;case 4:ae=1e4;break;default:ae=5e3}return ae=W+ae,G={id:d++,callback:z,priorityLevel:G,startTime:W,expirationTime:ae,sortIndex:-1},W>X?(G.sortIndex=W,e(u,G),n(c)===null&&G===n(u)&&(v?(_(C),C=-1):v=!0,$(A,W-X))):(G.sortIndex=ae,e(c,G),x||p||(x=!0,M||(M=!0,L()))),G},t.unstable_shouldYield=E,t.unstable_wrapCallback=function(G){var z=f;return function(){var W=f;f=z;try{return G.apply(this,arguments)}finally{f=W}}}})(PM)),PM}var qU;function ale(){return qU||(qU=1,MM.exports=rle()),MM.exports}var EM={exports:{}},as={};var GU;function ile(){if(GU)return as;GU=1;var t=zb();function e(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(e(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},a=Symbol.for("react.portal");function s(c,u,d){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:h==null?null:""+h,children:c,containerInfo:u,implementation:d}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return as.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,as.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(e(299));return s(c,u,null,d)},as.flushSync=function(c){var u=o.T,d=r.p;try{if(o.T=null,r.p=2,c)return c()}finally{o.T=u,r.p=d,r.d.f()}},as.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},as.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},as.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,h=l(d,u.crossOrigin),f=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:h,integrity:f,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:h,integrity:f,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},as.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},as.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,h=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:h,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},as.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},as.requestFormReset=function(c){r.d.r(c)},as.unstable_batchedUpdates=function(c,u){return c(u)},as.useFormState=function(c,u,d){return o.H.useFormState(c,u,d)},as.useFormStatus=function(){return o.H.useHostTransitionStatus()},as.version="19.2.4",as}var WU;function gK(){if(WU)return EM.exports;WU=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),EM.exports=ile(),EM.exports}var KU;function sle(){if(KU)return Qx;KU=1;var t=ale(),e=zb(),n=gK();function r(m){var b="https://react.dev/errors/"+m;if(1<arguments.length){b+="?args[]="+encodeURIComponent(arguments[1]);for(var S=2;S<arguments.length;S++)b+="&args[]="+encodeURIComponent(arguments[S])}return"Minified React error #"+m+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(m){return!(!m||m.nodeType!==1&&m.nodeType!==9&&m.nodeType!==11)}function s(m){var b=m,S=m;if(m.alternate)for(;b.return;)b=b.return;else{m=b;do b=m,(b.flags&4098)!==0&&(S=b.return),m=b.return;while(m)}return b.tag===3?S:null}function o(m){if(m.tag===13){var b=m.memoizedState;if(b===null&&(m=m.alternate,m!==null&&(b=m.memoizedState)),b!==null)return b.dehydrated}return null}function l(m){if(m.tag===31){var b=m.memoizedState;if(b===null&&(m=m.alternate,m!==null&&(b=m.memoizedState)),b!==null)return b.dehydrated}return null}function c(m){if(s(m)!==m)throw Error(r(188))}function u(m){var b=m.alternate;if(!b){if(b=s(m),b===null)throw Error(r(188));return b!==m?null:m}for(var S=m,T=b;;){var F=S.return;if(F===null)break;var I=F.alternate;if(I===null){if(T=F.return,T!==null){S=T;continue}break}if(F.child===I.child){for(I=F.child;I;){if(I===S)return c(F),m;if(I===T)return c(F),b;I=I.sibling}throw Error(r(188))}if(S.return!==T.return)S=F,T=I;else{for(var re=!1,Pe=F.child;Pe;){if(Pe===S){re=!0,S=F,T=I;break}if(Pe===T){re=!0,T=F,S=I;break}Pe=Pe.sibling}if(!re){for(Pe=I.child;Pe;){if(Pe===S){re=!0,S=I,T=F;break}if(Pe===T){re=!0,T=I,S=F;break}Pe=Pe.sibling}if(!re)throw Error(r(189))}}if(S.alternate!==T)throw Error(r(190))}if(S.tag!==3)throw Error(r(188));return S.stateNode.current===S?m:b}function d(m){var b=m.tag;if(b===5||b===26||b===27||b===6)return m;for(m=m.child;m!==null;){if(b=d(m),b!==null)return b;m=m.sibling}return null}var h=Object.assign,f=Symbol.for("react.element"),p=Symbol.for("react.transitional.element"),x=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),g=Symbol.for("react.strict_mode"),y=Symbol.for("react.profiler"),_=Symbol.for("react.consumer"),N=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),C=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),P=Symbol.for("react.activity"),E=Symbol.for("react.memo_cache_sentinel"),U=Symbol.iterator;function L(m){return m===null||typeof m!="object"?null:(m=U&&m[U]||m["@@iterator"],typeof m=="function"?m:null)}var B=Symbol.for("react.client.reference");function D(m){if(m==null)return null;if(typeof m=="function")return m.$$typeof===B?null:m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case v:return"Fragment";case y:return"Profiler";case g:return"StrictMode";case A:return"Suspense";case M:return"SuspenseList";case P:return"Activity"}if(typeof m=="object")switch(m.$$typeof){case x:return"Portal";case N:return m.displayName||"Context";case _:return(m._context.displayName||"Context")+".Consumer";case k:var b=m.render;return m=m.displayName,m||(m=b.displayName||b.name||"",m=m!==""?"ForwardRef("+m+")":"ForwardRef"),m;case C:return b=m.displayName||null,b!==null?b:D(m.type)||"Memo";case j:b=m._payload,m=m._init;try{return D(m(b))}catch{}}return null}var $=Array.isArray,G=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},X=[],ae=-1;function H(m){return{current:m}}function K(m){0>ae||(m.current=X[ae],X[ae]=null,ae--)}function te(m,b){ae++,X[ae]=m.current,m.current=b}var Z=H(null),ve=H(null),ce=H(null),ee=H(null);function je(m,b){switch(te(ce,b),te(ve,m),te(Z,null),b.nodeType){case 9:case 11:m=(m=b.documentElement)&&(m=m.namespaceURI)?cU(m):0;break;default:if(m=b.tagName,b=b.namespaceURI)b=cU(b),m=uU(b,m);else switch(m){case"svg":m=1;break;case"math":m=2;break;default:m=0}}K(Z),te(Z,m)}function he(){K(Z),K(ve),K(ce)}function oe(m){m.memoizedState!==null&&te(ee,m);var b=Z.current,S=uU(b,m.type);b!==S&&(te(ve,m),te(Z,S))}function _e(m){ve.current===m&&(K(Z),K(ve)),ee.current===m&&(K(ee),Gx._currentValue=W)}var ie,ze;function V(m){if(ie===void 0)try{throw Error()}catch(S){var b=S.stack.trim().match(/\n( *(at )?)/);ie=b&&b[1]||"",ze=-1<S.stack.indexOf(`
  2. at`)?" (<anonymous>)":-1<S.stack.indexOf("@")?"@unknown:0:0":""}return`
  3. `+ie+m+ze}var Y=!1;function me(m,b){if(!m||Y)return"";Y=!0;var S=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var T={DetermineComponentFrameRoot:function(){try{if(b){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(gt){var mt=gt}Reflect.construct(m,[],Ct)}else{try{Ct.call()}catch(gt){mt=gt}m.call(Ct.prototype)}}else{try{throw Error()}catch(gt){mt=gt}(Ct=m())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(gt){if(gt&&mt&&typeof gt.stack=="string")return[gt.stack,mt.stack]}return[null,null]}};T.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var F=Object.getOwnPropertyDescriptor(T.DetermineComponentFrameRoot,"name");F&&F.configurable&&Object.defineProperty(T.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var I=T.DetermineComponentFrameRoot(),re=I[0],Pe=I[1];if(re&&Pe){var Ve=re.split(`
  4. `),dt=Pe.split(`
  5. `);for(F=T=0;T<Ve.length&&!Ve[T].includes("DetermineComponentFrameRoot");)T++;for(;F<dt.length&&!dt[F].includes("DetermineComponentFrameRoot");)F++;if(T===Ve.length||F===dt.length)for(T=Ve.length-1,F=dt.length-1;1<=T&&0<=F&&Ve[T]!==dt[F];)F--;for(;1<=T&&0<=F;T--,F--)if(Ve[T]!==dt[F]){if(T!==1||F!==1)do if(T--,F--,0>F||Ve[T]!==dt[F]){var vt=`
  6. `+Ve[T].replace(" at new "," at ");return m.displayName&&vt.includes("<anonymous>")&&(vt=vt.replace("<anonymous>",m.displayName)),vt}while(1<=T&&0<=F);break}}}finally{Y=!1,Error.prepareStackTrace=S}return(S=m?m.displayName||m.name:"")?V(S):""}function Q(m,b){switch(m.tag){case 26:case 27:case 5:return V(m.type);case 16:return V("Lazy");case 13:return m.child!==b&&b!==null?V("Suspense Fallback"):V("Suspense");case 19:return V("SuspenseList");case 0:case 15:return me(m.type,!1);case 11:return me(m.type.render,!1);case 1:return me(m.type,!0);case 31:return V("Activity");default:return""}}function se(m){try{var b="",S=null;do b+=Q(m,S),S=m,m=m.return;while(m);return b}catch(T){return`
  7. Error generating stack: `+T.message+`
  8. `+T.stack}}var de=Object.prototype.hasOwnProperty,Le=t.unstable_scheduleCallback,Ne=t.unstable_cancelCallback,be=t.unstable_shouldYield,O=t.unstable_requestPaint,R=t.unstable_now,q=t.unstable_getCurrentPriorityLevel,J=t.unstable_ImmediatePriority,fe=t.unstable_UserBlockingPriority,le=t.unstable_NormalPriority,Be=t.unstable_LowPriority,Ie=t.unstable_IdlePriority,Ke=t.log,Oe=t.unstable_setDisableYieldValue,pe=null,xe=null;function ke(m){if(typeof Ke=="function"&&Oe(m),xe&&typeof xe.setStrictMode=="function")try{xe.setStrictMode(pe,m)}catch{}}var ge=Math.clz32?Math.clz32:Ee,we=Math.log,qe=Math.LN2;function Ee(m){return m>>>=0,m===0?32:31-(we(m)/qe|0)|0}var tt=256,De=262144,We=4194304;function Ae(m){var b=m&42;if(b!==0)return b;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return m&261888;case 262144:case 524288:case 1048576:case 2097152:return m&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function Re(m,b,S){var T=m.pendingLanes;if(T===0)return 0;var F=0,I=m.suspendedLanes,re=m.pingedLanes;m=m.warmLanes;var Pe=T&134217727;return Pe!==0?(T=Pe&~I,T!==0?F=Ae(T):(re&=Pe,re!==0?F=Ae(re):S||(S=Pe&~m,S!==0&&(F=Ae(S))))):(Pe=T&~I,Pe!==0?F=Ae(Pe):re!==0?F=Ae(re):S||(S=T&~m,S!==0&&(F=Ae(S)))),F===0?0:b!==0&&b!==F&&(b&I)===0&&(I=F&-F,S=b&-b,I>=S||I===32&&(S&4194048)!==0)?b:F}function $e(m,b){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&b)===0}function ht(m,b){switch(m){case 1:case 2:case 4:case 8:case 64:return b+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return b+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function At(){var m=We;return We<<=1,(We&62914560)===0&&(We=4194304),m}function Dt(m){for(var b=[],S=0;31>S;S++)b.push(m);return b}function It(m,b){m.pendingLanes|=b,b!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function kt(m,b,S,T,F,I){var re=m.pendingLanes;m.pendingLanes=S,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=S,m.entangledLanes&=S,m.errorRecoveryDisabledLanes&=S,m.shellSuspendCounter=0;var Pe=m.entanglements,Ve=m.expirationTimes,dt=m.hiddenUpdates;for(S=re&~S;0<S;){var vt=31-ge(S),Ct=1<<vt;Pe[vt]=0,Ve[vt]=-1;var mt=dt[vt];if(mt!==null)for(dt[vt]=null,vt=0;vt<mt.length;vt++){var gt=mt[vt];gt!==null&&(gt.lane&=-536870913)}S&=~Ct}T!==0&&Ue(m,T,0),I!==0&&F===0&&m.tag!==0&&(m.suspendedLanes|=I&~(re&~b))}function Ue(m,b,S){m.pendingLanes|=b,m.suspendedLanes&=~b;var T=31-ge(b);m.entangledLanes|=b,m.entanglements[T]=m.entanglements[T]|1073741824|S&261930}function bt(m,b){var S=m.entangledLanes|=b;for(m=m.entanglements;S;){var T=31-ge(S),F=1<<T;F&b|m[T]&b&&(m[T]|=b),S&=~F}}function yt(m,b){var S=b&-b;return S=(S&42)!==0?1:Gt(S),(S&(m.suspendedLanes|b))!==0?0:S}function Gt(m){switch(m){case 2:m=1;break;case 8:m=4;break;case 32:m=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:m=128;break;case 268435456:m=134217728;break;default:m=0}return m}function Cn(m){return m&=-m,2<m?8<m?(m&134217727)!==0?32:268435456:8:2}function vr(){var m=z.p;return m!==0?m:(m=window.event,m===void 0?32:DU(m.type))}function Qn(m,b){var S=z.p;try{return z.p=m,b()}finally{z.p=S}}var tr=Math.random().toString(36).slice(2),En="__reactFiber$"+tr,dr="__reactProps$"+tr,Tr="__reactContainer$"+tr,si="__reactEvents$"+tr,Fe="__reactListeners$"+tr,Se="__reactHandles$"+tr,nt="__reactResources$"+tr,ot="__reactMarker$"+tr;function Ge(m){delete m[En],delete m[dr],delete m[si],delete m[Fe],delete m[Se]}function zt(m){var b=m[En];if(b)return b;for(var S=m.parentNode;S;){if(b=S[Tr]||S[En]){if(S=b.alternate,b.child!==null||S!==null&&S.child!==null)for(m=bU(m);m!==null;){if(S=m[En])return S;m=bU(m)}return b}m=S,S=m.parentNode}return null}function ye(m){if(m=m[En]||m[Tr]){var b=m.tag;if(b===5||b===6||b===13||b===31||b===26||b===27||b===3)return m}return null}function He(m){var b=m.tag;if(b===5||b===26||b===27||b===6)return m.stateNode;throw Error(r(33))}function Ye(m){var b=m[nt];return b||(b=m[nt]={hoistableStyles:new Map,hoistableScripts:new Map}),b}function Xe(m){m[ot]=!0}var Te=new Set,lt={};function pt(m,b){at(m,b),at(m+"Capture",b)}function at(m,b){for(lt[m]=b,m=0;m<b.length;m++)Te.add(b[m])}var Tt=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),$t={},Rt={};function Pt(m){return de.call(Rt,m)?!0:de.call($t,m)?!1:Tt.test(m)?Rt[m]=!0:($t[m]=!0,!1)}function sn(m,b,S){if(Pt(b))if(S===null)m.removeAttribute(b);else{switch(typeof S){case"undefined":case"function":case"symbol":m.removeAttribute(b);return;case"boolean":var T=b.toLowerCase().slice(0,5);if(T!=="data-"&&T!=="aria-"){m.removeAttribute(b);return}}m.setAttribute(b,""+S)}}function Zt(m,b,S){if(S===null)m.removeAttribute(b);else{switch(typeof S){case"undefined":case"function":case"symbol":case"boolean":m.removeAttribute(b);return}m.setAttribute(b,""+S)}}function un(m,b,S,T){if(T===null)m.removeAttribute(S);else{switch(typeof T){case"undefined":case"function":case"symbol":case"boolean":m.removeAttribute(S);return}m.setAttributeNS(b,S,""+T)}}function kn(m){switch(typeof m){case"bigint":case"boolean":case"number":case"string":case"undefined":return m;case"object":return m;default:return""}}function Dn(m){var b=m.type;return(m=m.nodeName)&&m.toLowerCase()==="input"&&(b==="checkbox"||b==="radio")}function Xt(m,b,S){var T=Object.getOwnPropertyDescriptor(m.constructor.prototype,b);if(!m.hasOwnProperty(b)&&typeof T<"u"&&typeof T.get=="function"&&typeof T.set=="function"){var F=T.get,I=T.set;return Object.defineProperty(m,b,{configurable:!0,get:function(){return F.call(this)},set:function(re){S=""+re,I.call(this,re)}}),Object.defineProperty(m,b,{enumerable:T.enumerable}),{getValue:function(){return S},setValue:function(re){S=""+re},stopTracking:function(){m._valueTracker=null,delete m[b]}}}}function mn(m){if(!m._valueTracker){var b=Dn(m)?"checked":"value";m._valueTracker=Xt(m,b,""+m[b])}}function fn(m){if(!m)return!1;var b=m._valueTracker;if(!b)return!0;var S=b.getValue(),T="";return m&&(T=Dn(m)?m.checked?"true":"false":m.value),m=T,m!==S?(b.setValue(m),!0):!1}function Gr(m){if(m=m||(typeof document<"u"?document:void 0),typeof m>"u")return null;try{return m.activeElement||m.body}catch{return m.body}}var pn=/[\n"\\]/g;function Rn(m){return m.replace(pn,function(b){return"\\"+b.charCodeAt(0).toString(16)+" "})}function ia(m,b,S,T,F,I,re,Pe){m.name="",re!=null&&typeof re!="function"&&typeof re!="symbol"&&typeof re!="boolean"?m.type=re:m.removeAttribute("type"),b!=null?re==="number"?(b===0&&m.value===""||m.value!=b)&&(m.value=""+kn(b)):m.value!==""+kn(b)&&(m.value=""+kn(b)):re!=="submit"&&re!=="reset"||m.removeAttribute("value"),b!=null?va(m,re,kn(b)):S!=null?va(m,re,kn(S)):T!=null&&m.removeAttribute("value"),F==null&&I!=null&&(m.defaultChecked=!!I),F!=null&&(m.checked=F&&typeof F!="function"&&typeof F!="symbol"),Pe!=null&&typeof Pe!="function"&&typeof Pe!="symbol"&&typeof Pe!="boolean"?m.name=""+kn(Pe):m.removeAttribute("name")}function Sn(m,b,S,T,F,I,re,Pe){if(I!=null&&typeof I!="function"&&typeof I!="symbol"&&typeof I!="boolean"&&(m.type=I),b!=null||S!=null){if(!(I!=="submit"&&I!=="reset"||b!=null)){mn(m);return}S=S!=null?""+kn(S):"",b=b!=null?""+kn(b):S,Pe||b===m.value||(m.value=b),m.defaultValue=b}T=T??F,T=typeof T!="function"&&typeof T!="symbol"&&!!T,m.checked=Pe?m.checked:!!T,m.defaultChecked=!!T,re!=null&&typeof re!="function"&&typeof re!="symbol"&&typeof re!="boolean"&&(m.name=re),mn(m)}function va(m,b,S){b==="number"&&Gr(m.ownerDocument)===m||m.defaultValue===""+S||(m.defaultValue=""+S)}function sr(m,b,S,T){if(m=m.options,b){b={};for(var F=0;F<S.length;F++)b["$"+S[F]]=!0;for(S=0;S<m.length;S++)F=b.hasOwnProperty("$"+m[S].value),m[S].selected!==F&&(m[S].selected=F),F&&T&&(m[S].defaultSelected=!0)}else{for(S=""+kn(S),b=null,F=0;F<m.length;F++){if(m[F].value===S){m[F].selected=!0,T&&(m[F].defaultSelected=!0);return}b!==null||m[F].disabled||(b=m[F])}b!==null&&(b.selected=!0)}}function ma(m,b,S){if(b!=null&&(b=""+kn(b),b!==m.value&&(m.value=b),S==null)){m.defaultValue!==b&&(m.defaultValue=b);return}m.defaultValue=S!=null?""+kn(S):""}function xt(m,b,S,T){if(b==null){if(T!=null){if(S!=null)throw Error(r(92));if($(T)){if(1<T.length)throw Error(r(93));T=T[0]}S=T}S==null&&(S=""),b=S}S=kn(b),m.defaultValue=S,T=m.textContent,T===S&&T!==""&&T!==null&&(m.value=T),mn(m)}function Ft(m,b){if(b){var S=m.firstChild;if(S&&S===m.lastChild&&S.nodeType===3){S.nodeValue=b;return}}m.textContent=b}var bn=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Nt(m,b,S){var T=b.indexOf("--")===0;S==null||typeof S=="boolean"||S===""?T?m.setProperty(b,""):b==="float"?m.cssFloat="":m[b]="":T?m.setProperty(b,S):typeof S!="number"||S===0||bn.has(b)?b==="float"?m.cssFloat=S:m[b]=(""+S).trim():m[b]=S+"px"}function Zn(m,b,S){if(b!=null&&typeof b!="object")throw Error(r(62));if(m=m.style,S!=null){for(var T in S)!S.hasOwnProperty(T)||b!=null&&b.hasOwnProperty(T)||(T.indexOf("--")===0?m.setProperty(T,""):T==="float"?m.cssFloat="":m[T]="");for(var F in b)T=b[F],b.hasOwnProperty(F)&&S[F]!==T&&Nt(m,F,T)}else for(var I in b)b.hasOwnProperty(I)&&Nt(m,I,b[I])}function wr(m){if(m.indexOf("-")===-1)return!1;switch(m){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var hr=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),wa=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Va(m){return wa.test(""+m)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":m}function Vt(){}var xn=null;function Ss(m){return m=m.target||m.srcElement||window,m.correspondingUseElement&&(m=m.correspondingUseElement),m.nodeType===3?m.parentNode:m}var Ci=null,ns=null;function Tl(m){var b=ye(m);if(b&&(m=b.stateNode)){var S=m[dr]||null;e:switch(m=b.stateNode,b.type){case"input":if(ia(m,S.value,S.defaultValue,S.defaultValue,S.checked,S.defaultChecked,S.type,S.name),b=S.name,S.type==="radio"&&b!=null){for(S=m;S.parentNode;)S=S.parentNode;for(S=S.querySelectorAll('input[name="'+Rn(""+b)+'"][type="radio"]'),b=0;b<S.length;b++){var T=S[b];if(T!==m&&T.form===m.form){var F=T[dr]||null;if(!F)throw Error(r(90));ia(T,F.value,F.defaultValue,F.defaultValue,F.checked,F.defaultChecked,F.type,F.name)}}for(b=0;b<S.length;b++)T=S[b],T.form===m.form&&fn(T)}break e;case"textarea":ma(m,S.value,S.defaultValue);break e;case"select":b=S.value,b!=null&&sr(m,!!S.multiple,b,!1)}}}var rs=!1;function oi(m,b,S){if(rs)return m(b,S);rs=!0;try{var T=m(b);return T}finally{if(rs=!1,(Ci!==null||ns!==null)&&(jw(),Ci&&(b=Ci,m=ns,ns=Ci=null,Tl(b),m)))for(b=0;b<m.length;b++)Tl(m[b])}}function Sa(m,b){var S=m.stateNode;if(S===null)return null;var T=S[dr]||null;if(T===null)return null;S=T[b];e:switch(b){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(T=!T.disabled)||(m=m.type,T=!(m==="button"||m==="input"||m==="select"||m==="textarea")),m=!T;break e;default:m=!1}if(m)return null;if(S&&typeof S!="function")throw Error(r(231,b,typeof S));return S}var Qr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),mr=!1;if(Qr)try{var ho={};Object.defineProperty(ho,"passive",{get:function(){mr=!0}}),window.addEventListener("test",ho,ho),window.removeEventListener("test",ho,ho)}catch{mr=!1}var qa=null,Oa=null,mo=null;function Ur(){if(mo)return mo;var m,b=Oa,S=b.length,T,F="value"in qa?qa.value:qa.textContent,I=F.length;for(m=0;m<S&&b[m]===F[m];m++);var re=S-m;for(T=1;T<=re&&b[S-T]===F[I-T];T++);return mo=F.slice(m,1<T?1-T:void 0)}function fa(m){var b=m.keyCode;return"charCode"in m?(m=m.charCode,m===0&&b===13&&(m=13)):m=b,m===10&&(m=13),32<=m||m===13?m:0}function Us(){return!0}function Ht(){return!1}function Vn(m){function b(S,T,F,I,re){this._reactName=S,this._targetInst=F,this.type=T,this.nativeEvent=I,this.target=re,this.currentTarget=null;for(var Pe in m)m.hasOwnProperty(Pe)&&(S=m[Pe],this[Pe]=S?S(I):I[Pe]);return this.isDefaultPrevented=(I.defaultPrevented!=null?I.defaultPrevented:I.returnValue===!1)?Us:Ht,this.isPropagationStopped=Ht,this}return h(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var S=this.nativeEvent;S&&(S.preventDefault?S.preventDefault():typeof S.returnValue!="unknown"&&(S.returnValue=!1),this.isDefaultPrevented=Us)},stopPropagation:function(){var S=this.nativeEvent;S&&(S.stopPropagation?S.stopPropagation():typeof S.cancelBubble!="unknown"&&(S.cancelBubble=!0),this.isPropagationStopped=Us)},persist:function(){},isPersistent:Us}),b}var Ml={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(m){return m.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},um=Vn(Ml),Xc=h({},Ml,{view:0,detail:0}),Y0=Vn(Xc),hx,lp,ue,Et=h({},Xc,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:EA,button:0,buttons:0,relatedTarget:function(m){return m.relatedTarget===void 0?m.fromElement===m.srcElement?m.toElement:m.fromElement:m.relatedTarget},movementX:function(m){return"movementX"in m?m.movementX:(m!==ue&&(ue&&m.type==="mousemove"?(hx=m.screenX-ue.screenX,lp=m.screenY-ue.screenY):lp=hx=0,ue=m),hx)},movementY:function(m){return"movementY"in m?m.movementY:lp}}),sa=Vn(Et),Wr=h({},Et,{dataTransfer:0}),Yc=Vn(Wr),cp=h({},Xc,{relatedTarget:0}),fo=Vn(cp),_s=h({},Ml,{animationName:0,elapsedTime:0,pseudoElement:0}),PA=Vn(_s),hI=h({},Ml,{clipboardData:function(m){return"clipboardData"in m?m.clipboardData:window.clipboardData}}),rse=Vn(hI),ase=h({},Ml,{data:0}),mI=Vn(ase),ise={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},sse={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},ose={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function lse(m){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(m):(m=ose[m])?!!b[m]:!1}function EA(){return lse}var cse=h({},Xc,{key:function(m){if(m.key){var b=ise[m.key]||m.key;if(b!=="Unidentified")return b}return m.type==="keypress"?(m=fa(m),m===13?"Enter":String.fromCharCode(m)):m.type==="keydown"||m.type==="keyup"?sse[m.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:EA,charCode:function(m){return m.type==="keypress"?fa(m):0},keyCode:function(m){return m.type==="keydown"||m.type==="keyup"?m.keyCode:0},which:function(m){return m.type==="keypress"?fa(m):m.type==="keydown"||m.type==="keyup"?m.keyCode:0}}),use=Vn(cse),dse=h({},Et,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),fI=Vn(dse),hse=h({},Xc,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:EA}),mse=Vn(hse),fse=h({},Ml,{propertyName:0,elapsedTime:0,pseudoElement:0}),pse=Vn(fse),gse=h({},Et,{deltaX:function(m){return"deltaX"in m?m.deltaX:"wheelDeltaX"in m?-m.wheelDeltaX:0},deltaY:function(m){return"deltaY"in m?m.deltaY:"wheelDeltaY"in m?-m.wheelDeltaY:"wheelDelta"in m?-m.wheelDelta:0},deltaZ:0,deltaMode:0}),bse=Vn(gse),xse=h({},Ml,{newState:0,oldState:0}),yse=Vn(xse),vse=[9,13,27,32],jA=Qr&&"CompositionEvent"in window,mx=null;Qr&&"documentMode"in document&&(mx=document.documentMode);var wse=Qr&&"TextEvent"in window&&!mx,pI=Qr&&(!jA||mx&&8<mx&&11>=mx),gI=" ",bI=!1;function xI(m,b){switch(m){case"keyup":return vse.indexOf(b.keyCode)!==-1;case"keydown":return b.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function yI(m){return m=m.detail,typeof m=="object"&&"data"in m?m.data:null}var up=!1;function Sse(m,b){switch(m){case"compositionend":return yI(b);case"keypress":return b.which!==32?null:(bI=!0,gI);case"textInput":return m=b.data,m===gI&&bI?null:m;default:return null}}function _se(m,b){if(up)return m==="compositionend"||!jA&&xI(m,b)?(m=Ur(),mo=Oa=qa=null,up=!1,m):null;switch(m){case"paste":return null;case"keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case"compositionend":return pI&&b.locale!=="ko"?null:b.data;default:return null}}var Nse={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function vI(m){var b=m&&m.nodeName&&m.nodeName.toLowerCase();return b==="input"?!!Nse[m.type]:b==="textarea"}function wI(m,b,S,T){Ci?ns?ns.push(T):ns=[T]:Ci=T,b=zw(b,"onChange"),0<b.length&&(S=new um("onChange","change",null,S,T),m.push({event:S,listeners:b}))}var fx=null,px=null;function Cse(m){rU(m,0)}function Q0(m){var b=He(m);if(fn(b))return m}function SI(m,b){if(m==="change")return b}var _I=!1;if(Qr){var DA;if(Qr){var RA="oninput"in document;if(!RA){var NI=document.createElement("div");NI.setAttribute("oninput","return;"),RA=typeof NI.oninput=="function"}DA=RA}else DA=!1;_I=DA&&(!document.documentMode||9<document.documentMode)}function CI(){fx&&(fx.detachEvent("onpropertychange",kI),px=fx=null)}function kI(m){if(m.propertyName==="value"&&Q0(px)){var b=[];wI(b,px,m,Ss(m)),oi(Cse,b)}}function kse(m,b,S){m==="focusin"?(CI(),fx=b,px=S,fx.attachEvent("onpropertychange",kI)):m==="focusout"&&CI()}function Ase(m){if(m==="selectionchange"||m==="keyup"||m==="keydown")return Q0(px)}function Tse(m,b){if(m==="click")return Q0(b)}function Mse(m,b){if(m==="input"||m==="change")return Q0(b)}function Pse(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var po=typeof Object.is=="function"?Object.is:Pse;function gx(m,b){if(po(m,b))return!0;if(typeof m!="object"||m===null||typeof b!="object"||b===null)return!1;var S=Object.keys(m),T=Object.keys(b);if(S.length!==T.length)return!1;for(T=0;T<S.length;T++){var F=S[T];if(!de.call(b,F)||!po(m[F],b[F]))return!1}return!0}function AI(m){for(;m&&m.firstChild;)m=m.firstChild;return m}function TI(m,b){var S=AI(m);m=0;for(var T;S;){if(S.nodeType===3){if(T=m+S.textContent.length,m<=b&&T>=b)return{node:S,offset:b-m};m=T}e:{for(;S;){if(S.nextSibling){S=S.nextSibling;break e}S=S.parentNode}S=void 0}S=AI(S)}}function MI(m,b){return m&&b?m===b?!0:m&&m.nodeType===3?!1:b&&b.nodeType===3?MI(m,b.parentNode):"contains"in m?m.contains(b):m.compareDocumentPosition?!!(m.compareDocumentPosition(b)&16):!1:!1}function PI(m){m=m!=null&&m.ownerDocument!=null&&m.ownerDocument.defaultView!=null?m.ownerDocument.defaultView:window;for(var b=Gr(m.document);b instanceof m.HTMLIFrameElement;){try{var S=typeof b.contentWindow.location.href=="string"}catch{S=!1}if(S)m=b.contentWindow;else break;b=Gr(m.document)}return b}function FA(m){var b=m&&m.nodeName&&m.nodeName.toLowerCase();return b&&(b==="input"&&(m.type==="text"||m.type==="search"||m.type==="tel"||m.type==="url"||m.type==="password")||b==="textarea"||m.contentEditable==="true")}var Ese=Qr&&"documentMode"in document&&11>=document.documentMode,dp=null,LA=null,bx=null,OA=!1;function EI(m,b,S){var T=S.window===S?S.document:S.nodeType===9?S:S.ownerDocument;OA||dp==null||dp!==Gr(T)||(T=dp,"selectionStart"in T&&FA(T)?T={start:T.selectionStart,end:T.selectionEnd}:(T=(T.ownerDocument&&T.ownerDocument.defaultView||window).getSelection(),T={anchorNode:T.anchorNode,anchorOffset:T.anchorOffset,focusNode:T.focusNode,focusOffset:T.focusOffset}),bx&&gx(bx,T)||(bx=T,T=zw(LA,"onSelect"),0<T.length&&(b=new um("onSelect","select",null,b,S),m.push({event:b,listeners:T}),b.target=dp)))}function dm(m,b){var S={};return S[m.toLowerCase()]=b.toLowerCase(),S["Webkit"+m]="webkit"+b,S["Moz"+m]="moz"+b,S}var hp={animationend:dm("Animation","AnimationEnd"),animationiteration:dm("Animation","AnimationIteration"),animationstart:dm("Animation","AnimationStart"),transitionrun:dm("Transition","TransitionRun"),transitionstart:dm("Transition","TransitionStart"),transitioncancel:dm("Transition","TransitionCancel"),transitionend:dm("Transition","TransitionEnd")},IA={},jI={};Qr&&(jI=document.createElement("div").style,"AnimationEvent"in window||(delete hp.animationend.animation,delete hp.animationiteration.animation,delete hp.animationstart.animation),"TransitionEvent"in window||delete hp.transitionend.transition);function hm(m){if(IA[m])return IA[m];if(!hp[m])return m;var b=hp[m],S;for(S in b)if(b.hasOwnProperty(S)&&S in jI)return IA[m]=b[S];return m}var DI=hm("animationend"),RI=hm("animationiteration"),FI=hm("animationstart"),jse=hm("transitionrun"),Dse=hm("transitionstart"),Rse=hm("transitioncancel"),LI=hm("transitionend"),OI=new Map,zA="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");zA.push("scrollEnd");function Pl(m,b){OI.set(m,b),pt(b,[m])}var Z0=typeof reportError=="function"?reportError:function(m){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var b=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof m=="object"&&m!==null&&typeof m.message=="string"?String(m.message):String(m),error:m});if(!window.dispatchEvent(b))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",m);return}console.error(m)},zo=[],mp=0,UA=0;function J0(){for(var m=mp,b=UA=mp=0;b<m;){var S=zo[b];zo[b++]=null;var T=zo[b];zo[b++]=null;var F=zo[b];zo[b++]=null;var I=zo[b];if(zo[b++]=null,T!==null&&F!==null){var re=T.pending;re===null?F.next=F:(F.next=re.next,re.next=F),T.pending=F}I!==0&&II(S,F,I)}}function ew(m,b,S,T){zo[mp++]=m,zo[mp++]=b,zo[mp++]=S,zo[mp++]=T,UA|=T,m.lanes|=T,m=m.alternate,m!==null&&(m.lanes|=T)}function BA(m,b,S,T){return ew(m,b,S,T),tw(m)}function mm(m,b){return ew(m,null,null,b),tw(m)}function II(m,b,S){m.lanes|=S;var T=m.alternate;T!==null&&(T.lanes|=S);for(var F=!1,I=m.return;I!==null;)I.childLanes|=S,T=I.alternate,T!==null&&(T.childLanes|=S),I.tag===22&&(m=I.stateNode,m===null||m._visibility&1||(F=!0)),m=I,I=I.return;return m.tag===3?(I=m.stateNode,F&&b!==null&&(F=31-ge(S),m=I.hiddenUpdates,T=m[F],T===null?m[F]=[b]:T.push(b),b.lane=S|536870912),I):null}function tw(m){if(50<zx)throw zx=0,YT=null,Error(r(185));for(var b=m.return;b!==null;)m=b,b=m.return;return m.tag===3?m.stateNode:null}var fp={};function Fse(m,b,S,T){this.tag=m,this.key=S,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=b,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=T,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function go(m,b,S,T){return new Fse(m,b,S,T)}function HA(m){return m=m.prototype,!(!m||!m.isReactComponent)}function Qc(m,b){var S=m.alternate;return S===null?(S=go(m.tag,b,m.key,m.mode),S.elementType=m.elementType,S.type=m.type,S.stateNode=m.stateNode,S.alternate=m,m.alternate=S):(S.pendingProps=b,S.type=m.type,S.flags=0,S.subtreeFlags=0,S.deletions=null),S.flags=m.flags&65011712,S.childLanes=m.childLanes,S.lanes=m.lanes,S.child=m.child,S.memoizedProps=m.memoizedProps,S.memoizedState=m.memoizedState,S.updateQueue=m.updateQueue,b=m.dependencies,S.dependencies=b===null?null:{lanes:b.lanes,firstContext:b.firstContext},S.sibling=m.sibling,S.index=m.index,S.ref=m.ref,S.refCleanup=m.refCleanup,S}function zI(m,b){m.flags&=65011714;var S=m.alternate;return S===null?(m.childLanes=0,m.lanes=b,m.child=null,m.subtreeFlags=0,m.memoizedProps=null,m.memoizedState=null,m.updateQueue=null,m.dependencies=null,m.stateNode=null):(m.childLanes=S.childLanes,m.lanes=S.lanes,m.child=S.child,m.subtreeFlags=0,m.deletions=null,m.memoizedProps=S.memoizedProps,m.memoizedState=S.memoizedState,m.updateQueue=S.updateQueue,m.type=S.type,b=S.dependencies,m.dependencies=b===null?null:{lanes:b.lanes,firstContext:b.firstContext}),m}function nw(m,b,S,T,F,I){var re=0;if(T=m,typeof m=="function")HA(m)&&(re=1);else if(typeof m=="string")re=Uoe(m,S,Z.current)?26:m==="html"||m==="head"||m==="body"?27:5;else e:switch(m){case P:return m=go(31,S,b,F),m.elementType=P,m.lanes=I,m;case v:return fm(S.children,F,I,b);case g:re=8,F|=24;break;case y:return m=go(12,S,b,F|2),m.elementType=y,m.lanes=I,m;case A:return m=go(13,S,b,F),m.elementType=A,m.lanes=I,m;case M:return m=go(19,S,b,F),m.elementType=M,m.lanes=I,m;default:if(typeof m=="object"&&m!==null)switch(m.$$typeof){case N:re=10;break e;case _:re=9;break e;case k:re=11;break e;case C:re=14;break e;case j:re=16,T=null;break e}re=29,S=Error(r(130,m===null?"null":typeof m,"")),T=null}return b=go(re,S,b,F),b.elementType=m,b.type=T,b.lanes=I,b}function fm(m,b,S,T){return m=go(7,m,T,b),m.lanes=S,m}function $A(m,b,S){return m=go(6,m,null,b),m.lanes=S,m}function UI(m){var b=go(18,null,null,0);return b.stateNode=m,b}function VA(m,b,S){return b=go(4,m.children!==null?m.children:[],m.key,b),b.lanes=S,b.stateNode={containerInfo:m.containerInfo,pendingChildren:null,implementation:m.implementation},b}var BI=new WeakMap;function Uo(m,b){if(typeof m=="object"&&m!==null){var S=BI.get(m);return S!==void 0?S:(b={value:m,source:b,stack:se(b)},BI.set(m,b),b)}return{value:m,source:b,stack:se(b)}}var pp=[],gp=0,rw=null,xx=0,Bo=[],Ho=0,vd=null,oc=1,lc="";function Zc(m,b){pp[gp++]=xx,pp[gp++]=rw,rw=m,xx=b}function HI(m,b,S){Bo[Ho++]=oc,Bo[Ho++]=lc,Bo[Ho++]=vd,vd=m;var T=oc;m=lc;var F=32-ge(T)-1;T&=~(1<<F),S+=1;var I=32-ge(b)+F;if(30<I){var re=F-F%5;I=(T&(1<<re)-1).toString(32),T>>=re,F-=re,oc=1<<32-ge(b)+F|S<<F|T,lc=I+m}else oc=1<<I|S<<F|T,lc=m}function qA(m){m.return!==null&&(Zc(m,1),HI(m,1,0))}function GA(m){for(;m===rw;)rw=pp[--gp],pp[gp]=null,xx=pp[--gp],pp[gp]=null;for(;m===vd;)vd=Bo[--Ho],Bo[Ho]=null,lc=Bo[--Ho],Bo[Ho]=null,oc=Bo[--Ho],Bo[Ho]=null}function $I(m,b){Bo[Ho++]=oc,Bo[Ho++]=lc,Bo[Ho++]=vd,oc=b.id,lc=b.overflow,vd=m}var zi=null,Zr=null,nr=!1,wd=null,$o=!1,WA=Error(r(519));function Sd(m){var b=Error(r(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw yx(Uo(b,m)),WA}function VI(m){var b=m.stateNode,S=m.type,T=m.memoizedProps;switch(b[En]=m,b[dr]=T,S){case"dialog":Xn("cancel",b),Xn("close",b);break;case"iframe":case"object":case"embed":Xn("load",b);break;case"video":case"audio":for(S=0;S<Bx.length;S++)Xn(Bx[S],b);break;case"source":Xn("error",b);break;case"img":case"image":case"link":Xn("error",b),Xn("load",b);break;case"details":Xn("toggle",b);break;case"input":Xn("invalid",b),Sn(b,T.value,T.defaultValue,T.checked,T.defaultChecked,T.type,T.name,!0);break;case"select":Xn("invalid",b);break;case"textarea":Xn("invalid",b),xt(b,T.value,T.defaultValue,T.children)}S=T.children,typeof S!="string"&&typeof S!="number"&&typeof S!="bigint"||b.textContent===""+S||T.suppressHydrationWarning===!0||oU(b.textContent,S)?(T.popover!=null&&(Xn("beforetoggle",b),Xn("toggle",b)),T.onScroll!=null&&Xn("scroll",b),T.onScrollEnd!=null&&Xn("scrollend",b),T.onClick!=null&&(b.onclick=Vt),b=!0):b=!1,b||Sd(m,!0)}function qI(m){for(zi=m.return;zi;)switch(zi.tag){case 5:case 31:case 13:$o=!1;return;case 27:case 3:$o=!0;return;default:zi=zi.return}}function bp(m){if(m!==zi)return!1;if(!nr)return qI(m),nr=!0,!1;var b=m.tag,S;if((S=b!==3&&b!==27)&&((S=b===5)&&(S=m.type,S=!(S!=="form"&&S!=="button")||dM(m.type,m.memoizedProps)),S=!S),S&&Zr&&Sd(m),qI(m),b===13){if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(r(317));Zr=gU(m)}else if(b===31){if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(r(317));Zr=gU(m)}else b===27?(b=Zr,Ld(m.type)?(m=gM,gM=null,Zr=m):Zr=b):Zr=zi?qo(m.stateNode.nextSibling):null;return!0}function pm(){Zr=zi=null,nr=!1}function KA(){var m=wd;return m!==null&&(Vs===null?Vs=m:Vs.push.apply(Vs,m),wd=null),m}function yx(m){wd===null?wd=[m]:wd.push(m)}var XA=H(null),gm=null,Jc=null;function _d(m,b,S){te(XA,b._currentValue),b._currentValue=S}function eu(m){m._currentValue=XA.current,K(XA)}function YA(m,b,S){for(;m!==null;){var T=m.alternate;if((m.childLanes&b)!==b?(m.childLanes|=b,T!==null&&(T.childLanes|=b)):T!==null&&(T.childLanes&b)!==b&&(T.childLanes|=b),m===S)break;m=m.return}}function QA(m,b,S,T){var F=m.child;for(F!==null&&(F.return=m);F!==null;){var I=F.dependencies;if(I!==null){var re=F.child;I=I.firstContext;e:for(;I!==null;){var Pe=I;I=F;for(var Ve=0;Ve<b.length;Ve++)if(Pe.context===b[Ve]){I.lanes|=S,Pe=I.alternate,Pe!==null&&(Pe.lanes|=S),YA(I.return,S,m),T||(re=null);break e}I=Pe.next}}else if(F.tag===18){if(re=F.return,re===null)throw Error(r(341));re.lanes|=S,I=re.alternate,I!==null&&(I.lanes|=S),YA(re,S,m),re=null}else re=F.child;if(re!==null)re.return=F;else for(re=F;re!==null;){if(re===m){re=null;break}if(F=re.sibling,F!==null){F.return=re.return,re=F;break}re=re.return}F=re}}function xp(m,b,S,T){m=null;for(var F=b,I=!1;F!==null;){if(!I){if((F.flags&524288)!==0)I=!0;else if((F.flags&262144)!==0)break}if(F.tag===10){var re=F.alternate;if(re===null)throw Error(r(387));if(re=re.memoizedProps,re!==null){var Pe=F.type;po(F.pendingProps.value,re.value)||(m!==null?m.push(Pe):m=[Pe])}}else if(F===ee.current){if(re=F.alternate,re===null)throw Error(r(387));re.memoizedState.memoizedState!==F.memoizedState.memoizedState&&(m!==null?m.push(Gx):m=[Gx])}F=F.return}m!==null&&QA(b,m,S,T),b.flags|=262144}function aw(m){for(m=m.firstContext;m!==null;){if(!po(m.context._currentValue,m.memoizedValue))return!0;m=m.next}return!1}function bm(m){gm=m,Jc=null,m=m.dependencies,m!==null&&(m.firstContext=null)}function Ui(m){return GI(gm,m)}function iw(m,b){return gm===null&&bm(m),GI(m,b)}function GI(m,b){var S=b._currentValue;if(b={context:b,memoizedValue:S,next:null},Jc===null){if(m===null)throw Error(r(308));Jc=b,m.dependencies={lanes:0,firstContext:b},m.flags|=524288}else Jc=Jc.next=b;return S}var Lse=typeof AbortController<"u"?AbortController:function(){var m=[],b=this.signal={aborted:!1,addEventListener:function(S,T){m.push(T)}};this.abort=function(){b.aborted=!0,m.forEach(function(S){return S()})}},Ose=t.unstable_scheduleCallback,Ise=t.unstable_NormalPriority,Ga={$$typeof:N,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function ZA(){return{controller:new Lse,data:new Map,refCount:0}}function vx(m){m.refCount--,m.refCount===0&&Ose(Ise,function(){m.controller.abort()})}var wx=null,JA=0,yp=0,vp=null;function zse(m,b){if(wx===null){var S=wx=[];JA=0,yp=nM(),vp={status:"pending",value:void 0,then:function(T){S.push(T)}}}return JA++,b.then(WI,WI),b}function WI(){if(--JA===0&&wx!==null){vp!==null&&(vp.status="fulfilled");var m=wx;wx=null,yp=0,vp=null;for(var b=0;b<m.length;b++)(0,m[b])()}}function Use(m,b){var S=[],T={status:"pending",value:null,reason:null,then:function(F){S.push(F)}};return m.then(function(){T.status="fulfilled",T.value=b;for(var F=0;F<S.length;F++)(0,S[F])(b)},function(F){for(T.status="rejected",T.reason=F,F=0;F<S.length;F++)(0,S[F])(void 0)}),T}var KI=G.S;G.S=function(m,b){E5=R(),typeof b=="object"&&b!==null&&typeof b.then=="function"&&zse(m,b),KI!==null&&KI(m,b)};var xm=H(null);function eT(){var m=xm.current;return m!==null?m:Br.pooledCache}function sw(m,b){b===null?te(xm,xm.current):te(xm,b.pool)}function XI(){var m=eT();return m===null?null:{parent:Ga._currentValue,pool:m}}var wp=Error(r(460)),tT=Error(r(474)),ow=Error(r(542)),lw={then:function(){}};function YI(m){return m=m.status,m==="fulfilled"||m==="rejected"}function QI(m,b,S){switch(S=m[S],S===void 0?m.push(b):S!==b&&(b.then(Vt,Vt),b=S),b.status){case"fulfilled":return b.value;case"rejected":throw m=b.reason,JI(m),m;default:if(typeof b.status=="string")b.then(Vt,Vt);else{if(m=Br,m!==null&&100<m.shellSuspendCounter)throw Error(r(482));m=b,m.status="pending",m.then(function(T){if(b.status==="pending"){var F=b;F.status="fulfilled",F.value=T}},function(T){if(b.status==="pending"){var F=b;F.status="rejected",F.reason=T}})}switch(b.status){case"fulfilled":return b.value;case"rejected":throw m=b.reason,JI(m),m}throw vm=b,wp}}function ym(m){try{var b=m._init;return b(m._payload)}catch(S){throw S!==null&&typeof S=="object"&&typeof S.then=="function"?(vm=S,wp):S}}var vm=null;function ZI(){if(vm===null)throw Error(r(459));var m=vm;return vm=null,m}function JI(m){if(m===wp||m===ow)throw Error(r(483))}var Sp=null,Sx=0;function cw(m){var b=Sx;return Sx+=1,Sp===null&&(Sp=[]),QI(Sp,m,b)}function _x(m,b){b=b.props.ref,m.ref=b!==void 0?b:null}function uw(m,b){throw b.$$typeof===f?Error(r(525)):(m=Object.prototype.toString.call(b),Error(r(31,m==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":m)))}function ez(m){function b(rt,Qe){if(m){var ut=rt.deletions;ut===null?(rt.deletions=[Qe],rt.flags|=16):ut.push(Qe)}}function S(rt,Qe){if(!m)return null;for(;Qe!==null;)b(rt,Qe),Qe=Qe.sibling;return null}function T(rt){for(var Qe=new Map;rt!==null;)rt.key!==null?Qe.set(rt.key,rt):Qe.set(rt.index,rt),rt=rt.sibling;return Qe}function F(rt,Qe){return rt=Qc(rt,Qe),rt.index=0,rt.sibling=null,rt}function I(rt,Qe,ut){return rt.index=ut,m?(ut=rt.alternate,ut!==null?(ut=ut.index,ut<Qe?(rt.flags|=67108866,Qe):ut):(rt.flags|=67108866,Qe)):(rt.flags|=1048576,Qe)}function re(rt){return m&&rt.alternate===null&&(rt.flags|=67108866),rt}function Pe(rt,Qe,ut,St){return Qe===null||Qe.tag!==6?(Qe=$A(ut,rt.mode,St),Qe.return=rt,Qe):(Qe=F(Qe,ut),Qe.return=rt,Qe)}function Ve(rt,Qe,ut,St){var on=ut.type;return on===v?vt(rt,Qe,ut.props.children,St,ut.key):Qe!==null&&(Qe.elementType===on||typeof on=="object"&&on!==null&&on.$$typeof===j&&ym(on)===Qe.type)?(Qe=F(Qe,ut.props),_x(Qe,ut),Qe.return=rt,Qe):(Qe=nw(ut.type,ut.key,ut.props,null,rt.mode,St),_x(Qe,ut),Qe.return=rt,Qe)}function dt(rt,Qe,ut,St){return Qe===null||Qe.tag!==4||Qe.stateNode.containerInfo!==ut.containerInfo||Qe.stateNode.implementation!==ut.implementation?(Qe=VA(ut,rt.mode,St),Qe.return=rt,Qe):(Qe=F(Qe,ut.children||[]),Qe.return=rt,Qe)}function vt(rt,Qe,ut,St,on){return Qe===null||Qe.tag!==7?(Qe=fm(ut,rt.mode,St,on),Qe.return=rt,Qe):(Qe=F(Qe,ut),Qe.return=rt,Qe)}function Ct(rt,Qe,ut){if(typeof Qe=="string"&&Qe!==""||typeof Qe=="number"||typeof Qe=="bigint")return Qe=$A(""+Qe,rt.mode,ut),Qe.return=rt,Qe;if(typeof Qe=="object"&&Qe!==null){switch(Qe.$$typeof){case p:return ut=nw(Qe.type,Qe.key,Qe.props,null,rt.mode,ut),_x(ut,Qe),ut.return=rt,ut;case x:return Qe=VA(Qe,rt.mode,ut),Qe.return=rt,Qe;case j:return Qe=ym(Qe),Ct(rt,Qe,ut)}if($(Qe)||L(Qe))return Qe=fm(Qe,rt.mode,ut,null),Qe.return=rt,Qe;if(typeof Qe.then=="function")return Ct(rt,cw(Qe),ut);if(Qe.$$typeof===N)return Ct(rt,iw(rt,Qe),ut);uw(rt,Qe)}return null}function mt(rt,Qe,ut,St){var on=Qe!==null?Qe.key:null;if(typeof ut=="string"&&ut!==""||typeof ut=="number"||typeof ut=="bigint")return on!==null?null:Pe(rt,Qe,""+ut,St);if(typeof ut=="object"&&ut!==null){switch(ut.$$typeof){case p:return ut.key===on?Ve(rt,Qe,ut,St):null;case x:return ut.key===on?dt(rt,Qe,ut,St):null;case j:return ut=ym(ut),mt(rt,Qe,ut,St)}if($(ut)||L(ut))return on!==null?null:vt(rt,Qe,ut,St,null);if(typeof ut.then=="function")return mt(rt,Qe,cw(ut),St);if(ut.$$typeof===N)return mt(rt,Qe,iw(rt,ut),St);uw(rt,ut)}return null}function gt(rt,Qe,ut,St,on){if(typeof St=="string"&&St!==""||typeof St=="number"||typeof St=="bigint")return rt=rt.get(ut)||null,Pe(Qe,rt,""+St,on);if(typeof St=="object"&&St!==null){switch(St.$$typeof){case p:return rt=rt.get(St.key===null?ut:St.key)||null,Ve(Qe,rt,St,on);case x:return rt=rt.get(St.key===null?ut:St.key)||null,dt(Qe,rt,St,on);case j:return St=ym(St),gt(rt,Qe,ut,St,on)}if($(St)||L(St))return rt=rt.get(ut)||null,vt(Qe,rt,St,on,null);if(typeof St.then=="function")return gt(rt,Qe,ut,cw(St),on);if(St.$$typeof===N)return gt(rt,Qe,ut,iw(Qe,St),on);uw(Qe,St)}return null}function Qt(rt,Qe,ut,St){for(var on=null,or=null,tn=Qe,jn=Qe=0,er=null;tn!==null&&jn<ut.length;jn++){tn.index>jn?(er=tn,tn=null):er=tn.sibling;var lr=mt(rt,tn,ut[jn],St);if(lr===null){tn===null&&(tn=er);break}m&&tn&&lr.alternate===null&&b(rt,tn),Qe=I(lr,Qe,jn),or===null?on=lr:or.sibling=lr,or=lr,tn=er}if(jn===ut.length)return S(rt,tn),nr&&Zc(rt,jn),on;if(tn===null){for(;jn<ut.length;jn++)tn=Ct(rt,ut[jn],St),tn!==null&&(Qe=I(tn,Qe,jn),or===null?on=tn:or.sibling=tn,or=tn);return nr&&Zc(rt,jn),on}for(tn=T(tn);jn<ut.length;jn++)er=gt(tn,rt,jn,ut[jn],St),er!==null&&(m&&er.alternate!==null&&tn.delete(er.key===null?jn:er.key),Qe=I(er,Qe,jn),or===null?on=er:or.sibling=er,or=er);return m&&tn.forEach(function(Bd){return b(rt,Bd)}),nr&&Zc(rt,jn),on}function hn(rt,Qe,ut,St){if(ut==null)throw Error(r(151));for(var on=null,or=null,tn=Qe,jn=Qe=0,er=null,lr=ut.next();tn!==null&&!lr.done;jn++,lr=ut.next()){tn.index>jn?(er=tn,tn=null):er=tn.sibling;var Bd=mt(rt,tn,lr.value,St);if(Bd===null){tn===null&&(tn=er);break}m&&tn&&Bd.alternate===null&&b(rt,tn),Qe=I(Bd,Qe,jn),or===null?on=Bd:or.sibling=Bd,or=Bd,tn=er}if(lr.done)return S(rt,tn),nr&&Zc(rt,jn),on;if(tn===null){for(;!lr.done;jn++,lr=ut.next())lr=Ct(rt,lr.value,St),lr!==null&&(Qe=I(lr,Qe,jn),or===null?on=lr:or.sibling=lr,or=lr);return nr&&Zc(rt,jn),on}for(tn=T(tn);!lr.done;jn++,lr=ut.next())lr=gt(tn,rt,jn,lr.value,St),lr!==null&&(m&&lr.alternate!==null&&tn.delete(lr.key===null?jn:lr.key),Qe=I(lr,Qe,jn),or===null?on=lr:or.sibling=lr,or=lr);return m&&tn.forEach(function(Qoe){return b(rt,Qoe)}),nr&&Zc(rt,jn),on}function Er(rt,Qe,ut,St){if(typeof ut=="object"&&ut!==null&&ut.type===v&&ut.key===null&&(ut=ut.props.children),typeof ut=="object"&&ut!==null){switch(ut.$$typeof){case p:e:{for(var on=ut.key;Qe!==null;){if(Qe.key===on){if(on=ut.type,on===v){if(Qe.tag===7){S(rt,Qe.sibling),St=F(Qe,ut.props.children),St.return=rt,rt=St;break e}}else if(Qe.elementType===on||typeof on=="object"&&on!==null&&on.$$typeof===j&&ym(on)===Qe.type){S(rt,Qe.sibling),St=F(Qe,ut.props),_x(St,ut),St.return=rt,rt=St;break e}S(rt,Qe);break}else b(rt,Qe);Qe=Qe.sibling}ut.type===v?(St=fm(ut.props.children,rt.mode,St,ut.key),St.return=rt,rt=St):(St=nw(ut.type,ut.key,ut.props,null,rt.mode,St),_x(St,ut),St.return=rt,rt=St)}return re(rt);case x:e:{for(on=ut.key;Qe!==null;){if(Qe.key===on)if(Qe.tag===4&&Qe.stateNode.containerInfo===ut.containerInfo&&Qe.stateNode.implementation===ut.implementation){S(rt,Qe.sibling),St=F(Qe,ut.children||[]),St.return=rt,rt=St;break e}else{S(rt,Qe);break}else b(rt,Qe);Qe=Qe.sibling}St=VA(ut,rt.mode,St),St.return=rt,rt=St}return re(rt);case j:return ut=ym(ut),Er(rt,Qe,ut,St)}if($(ut))return Qt(rt,Qe,ut,St);if(L(ut)){if(on=L(ut),typeof on!="function")throw Error(r(150));return ut=on.call(ut),hn(rt,Qe,ut,St)}if(typeof ut.then=="function")return Er(rt,Qe,cw(ut),St);if(ut.$$typeof===N)return Er(rt,Qe,iw(rt,ut),St);uw(rt,ut)}return typeof ut=="string"&&ut!==""||typeof ut=="number"||typeof ut=="bigint"?(ut=""+ut,Qe!==null&&Qe.tag===6?(S(rt,Qe.sibling),St=F(Qe,ut),St.return=rt,rt=St):(S(rt,Qe),St=$A(ut,rt.mode,St),St.return=rt,rt=St),re(rt)):S(rt,Qe)}return function(rt,Qe,ut,St){try{Sx=0;var on=Er(rt,Qe,ut,St);return Sp=null,on}catch(tn){if(tn===wp||tn===ow)throw tn;var or=go(29,tn,null,rt.mode);return or.lanes=St,or.return=rt,or}}}var wm=ez(!0),tz=ez(!1),Nd=!1;function nT(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function rT(m,b){m=m.updateQueue,b.updateQueue===m&&(b.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function Cd(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function kd(m,b,S){var T=m.updateQueue;if(T===null)return null;if(T=T.shared,(fr&2)!==0){var F=T.pending;return F===null?b.next=b:(b.next=F.next,F.next=b),T.pending=b,b=tw(m),II(m,null,S),b}return ew(m,T,b,S),tw(m)}function Nx(m,b,S){if(b=b.updateQueue,b!==null&&(b=b.shared,(S&4194048)!==0)){var T=b.lanes;T&=m.pendingLanes,S|=T,b.lanes=S,bt(m,S)}}function aT(m,b){var S=m.updateQueue,T=m.alternate;if(T!==null&&(T=T.updateQueue,S===T)){var F=null,I=null;if(S=S.firstBaseUpdate,S!==null){do{var re={lane:S.lane,tag:S.tag,payload:S.payload,callback:null,next:null};I===null?F=I=re:I=I.next=re,S=S.next}while(S!==null);I===null?F=I=b:I=I.next=b}else F=I=b;S={baseState:T.baseState,firstBaseUpdate:F,lastBaseUpdate:I,shared:T.shared,callbacks:T.callbacks},m.updateQueue=S;return}m=S.lastBaseUpdate,m===null?S.firstBaseUpdate=b:m.next=b,S.lastBaseUpdate=b}var iT=!1;function Cx(){if(iT){var m=vp;if(m!==null)throw m}}function kx(m,b,S,T){iT=!1;var F=m.updateQueue;Nd=!1;var I=F.firstBaseUpdate,re=F.lastBaseUpdate,Pe=F.shared.pending;if(Pe!==null){F.shared.pending=null;var Ve=Pe,dt=Ve.next;Ve.next=null,re===null?I=dt:re.next=dt,re=Ve;var vt=m.alternate;vt!==null&&(vt=vt.updateQueue,Pe=vt.lastBaseUpdate,Pe!==re&&(Pe===null?vt.firstBaseUpdate=dt:Pe.next=dt,vt.lastBaseUpdate=Ve))}if(I!==null){var Ct=F.baseState;re=0,vt=dt=Ve=null,Pe=I;do{var mt=Pe.lane&-536870913,gt=mt!==Pe.lane;if(gt?(Jn&mt)===mt:(T&mt)===mt){mt!==0&&mt===yp&&(iT=!0),vt!==null&&(vt=vt.next={lane:0,tag:Pe.tag,payload:Pe.payload,callback:null,next:null});e:{var Qt=m,hn=Pe;mt=b;var Er=S;switch(hn.tag){case 1:if(Qt=hn.payload,typeof Qt=="function"){Ct=Qt.call(Er,Ct,mt);break e}Ct=Qt;break e;case 3:Qt.flags=Qt.flags&-65537|128;case 0:if(Qt=hn.payload,mt=typeof Qt=="function"?Qt.call(Er,Ct,mt):Qt,mt==null)break e;Ct=h({},Ct,mt);break e;case 2:Nd=!0}}mt=Pe.callback,mt!==null&&(m.flags|=64,gt&&(m.flags|=8192),gt=F.callbacks,gt===null?F.callbacks=[mt]:gt.push(mt))}else gt={lane:mt,tag:Pe.tag,payload:Pe.payload,callback:Pe.callback,next:null},vt===null?(dt=vt=gt,Ve=Ct):vt=vt.next=gt,re|=mt;if(Pe=Pe.next,Pe===null){if(Pe=F.shared.pending,Pe===null)break;gt=Pe,Pe=gt.next,gt.next=null,F.lastBaseUpdate=gt,F.shared.pending=null}}while(!0);vt===null&&(Ve=Ct),F.baseState=Ve,F.firstBaseUpdate=dt,F.lastBaseUpdate=vt,I===null&&(F.shared.lanes=0),Ed|=re,m.lanes=re,m.memoizedState=Ct}}function nz(m,b){if(typeof m!="function")throw Error(r(191,m));m.call(b)}function rz(m,b){var S=m.callbacks;if(S!==null)for(m.callbacks=null,m=0;m<S.length;m++)nz(S[m],b)}var _p=H(null),dw=H(0);function az(m,b){m=cu,te(dw,m),te(_p,b),cu=m|b.baseLanes}function sT(){te(dw,cu),te(_p,_p.current)}function oT(){cu=dw.current,K(_p),K(dw)}var bo=H(null),Vo=null;function Ad(m){var b=m.alternate;te(Ia,Ia.current&1),te(bo,m),Vo===null&&(b===null||_p.current!==null||b.memoizedState!==null)&&(Vo=m)}function lT(m){te(Ia,Ia.current),te(bo,m),Vo===null&&(Vo=m)}function iz(m){m.tag===22?(te(Ia,Ia.current),te(bo,m),Vo===null&&(Vo=m)):Td()}function Td(){te(Ia,Ia.current),te(bo,bo.current)}function xo(m){K(bo),Vo===m&&(Vo=null),K(Ia)}var Ia=H(0);function hw(m){for(var b=m;b!==null;){if(b.tag===13){var S=b.memoizedState;if(S!==null&&(S=S.dehydrated,S===null||fM(S)||pM(S)))return b}else if(b.tag===19&&(b.memoizedProps.revealOrder==="forwards"||b.memoizedProps.revealOrder==="backwards"||b.memoizedProps.revealOrder==="unstable_legacy-backwards"||b.memoizedProps.revealOrder==="together")){if((b.flags&128)!==0)return b}else if(b.child!==null){b.child.return=b,b=b.child;continue}if(b===m)break;for(;b.sibling===null;){if(b.return===null||b.return===m)return null;b=b.return}b.sibling.return=b.return,b=b.sibling}return null}var tu=0,Mn=null,Mr=null,Wa=null,mw=!1,Np=!1,Sm=!1,fw=0,Ax=0,Cp=null,Bse=0;function _a(){throw Error(r(321))}function cT(m,b){if(b===null)return!1;for(var S=0;S<b.length&&S<m.length;S++)if(!po(m[S],b[S]))return!1;return!0}function uT(m,b,S,T,F,I){return tu=I,Mn=b,b.memoizedState=null,b.updateQueue=null,b.lanes=0,G.H=m===null||m.memoizedState===null?Hz:CT,Sm=!1,I=S(T,F),Sm=!1,Np&&(I=oz(b,S,T,F)),sz(m),I}function sz(m){G.H=Px;var b=Mr!==null&&Mr.next!==null;if(tu=0,Wa=Mr=Mn=null,mw=!1,Ax=0,Cp=null,b)throw Error(r(300));m===null||Ka||(m=m.dependencies,m!==null&&aw(m)&&(Ka=!0))}function oz(m,b,S,T){Mn=m;var F=0;do{if(Np&&(Cp=null),Ax=0,Np=!1,25<=F)throw Error(r(301));if(F+=1,Wa=Mr=null,m.updateQueue!=null){var I=m.updateQueue;I.lastEffect=null,I.events=null,I.stores=null,I.memoCache!=null&&(I.memoCache.index=0)}G.H=$z,I=b(S,T)}while(Np);return I}function Hse(){var m=G.H,b=m.useState()[0];return b=typeof b.then=="function"?Tx(b):b,m=m.useState()[0],(Mr!==null?Mr.memoizedState:null)!==m&&(Mn.flags|=1024),b}function dT(){var m=fw!==0;return fw=0,m}function hT(m,b,S){b.updateQueue=m.updateQueue,b.flags&=-2053,m.lanes&=~S}function mT(m){if(mw){for(m=m.memoizedState;m!==null;){var b=m.queue;b!==null&&(b.pending=null),m=m.next}mw=!1}tu=0,Wa=Mr=Mn=null,Np=!1,Ax=fw=0,Cp=null}function Ns(){var m={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Wa===null?Mn.memoizedState=Wa=m:Wa=Wa.next=m,Wa}function za(){if(Mr===null){var m=Mn.alternate;m=m!==null?m.memoizedState:null}else m=Mr.next;var b=Wa===null?Mn.memoizedState:Wa.next;if(b!==null)Wa=b,Mr=m;else{if(m===null)throw Mn.alternate===null?Error(r(467)):Error(r(310));Mr=m,m={memoizedState:Mr.memoizedState,baseState:Mr.baseState,baseQueue:Mr.baseQueue,queue:Mr.queue,next:null},Wa===null?Mn.memoizedState=Wa=m:Wa=Wa.next=m}return Wa}function pw(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Tx(m){var b=Ax;return Ax+=1,Cp===null&&(Cp=[]),m=QI(Cp,m,b),b=Mn,(Wa===null?b.memoizedState:Wa.next)===null&&(b=b.alternate,G.H=b===null||b.memoizedState===null?Hz:CT),m}function gw(m){if(m!==null&&typeof m=="object"){if(typeof m.then=="function")return Tx(m);if(m.$$typeof===N)return Ui(m)}throw Error(r(438,String(m)))}function fT(m){var b=null,S=Mn.updateQueue;if(S!==null&&(b=S.memoCache),b==null){var T=Mn.alternate;T!==null&&(T=T.updateQueue,T!==null&&(T=T.memoCache,T!=null&&(b={data:T.data.map(function(F){return F.slice()}),index:0})))}if(b==null&&(b={data:[],index:0}),S===null&&(S=pw(),Mn.updateQueue=S),S.memoCache=b,S=b.data[b.index],S===void 0)for(S=b.data[b.index]=Array(m),T=0;T<m;T++)S[T]=E;return b.index++,S}function nu(m,b){return typeof b=="function"?b(m):b}function bw(m){var b=za();return pT(b,Mr,m)}function pT(m,b,S){var T=m.queue;if(T===null)throw Error(r(311));T.lastRenderedReducer=S;var F=m.baseQueue,I=T.pending;if(I!==null){if(F!==null){var re=F.next;F.next=I.next,I.next=re}b.baseQueue=F=I,T.pending=null}if(I=m.baseState,F===null)m.memoizedState=I;else{b=F.next;var Pe=re=null,Ve=null,dt=b,vt=!1;do{var Ct=dt.lane&-536870913;if(Ct!==dt.lane?(Jn&Ct)===Ct:(tu&Ct)===Ct){var mt=dt.revertLane;if(mt===0)Ve!==null&&(Ve=Ve.next={lane:0,revertLane:0,gesture:null,action:dt.action,hasEagerState:dt.hasEagerState,eagerState:dt.eagerState,next:null}),Ct===yp&&(vt=!0);else if((tu&mt)===mt){dt=dt.next,mt===yp&&(vt=!0);continue}else Ct={lane:0,revertLane:dt.revertLane,gesture:null,action:dt.action,hasEagerState:dt.hasEagerState,eagerState:dt.eagerState,next:null},Ve===null?(Pe=Ve=Ct,re=I):Ve=Ve.next=Ct,Mn.lanes|=mt,Ed|=mt;Ct=dt.action,Sm&&S(I,Ct),I=dt.hasEagerState?dt.eagerState:S(I,Ct)}else mt={lane:Ct,revertLane:dt.revertLane,gesture:dt.gesture,action:dt.action,hasEagerState:dt.hasEagerState,eagerState:dt.eagerState,next:null},Ve===null?(Pe=Ve=mt,re=I):Ve=Ve.next=mt,Mn.lanes|=Ct,Ed|=Ct;dt=dt.next}while(dt!==null&&dt!==b);if(Ve===null?re=I:Ve.next=Pe,!po(I,m.memoizedState)&&(Ka=!0,vt&&(S=vp,S!==null)))throw S;m.memoizedState=I,m.baseState=re,m.baseQueue=Ve,T.lastRenderedState=I}return F===null&&(T.lanes=0),[m.memoizedState,T.dispatch]}function gT(m){var b=za(),S=b.queue;if(S===null)throw Error(r(311));S.lastRenderedReducer=m;var T=S.dispatch,F=S.pending,I=b.memoizedState;if(F!==null){S.pending=null;var re=F=F.next;do I=m(I,re.action),re=re.next;while(re!==F);po(I,b.memoizedState)||(Ka=!0),b.memoizedState=I,b.baseQueue===null&&(b.baseState=I),S.lastRenderedState=I}return[I,T]}function lz(m,b,S){var T=Mn,F=za(),I=nr;if(I){if(S===void 0)throw Error(r(407));S=S()}else S=b();var re=!po((Mr||F).memoizedState,S);if(re&&(F.memoizedState=S,Ka=!0),F=F.queue,yT(dz.bind(null,T,F,m),[m]),F.getSnapshot!==b||re||Wa!==null&&Wa.memoizedState.tag&1){if(T.flags|=2048,kp(9,{destroy:void 0},uz.bind(null,T,F,S,b),null),Br===null)throw Error(r(349));I||(tu&127)!==0||cz(T,b,S)}return S}function cz(m,b,S){m.flags|=16384,m={getSnapshot:b,value:S},b=Mn.updateQueue,b===null?(b=pw(),Mn.updateQueue=b,b.stores=[m]):(S=b.stores,S===null?b.stores=[m]:S.push(m))}function uz(m,b,S,T){b.value=S,b.getSnapshot=T,hz(b)&&mz(m)}function dz(m,b,S){return S(function(){hz(b)&&mz(m)})}function hz(m){var b=m.getSnapshot;m=m.value;try{var S=b();return!po(m,S)}catch{return!0}}function mz(m){var b=mm(m,2);b!==null&&qs(b,m,2)}function bT(m){var b=Ns();if(typeof m=="function"){var S=m;if(m=S(),Sm){ke(!0);try{S()}finally{ke(!1)}}}return b.memoizedState=b.baseState=m,b.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:nu,lastRenderedState:m},b}function fz(m,b,S,T){return m.baseState=S,pT(m,Mr,typeof T=="function"?T:nu)}function $se(m,b,S,T,F){if(vw(m))throw Error(r(485));if(m=b.action,m!==null){var I={payload:F,action:m,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(re){I.listeners.push(re)}};G.T!==null?S(!0):I.isTransition=!1,T(I),S=b.pending,S===null?(I.next=b.pending=I,pz(b,I)):(I.next=S.next,b.pending=S.next=I)}}function pz(m,b){var S=b.action,T=b.payload,F=m.state;if(b.isTransition){var I=G.T,re={};G.T=re;try{var Pe=S(F,T),Ve=G.S;Ve!==null&&Ve(re,Pe),gz(m,b,Pe)}catch(dt){xT(m,b,dt)}finally{I!==null&&re.types!==null&&(I.types=re.types),G.T=I}}else try{I=S(F,T),gz(m,b,I)}catch(dt){xT(m,b,dt)}}function gz(m,b,S){S!==null&&typeof S=="object"&&typeof S.then=="function"?S.then(function(T){bz(m,b,T)},function(T){return xT(m,b,T)}):bz(m,b,S)}function bz(m,b,S){b.status="fulfilled",b.value=S,xz(b),m.state=S,b=m.pending,b!==null&&(S=b.next,S===b?m.pending=null:(S=S.next,b.next=S,pz(m,S)))}function xT(m,b,S){var T=m.pending;if(m.pending=null,T!==null){T=T.next;do b.status="rejected",b.reason=S,xz(b),b=b.next;while(b!==T)}m.action=null}function xz(m){m=m.listeners;for(var b=0;b<m.length;b++)(0,m[b])()}function yz(m,b){return b}function vz(m,b){if(nr){var S=Br.formState;if(S!==null){e:{var T=Mn;if(nr){if(Zr){t:{for(var F=Zr,I=$o;F.nodeType!==8;){if(!I){F=null;break t}if(F=qo(F.nextSibling),F===null){F=null;break t}}I=F.data,F=I==="F!"||I==="F"?F:null}if(F){Zr=qo(F.nextSibling),T=F.data==="F!";break e}}Sd(T)}T=!1}T&&(b=S[0])}}return S=Ns(),S.memoizedState=S.baseState=b,T={pending:null,lanes:0,dispatch:null,lastRenderedReducer:yz,lastRenderedState:b},S.queue=T,S=zz.bind(null,Mn,T),T.dispatch=S,T=bT(!1),I=NT.bind(null,Mn,!1,T.queue),T=Ns(),F={state:b,dispatch:null,action:m,pending:null},T.queue=F,S=$se.bind(null,Mn,F,I,S),F.dispatch=S,T.memoizedState=m,[b,S,!1]}function wz(m){var b=za();return Sz(b,Mr,m)}function Sz(m,b,S){if(b=pT(m,b,yz)[0],m=bw(nu)[0],typeof b=="object"&&b!==null&&typeof b.then=="function")try{var T=Tx(b)}catch(re){throw re===wp?ow:re}else T=b;b=za();var F=b.queue,I=F.dispatch;return S!==b.memoizedState&&(Mn.flags|=2048,kp(9,{destroy:void 0},Vse.bind(null,F,S),null)),[T,I,m]}function Vse(m,b){m.action=b}function _z(m){var b=za(),S=Mr;if(S!==null)return Sz(b,S,m);za(),b=b.memoizedState,S=za();var T=S.queue.dispatch;return S.memoizedState=m,[b,T,!1]}function kp(m,b,S,T){return m={tag:m,create:S,deps:T,inst:b,next:null},b=Mn.updateQueue,b===null&&(b=pw(),Mn.updateQueue=b),S=b.lastEffect,S===null?b.lastEffect=m.next=m:(T=S.next,S.next=m,m.next=T,b.lastEffect=m),m}function Nz(){return za().memoizedState}function xw(m,b,S,T){var F=Ns();Mn.flags|=m,F.memoizedState=kp(1|b,{destroy:void 0},S,T===void 0?null:T)}function yw(m,b,S,T){var F=za();T=T===void 0?null:T;var I=F.memoizedState.inst;Mr!==null&&T!==null&&cT(T,Mr.memoizedState.deps)?F.memoizedState=kp(b,I,S,T):(Mn.flags|=m,F.memoizedState=kp(1|b,I,S,T))}function Cz(m,b){xw(8390656,8,m,b)}function yT(m,b){yw(2048,8,m,b)}function qse(m){Mn.flags|=4;var b=Mn.updateQueue;if(b===null)b=pw(),Mn.updateQueue=b,b.events=[m];else{var S=b.events;S===null?b.events=[m]:S.push(m)}}function kz(m){var b=za().memoizedState;return qse({ref:b,nextImpl:m}),function(){if((fr&2)!==0)throw Error(r(440));return b.impl.apply(void 0,arguments)}}function Az(m,b){return yw(4,2,m,b)}function Tz(m,b){return yw(4,4,m,b)}function Mz(m,b){if(typeof b=="function"){m=m();var S=b(m);return function(){typeof S=="function"?S():b(null)}}if(b!=null)return m=m(),b.current=m,function(){b.current=null}}function Pz(m,b,S){S=S!=null?S.concat([m]):null,yw(4,4,Mz.bind(null,b,m),S)}function vT(){}function Ez(m,b){var S=za();b=b===void 0?null:b;var T=S.memoizedState;return b!==null&&cT(b,T[1])?T[0]:(S.memoizedState=[m,b],m)}function jz(m,b){var S=za();b=b===void 0?null:b;var T=S.memoizedState;if(b!==null&&cT(b,T[1]))return T[0];if(T=m(),Sm){ke(!0);try{m()}finally{ke(!1)}}return S.memoizedState=[T,b],T}function wT(m,b,S){return S===void 0||(tu&1073741824)!==0&&(Jn&261930)===0?m.memoizedState=b:(m.memoizedState=S,m=D5(),Mn.lanes|=m,Ed|=m,S)}function Dz(m,b,S,T){return po(S,b)?S:_p.current!==null?(m=wT(m,S,T),po(m,b)||(Ka=!0),m):(tu&42)===0||(tu&1073741824)!==0&&(Jn&261930)===0?(Ka=!0,m.memoizedState=S):(m=D5(),Mn.lanes|=m,Ed|=m,b)}function Rz(m,b,S,T,F){var I=z.p;z.p=I!==0&&8>I?I:8;var re=G.T,Pe={};G.T=Pe,NT(m,!1,b,S);try{var Ve=F(),dt=G.S;if(dt!==null&&dt(Pe,Ve),Ve!==null&&typeof Ve=="object"&&typeof Ve.then=="function"){var vt=Use(Ve,T);Mx(m,b,vt,wo(m))}else Mx(m,b,T,wo(m))}catch(Ct){Mx(m,b,{then:function(){},status:"rejected",reason:Ct},wo())}finally{z.p=I,re!==null&&Pe.types!==null&&(re.types=Pe.types),G.T=re}}function Gse(){}function ST(m,b,S,T){if(m.tag!==5)throw Error(r(476));var F=Fz(m).queue;Rz(m,F,b,W,S===null?Gse:function(){return Lz(m),S(T)})}function Fz(m){var b=m.memoizedState;if(b!==null)return b;b={memoizedState:W,baseState:W,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nu,lastRenderedState:W},next:null};var S={};return b.next={memoizedState:S,baseState:S,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:nu,lastRenderedState:S},next:null},m.memoizedState=b,m=m.alternate,m!==null&&(m.memoizedState=b),b}function Lz(m){var b=Fz(m);b.next===null&&(b=m.alternate.memoizedState),Mx(m,b.next.queue,{},wo())}function _T(){return Ui(Gx)}function Oz(){return za().memoizedState}function Iz(){return za().memoizedState}function Wse(m){for(var b=m.return;b!==null;){switch(b.tag){case 24:case 3:var S=wo();m=Cd(S);var T=kd(b,m,S);T!==null&&(qs(T,b,S),Nx(T,b,S)),b={cache:ZA()},m.payload=b;return}b=b.return}}function Kse(m,b,S){var T=wo();S={lane:T,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null},vw(m)?Uz(b,S):(S=BA(m,b,S,T),S!==null&&(qs(S,m,T),Bz(S,b,T)))}function zz(m,b,S){var T=wo();Mx(m,b,S,T)}function Mx(m,b,S,T){var F={lane:T,revertLane:0,gesture:null,action:S,hasEagerState:!1,eagerState:null,next:null};if(vw(m))Uz(b,F);else{var I=m.alternate;if(m.lanes===0&&(I===null||I.lanes===0)&&(I=b.lastRenderedReducer,I!==null))try{var re=b.lastRenderedState,Pe=I(re,S);if(F.hasEagerState=!0,F.eagerState=Pe,po(Pe,re))return ew(m,b,F,0),Br===null&&J0(),!1}catch{}if(S=BA(m,b,F,T),S!==null)return qs(S,m,T),Bz(S,b,T),!0}return!1}function NT(m,b,S,T){if(T={lane:2,revertLane:nM(),gesture:null,action:T,hasEagerState:!1,eagerState:null,next:null},vw(m)){if(b)throw Error(r(479))}else b=BA(m,S,T,2),b!==null&&qs(b,m,2)}function vw(m){var b=m.alternate;return m===Mn||b!==null&&b===Mn}function Uz(m,b){Np=mw=!0;var S=m.pending;S===null?b.next=b:(b.next=S.next,S.next=b),m.pending=b}function Bz(m,b,S){if((S&4194048)!==0){var T=b.lanes;T&=m.pendingLanes,S|=T,b.lanes=S,bt(m,S)}}var Px={readContext:Ui,use:gw,useCallback:_a,useContext:_a,useEffect:_a,useImperativeHandle:_a,useLayoutEffect:_a,useInsertionEffect:_a,useMemo:_a,useReducer:_a,useRef:_a,useState:_a,useDebugValue:_a,useDeferredValue:_a,useTransition:_a,useSyncExternalStore:_a,useId:_a,useHostTransitionStatus:_a,useFormState:_a,useActionState:_a,useOptimistic:_a,useMemoCache:_a,useCacheRefresh:_a};Px.useEffectEvent=_a;var Hz={readContext:Ui,use:gw,useCallback:function(m,b){return Ns().memoizedState=[m,b===void 0?null:b],m},useContext:Ui,useEffect:Cz,useImperativeHandle:function(m,b,S){S=S!=null?S.concat([m]):null,xw(4194308,4,Mz.bind(null,b,m),S)},useLayoutEffect:function(m,b){return xw(4194308,4,m,b)},useInsertionEffect:function(m,b){xw(4,2,m,b)},useMemo:function(m,b){var S=Ns();b=b===void 0?null:b;var T=m();if(Sm){ke(!0);try{m()}finally{ke(!1)}}return S.memoizedState=[T,b],T},useReducer:function(m,b,S){var T=Ns();if(S!==void 0){var F=S(b);if(Sm){ke(!0);try{S(b)}finally{ke(!1)}}}else F=b;return T.memoizedState=T.baseState=F,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:F},T.queue=m,m=m.dispatch=Kse.bind(null,Mn,m),[T.memoizedState,m]},useRef:function(m){var b=Ns();return m={current:m},b.memoizedState=m},useState:function(m){m=bT(m);var b=m.queue,S=zz.bind(null,Mn,b);return b.dispatch=S,[m.memoizedState,S]},useDebugValue:vT,useDeferredValue:function(m,b){var S=Ns();return wT(S,m,b)},useTransition:function(){var m=bT(!1);return m=Rz.bind(null,Mn,m.queue,!0,!1),Ns().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,b,S){var T=Mn,F=Ns();if(nr){if(S===void 0)throw Error(r(407));S=S()}else{if(S=b(),Br===null)throw Error(r(349));(Jn&127)!==0||cz(T,b,S)}F.memoizedState=S;var I={value:S,getSnapshot:b};return F.queue=I,Cz(dz.bind(null,T,I,m),[m]),T.flags|=2048,kp(9,{destroy:void 0},uz.bind(null,T,I,S,b),null),S},useId:function(){var m=Ns(),b=Br.identifierPrefix;if(nr){var S=lc,T=oc;S=(T&~(1<<32-ge(T)-1)).toString(32)+S,b="_"+b+"R_"+S,S=fw++,0<S&&(b+="H"+S.toString(32)),b+="_"}else S=Bse++,b="_"+b+"r_"+S.toString(32)+"_";return m.memoizedState=b},useHostTransitionStatus:_T,useFormState:vz,useActionState:vz,useOptimistic:function(m){var b=Ns();b.memoizedState=b.baseState=m;var S={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return b.queue=S,b=NT.bind(null,Mn,!0,S),S.dispatch=b,[m,b]},useMemoCache:fT,useCacheRefresh:function(){return Ns().memoizedState=Wse.bind(null,Mn)},useEffectEvent:function(m){var b=Ns(),S={impl:m};return b.memoizedState=S,function(){if((fr&2)!==0)throw Error(r(440));return S.impl.apply(void 0,arguments)}}},CT={readContext:Ui,use:gw,useCallback:Ez,useContext:Ui,useEffect:yT,useImperativeHandle:Pz,useInsertionEffect:Az,useLayoutEffect:Tz,useMemo:jz,useReducer:bw,useRef:Nz,useState:function(){return bw(nu)},useDebugValue:vT,useDeferredValue:function(m,b){var S=za();return Dz(S,Mr.memoizedState,m,b)},useTransition:function(){var m=bw(nu)[0],b=za().memoizedState;return[typeof m=="boolean"?m:Tx(m),b]},useSyncExternalStore:lz,useId:Oz,useHostTransitionStatus:_T,useFormState:wz,useActionState:wz,useOptimistic:function(m,b){var S=za();return fz(S,Mr,m,b)},useMemoCache:fT,useCacheRefresh:Iz};CT.useEffectEvent=kz;var $z={readContext:Ui,use:gw,useCallback:Ez,useContext:Ui,useEffect:yT,useImperativeHandle:Pz,useInsertionEffect:Az,useLayoutEffect:Tz,useMemo:jz,useReducer:gT,useRef:Nz,useState:function(){return gT(nu)},useDebugValue:vT,useDeferredValue:function(m,b){var S=za();return Mr===null?wT(S,m,b):Dz(S,Mr.memoizedState,m,b)},useTransition:function(){var m=gT(nu)[0],b=za().memoizedState;return[typeof m=="boolean"?m:Tx(m),b]},useSyncExternalStore:lz,useId:Oz,useHostTransitionStatus:_T,useFormState:_z,useActionState:_z,useOptimistic:function(m,b){var S=za();return Mr!==null?fz(S,Mr,m,b):(S.baseState=m,[m,S.queue.dispatch])},useMemoCache:fT,useCacheRefresh:Iz};$z.useEffectEvent=kz;function kT(m,b,S,T){b=m.memoizedState,S=S(T,b),S=S==null?b:h({},b,S),m.memoizedState=S,m.lanes===0&&(m.updateQueue.baseState=S)}var AT={enqueueSetState:function(m,b,S){m=m._reactInternals;var T=wo(),F=Cd(T);F.payload=b,S!=null&&(F.callback=S),b=kd(m,F,T),b!==null&&(qs(b,m,T),Nx(b,m,T))},enqueueReplaceState:function(m,b,S){m=m._reactInternals;var T=wo(),F=Cd(T);F.tag=1,F.payload=b,S!=null&&(F.callback=S),b=kd(m,F,T),b!==null&&(qs(b,m,T),Nx(b,m,T))},enqueueForceUpdate:function(m,b){m=m._reactInternals;var S=wo(),T=Cd(S);T.tag=2,b!=null&&(T.callback=b),b=kd(m,T,S),b!==null&&(qs(b,m,S),Nx(b,m,S))}};function Vz(m,b,S,T,F,I,re){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(T,I,re):b.prototype&&b.prototype.isPureReactComponent?!gx(S,T)||!gx(F,I):!0}function qz(m,b,S,T){m=b.state,typeof b.componentWillReceiveProps=="function"&&b.componentWillReceiveProps(S,T),typeof b.UNSAFE_componentWillReceiveProps=="function"&&b.UNSAFE_componentWillReceiveProps(S,T),b.state!==m&&AT.enqueueReplaceState(b,b.state,null)}function _m(m,b){var S=b;if("ref"in b){S={};for(var T in b)T!=="ref"&&(S[T]=b[T])}if(m=m.defaultProps){S===b&&(S=h({},S));for(var F in m)S[F]===void 0&&(S[F]=m[F])}return S}function Gz(m){Z0(m)}function Wz(m){console.error(m)}function Kz(m){Z0(m)}function ww(m,b){try{var S=m.onUncaughtError;S(b.value,{componentStack:b.stack})}catch(T){setTimeout(function(){throw T})}}function Xz(m,b,S){try{var T=m.onCaughtError;T(S.value,{componentStack:S.stack,errorBoundary:b.tag===1?b.stateNode:null})}catch(F){setTimeout(function(){throw F})}}function TT(m,b,S){return S=Cd(S),S.tag=3,S.payload={element:null},S.callback=function(){ww(m,b)},S}function Yz(m){return m=Cd(m),m.tag=3,m}function Qz(m,b,S,T){var F=S.type.getDerivedStateFromError;if(typeof F=="function"){var I=T.value;m.payload=function(){return F(I)},m.callback=function(){Xz(b,S,T)}}var re=S.stateNode;re!==null&&typeof re.componentDidCatch=="function"&&(m.callback=function(){Xz(b,S,T),typeof F!="function"&&(jd===null?jd=new Set([this]):jd.add(this));var Pe=T.stack;this.componentDidCatch(T.value,{componentStack:Pe!==null?Pe:""})})}function Xse(m,b,S,T,F){if(S.flags|=32768,T!==null&&typeof T=="object"&&typeof T.then=="function"){if(b=S.alternate,b!==null&&xp(b,S,F,!0),S=bo.current,S!==null){switch(S.tag){case 31:case 13:return Vo===null?Dw():S.alternate===null&&Na===0&&(Na=3),S.flags&=-257,S.flags|=65536,S.lanes=F,T===lw?S.flags|=16384:(b=S.updateQueue,b===null?S.updateQueue=new Set([T]):b.add(T),JT(m,T,F)),!1;case 22:return S.flags|=65536,T===lw?S.flags|=16384:(b=S.updateQueue,b===null?(b={transitions:null,markerInstances:null,retryQueue:new Set([T])},S.updateQueue=b):(S=b.retryQueue,S===null?b.retryQueue=new Set([T]):S.add(T)),JT(m,T,F)),!1}throw Error(r(435,S.tag))}return JT(m,T,F),Dw(),!1}if(nr)return b=bo.current,b!==null?((b.flags&65536)===0&&(b.flags|=256),b.flags|=65536,b.lanes=F,T!==WA&&(m=Error(r(422),{cause:T}),yx(Uo(m,S)))):(T!==WA&&(b=Error(r(423),{cause:T}),yx(Uo(b,S))),m=m.current.alternate,m.flags|=65536,F&=-F,m.lanes|=F,T=Uo(T,S),F=TT(m.stateNode,T,F),aT(m,F),Na!==4&&(Na=2)),!1;var I=Error(r(520),{cause:T});if(I=Uo(I,S),Ix===null?Ix=[I]:Ix.push(I),Na!==4&&(Na=2),b===null)return!0;T=Uo(T,S),S=b;do{switch(S.tag){case 3:return S.flags|=65536,m=F&-F,S.lanes|=m,m=TT(S.stateNode,T,m),aT(S,m),!1;case 1:if(b=S.type,I=S.stateNode,(S.flags&128)===0&&(typeof b.getDerivedStateFromError=="function"||I!==null&&typeof I.componentDidCatch=="function"&&(jd===null||!jd.has(I))))return S.flags|=65536,F&=-F,S.lanes|=F,F=Yz(F),Qz(F,m,S,T),aT(S,F),!1}S=S.return}while(S!==null);return!1}var MT=Error(r(461)),Ka=!1;function Bi(m,b,S,T){b.child=m===null?tz(b,null,S,T):wm(b,m.child,S,T)}function Zz(m,b,S,T,F){S=S.render;var I=b.ref;if("ref"in T){var re={};for(var Pe in T)Pe!=="ref"&&(re[Pe]=T[Pe])}else re=T;return bm(b),T=uT(m,b,S,re,I,F),Pe=dT(),m!==null&&!Ka?(hT(m,b,F),ru(m,b,F)):(nr&&Pe&&qA(b),b.flags|=1,Bi(m,b,T,F),b.child)}function Jz(m,b,S,T,F){if(m===null){var I=S.type;return typeof I=="function"&&!HA(I)&&I.defaultProps===void 0&&S.compare===null?(b.tag=15,b.type=I,e5(m,b,I,T,F)):(m=nw(S.type,null,T,b,b.mode,F),m.ref=b.ref,m.return=b,b.child=m)}if(I=m.child,!OT(m,F)){var re=I.memoizedProps;if(S=S.compare,S=S!==null?S:gx,S(re,T)&&m.ref===b.ref)return ru(m,b,F)}return b.flags|=1,m=Qc(I,T),m.ref=b.ref,m.return=b,b.child=m}function e5(m,b,S,T,F){if(m!==null){var I=m.memoizedProps;if(gx(I,T)&&m.ref===b.ref)if(Ka=!1,b.pendingProps=T=I,OT(m,F))(m.flags&131072)!==0&&(Ka=!0);else return b.lanes=m.lanes,ru(m,b,F)}return PT(m,b,S,T,F)}function t5(m,b,S,T){var F=T.children,I=m!==null?m.memoizedState:null;if(m===null&&b.stateNode===null&&(b.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),T.mode==="hidden"){if((b.flags&128)!==0){if(I=I!==null?I.baseLanes|S:S,m!==null){for(T=b.child=m.child,F=0;T!==null;)F=F|T.lanes|T.childLanes,T=T.sibling;T=F&~I}else T=0,b.child=null;return n5(m,b,I,S,T)}if((S&536870912)!==0)b.memoizedState={baseLanes:0,cachePool:null},m!==null&&sw(b,I!==null?I.cachePool:null),I!==null?az(b,I):sT(),iz(b);else return T=b.lanes=536870912,n5(m,b,I!==null?I.baseLanes|S:S,S,T)}else I!==null?(sw(b,I.cachePool),az(b,I),Td(),b.memoizedState=null):(m!==null&&sw(b,null),sT(),Td());return Bi(m,b,F,S),b.child}function Ex(m,b){return m!==null&&m.tag===22||b.stateNode!==null||(b.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),b.sibling}function n5(m,b,S,T,F){var I=eT();return I=I===null?null:{parent:Ga._currentValue,pool:I},b.memoizedState={baseLanes:S,cachePool:I},m!==null&&sw(b,null),sT(),iz(b),m!==null&&xp(m,b,T,!0),b.childLanes=F,null}function Sw(m,b){return b=Nw({mode:b.mode,children:b.children},m.mode),b.ref=m.ref,m.child=b,b.return=m,b}function r5(m,b,S){return wm(b,m.child,null,S),m=Sw(b,b.pendingProps),m.flags|=2,xo(b),b.memoizedState=null,m}function Yse(m,b,S){var T=b.pendingProps,F=(b.flags&128)!==0;if(b.flags&=-129,m===null){if(nr){if(T.mode==="hidden")return m=Sw(b,T),b.lanes=536870912,Ex(null,m);if(lT(b),(m=Zr)?(m=pU(m,$o),m=m!==null&&m.data==="&"?m:null,m!==null&&(b.memoizedState={dehydrated:m,treeContext:vd!==null?{id:oc,overflow:lc}:null,retryLane:536870912,hydrationErrors:null},S=UI(m),S.return=b,b.child=S,zi=b,Zr=null)):m=null,m===null)throw Sd(b);return b.lanes=536870912,null}return Sw(b,T)}var I=m.memoizedState;if(I!==null){var re=I.dehydrated;if(lT(b),F)if(b.flags&256)b.flags&=-257,b=r5(m,b,S);else if(b.memoizedState!==null)b.child=m.child,b.flags|=128,b=null;else throw Error(r(558));else if(Ka||xp(m,b,S,!1),F=(S&m.childLanes)!==0,Ka||F){if(T=Br,T!==null&&(re=yt(T,S),re!==0&&re!==I.retryLane))throw I.retryLane=re,mm(m,re),qs(T,m,re),MT;Dw(),b=r5(m,b,S)}else m=I.treeContext,Zr=qo(re.nextSibling),zi=b,nr=!0,wd=null,$o=!1,m!==null&&$I(b,m),b=Sw(b,T),b.flags|=4096;return b}return m=Qc(m.child,{mode:T.mode,children:T.children}),m.ref=b.ref,b.child=m,m.return=b,m}function _w(m,b){var S=b.ref;if(S===null)m!==null&&m.ref!==null&&(b.flags|=4194816);else{if(typeof S!="function"&&typeof S!="object")throw Error(r(284));(m===null||m.ref!==S)&&(b.flags|=4194816)}}function PT(m,b,S,T,F){return bm(b),S=uT(m,b,S,T,void 0,F),T=dT(),m!==null&&!Ka?(hT(m,b,F),ru(m,b,F)):(nr&&T&&qA(b),b.flags|=1,Bi(m,b,S,F),b.child)}function a5(m,b,S,T,F,I){return bm(b),b.updateQueue=null,S=oz(b,T,S,F),sz(m),T=dT(),m!==null&&!Ka?(hT(m,b,I),ru(m,b,I)):(nr&&T&&qA(b),b.flags|=1,Bi(m,b,S,I),b.child)}function i5(m,b,S,T,F){if(bm(b),b.stateNode===null){var I=fp,re=S.contextType;typeof re=="object"&&re!==null&&(I=Ui(re)),I=new S(T,I),b.memoizedState=I.state!==null&&I.state!==void 0?I.state:null,I.updater=AT,b.stateNode=I,I._reactInternals=b,I=b.stateNode,I.props=T,I.state=b.memoizedState,I.refs={},nT(b),re=S.contextType,I.context=typeof re=="object"&&re!==null?Ui(re):fp,I.state=b.memoizedState,re=S.getDerivedStateFromProps,typeof re=="function"&&(kT(b,S,re,T),I.state=b.memoizedState),typeof S.getDerivedStateFromProps=="function"||typeof I.getSnapshotBeforeUpdate=="function"||typeof I.UNSAFE_componentWillMount!="function"&&typeof I.componentWillMount!="function"||(re=I.state,typeof I.componentWillMount=="function"&&I.componentWillMount(),typeof I.UNSAFE_componentWillMount=="function"&&I.UNSAFE_componentWillMount(),re!==I.state&&AT.enqueueReplaceState(I,I.state,null),kx(b,T,I,F),Cx(),I.state=b.memoizedState),typeof I.componentDidMount=="function"&&(b.flags|=4194308),T=!0}else if(m===null){I=b.stateNode;var Pe=b.memoizedProps,Ve=_m(S,Pe);I.props=Ve;var dt=I.context,vt=S.contextType;re=fp,typeof vt=="object"&&vt!==null&&(re=Ui(vt));var Ct=S.getDerivedStateFromProps;vt=typeof Ct=="function"||typeof I.getSnapshotBeforeUpdate=="function",Pe=b.pendingProps!==Pe,vt||typeof I.UNSAFE_componentWillReceiveProps!="function"&&typeof I.componentWillReceiveProps!="function"||(Pe||dt!==re)&&qz(b,I,T,re),Nd=!1;var mt=b.memoizedState;I.state=mt,kx(b,T,I,F),Cx(),dt=b.memoizedState,Pe||mt!==dt||Nd?(typeof Ct=="function"&&(kT(b,S,Ct,T),dt=b.memoizedState),(Ve=Nd||Vz(b,S,Ve,T,mt,dt,re))?(vt||typeof I.UNSAFE_componentWillMount!="function"&&typeof I.componentWillMount!="function"||(typeof I.componentWillMount=="function"&&I.componentWillMount(),typeof I.UNSAFE_componentWillMount=="function"&&I.UNSAFE_componentWillMount()),typeof I.componentDidMount=="function"&&(b.flags|=4194308)):(typeof I.componentDidMount=="function"&&(b.flags|=4194308),b.memoizedProps=T,b.memoizedState=dt),I.props=T,I.state=dt,I.context=re,T=Ve):(typeof I.componentDidMount=="function"&&(b.flags|=4194308),T=!1)}else{I=b.stateNode,rT(m,b),re=b.memoizedProps,vt=_m(S,re),I.props=vt,Ct=b.pendingProps,mt=I.context,dt=S.contextType,Ve=fp,typeof dt=="object"&&dt!==null&&(Ve=Ui(dt)),Pe=S.getDerivedStateFromProps,(dt=typeof Pe=="function"||typeof I.getSnapshotBeforeUpdate=="function")||typeof I.UNSAFE_componentWillReceiveProps!="function"&&typeof I.componentWillReceiveProps!="function"||(re!==Ct||mt!==Ve)&&qz(b,I,T,Ve),Nd=!1,mt=b.memoizedState,I.state=mt,kx(b,T,I,F),Cx();var gt=b.memoizedState;re!==Ct||mt!==gt||Nd||m!==null&&m.dependencies!==null&&aw(m.dependencies)?(typeof Pe=="function"&&(kT(b,S,Pe,T),gt=b.memoizedState),(vt=Nd||Vz(b,S,vt,T,mt,gt,Ve)||m!==null&&m.dependencies!==null&&aw(m.dependencies))?(dt||typeof I.UNSAFE_componentWillUpdate!="function"&&typeof I.componentWillUpdate!="function"||(typeof I.componentWillUpdate=="function"&&I.componentWillUpdate(T,gt,Ve),typeof I.UNSAFE_componentWillUpdate=="function"&&I.UNSAFE_componentWillUpdate(T,gt,Ve)),typeof I.componentDidUpdate=="function"&&(b.flags|=4),typeof I.getSnapshotBeforeUpdate=="function"&&(b.flags|=1024)):(typeof I.componentDidUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(b.flags|=4),typeof I.getSnapshotBeforeUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(b.flags|=1024),b.memoizedProps=T,b.memoizedState=gt),I.props=T,I.state=gt,I.context=Ve,T=vt):(typeof I.componentDidUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(b.flags|=4),typeof I.getSnapshotBeforeUpdate!="function"||re===m.memoizedProps&&mt===m.memoizedState||(b.flags|=1024),T=!1)}return I=T,_w(m,b),T=(b.flags&128)!==0,I||T?(I=b.stateNode,S=T&&typeof S.getDerivedStateFromError!="function"?null:I.render(),b.flags|=1,m!==null&&T?(b.child=wm(b,m.child,null,F),b.child=wm(b,null,S,F)):Bi(m,b,S,F),b.memoizedState=I.state,m=b.child):m=ru(m,b,F),m}function s5(m,b,S,T){return pm(),b.flags|=256,Bi(m,b,S,T),b.child}var ET={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function jT(m){return{baseLanes:m,cachePool:XI()}}function DT(m,b,S){return m=m!==null?m.childLanes&~S:0,b&&(m|=vo),m}function o5(m,b,S){var T=b.pendingProps,F=!1,I=(b.flags&128)!==0,re;if((re=I)||(re=m!==null&&m.memoizedState===null?!1:(Ia.current&2)!==0),re&&(F=!0,b.flags&=-129),re=(b.flags&32)!==0,b.flags&=-33,m===null){if(nr){if(F?Ad(b):Td(),(m=Zr)?(m=pU(m,$o),m=m!==null&&m.data!=="&"?m:null,m!==null&&(b.memoizedState={dehydrated:m,treeContext:vd!==null?{id:oc,overflow:lc}:null,retryLane:536870912,hydrationErrors:null},S=UI(m),S.return=b,b.child=S,zi=b,Zr=null)):m=null,m===null)throw Sd(b);return pM(m)?b.lanes=32:b.lanes=536870912,null}var Pe=T.children;return T=T.fallback,F?(Td(),F=b.mode,Pe=Nw({mode:"hidden",children:Pe},F),T=fm(T,F,S,null),Pe.return=b,T.return=b,Pe.sibling=T,b.child=Pe,T=b.child,T.memoizedState=jT(S),T.childLanes=DT(m,re,S),b.memoizedState=ET,Ex(null,T)):(Ad(b),RT(b,Pe))}var Ve=m.memoizedState;if(Ve!==null&&(Pe=Ve.dehydrated,Pe!==null)){if(I)b.flags&256?(Ad(b),b.flags&=-257,b=FT(m,b,S)):b.memoizedState!==null?(Td(),b.child=m.child,b.flags|=128,b=null):(Td(),Pe=T.fallback,F=b.mode,T=Nw({mode:"visible",children:T.children},F),Pe=fm(Pe,F,S,null),Pe.flags|=2,T.return=b,Pe.return=b,T.sibling=Pe,b.child=T,wm(b,m.child,null,S),T=b.child,T.memoizedState=jT(S),T.childLanes=DT(m,re,S),b.memoizedState=ET,b=Ex(null,T));else if(Ad(b),pM(Pe)){if(re=Pe.nextSibling&&Pe.nextSibling.dataset,re)var dt=re.dgst;re=dt,T=Error(r(419)),T.stack="",T.digest=re,yx({value:T,source:null,stack:null}),b=FT(m,b,S)}else if(Ka||xp(m,b,S,!1),re=(S&m.childLanes)!==0,Ka||re){if(re=Br,re!==null&&(T=yt(re,S),T!==0&&T!==Ve.retryLane))throw Ve.retryLane=T,mm(m,T),qs(re,m,T),MT;fM(Pe)||Dw(),b=FT(m,b,S)}else fM(Pe)?(b.flags|=192,b.child=m.child,b=null):(m=Ve.treeContext,Zr=qo(Pe.nextSibling),zi=b,nr=!0,wd=null,$o=!1,m!==null&&$I(b,m),b=RT(b,T.children),b.flags|=4096);return b}return F?(Td(),Pe=T.fallback,F=b.mode,Ve=m.child,dt=Ve.sibling,T=Qc(Ve,{mode:"hidden",children:T.children}),T.subtreeFlags=Ve.subtreeFlags&65011712,dt!==null?Pe=Qc(dt,Pe):(Pe=fm(Pe,F,S,null),Pe.flags|=2),Pe.return=b,T.return=b,T.sibling=Pe,b.child=T,Ex(null,T),T=b.child,Pe=m.child.memoizedState,Pe===null?Pe=jT(S):(F=Pe.cachePool,F!==null?(Ve=Ga._currentValue,F=F.parent!==Ve?{parent:Ve,pool:Ve}:F):F=XI(),Pe={baseLanes:Pe.baseLanes|S,cachePool:F}),T.memoizedState=Pe,T.childLanes=DT(m,re,S),b.memoizedState=ET,Ex(m.child,T)):(Ad(b),S=m.child,m=S.sibling,S=Qc(S,{mode:"visible",children:T.children}),S.return=b,S.sibling=null,m!==null&&(re=b.deletions,re===null?(b.deletions=[m],b.flags|=16):re.push(m)),b.child=S,b.memoizedState=null,S)}function RT(m,b){return b=Nw({mode:"visible",children:b},m.mode),b.return=m,m.child=b}function Nw(m,b){return m=go(22,m,null,b),m.lanes=0,m}function FT(m,b,S){return wm(b,m.child,null,S),m=RT(b,b.pendingProps.children),m.flags|=2,b.memoizedState=null,m}function l5(m,b,S){m.lanes|=b;var T=m.alternate;T!==null&&(T.lanes|=b),YA(m.return,b,S)}function LT(m,b,S,T,F,I){var re=m.memoizedState;re===null?m.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:T,tail:S,tailMode:F,treeForkCount:I}:(re.isBackwards=b,re.rendering=null,re.renderingStartTime=0,re.last=T,re.tail=S,re.tailMode=F,re.treeForkCount=I)}function c5(m,b,S){var T=b.pendingProps,F=T.revealOrder,I=T.tail;T=T.children;var re=Ia.current,Pe=(re&2)!==0;if(Pe?(re=re&1|2,b.flags|=128):re&=1,te(Ia,re),Bi(m,b,T,S),T=nr?xx:0,!Pe&&m!==null&&(m.flags&128)!==0)e:for(m=b.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&l5(m,S,b);else if(m.tag===19)l5(m,S,b);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===b)break e;for(;m.sibling===null;){if(m.return===null||m.return===b)break e;m=m.return}m.sibling.return=m.return,m=m.sibling}switch(F){case"forwards":for(S=b.child,F=null;S!==null;)m=S.alternate,m!==null&&hw(m)===null&&(F=S),S=S.sibling;S=F,S===null?(F=b.child,b.child=null):(F=S.sibling,S.sibling=null),LT(b,!1,F,S,I,T);break;case"backwards":case"unstable_legacy-backwards":for(S=null,F=b.child,b.child=null;F!==null;){if(m=F.alternate,m!==null&&hw(m)===null){b.child=F;break}m=F.sibling,F.sibling=S,S=F,F=m}LT(b,!0,S,null,I,T);break;case"together":LT(b,!1,null,null,void 0,T);break;default:b.memoizedState=null}return b.child}function ru(m,b,S){if(m!==null&&(b.dependencies=m.dependencies),Ed|=b.lanes,(S&b.childLanes)===0)if(m!==null){if(xp(m,b,S,!1),(S&b.childLanes)===0)return null}else return null;if(m!==null&&b.child!==m.child)throw Error(r(153));if(b.child!==null){for(m=b.child,S=Qc(m,m.pendingProps),b.child=S,S.return=b;m.sibling!==null;)m=m.sibling,S=S.sibling=Qc(m,m.pendingProps),S.return=b;S.sibling=null}return b.child}function OT(m,b){return(m.lanes&b)!==0?!0:(m=m.dependencies,!!(m!==null&&aw(m)))}function Qse(m,b,S){switch(b.tag){case 3:je(b,b.stateNode.containerInfo),_d(b,Ga,m.memoizedState.cache),pm();break;case 27:case 5:oe(b);break;case 4:je(b,b.stateNode.containerInfo);break;case 10:_d(b,b.type,b.memoizedProps.value);break;case 31:if(b.memoizedState!==null)return b.flags|=128,lT(b),null;break;case 13:var T=b.memoizedState;if(T!==null)return T.dehydrated!==null?(Ad(b),b.flags|=128,null):(S&b.child.childLanes)!==0?o5(m,b,S):(Ad(b),m=ru(m,b,S),m!==null?m.sibling:null);Ad(b);break;case 19:var F=(m.flags&128)!==0;if(T=(S&b.childLanes)!==0,T||(xp(m,b,S,!1),T=(S&b.childLanes)!==0),F){if(T)return c5(m,b,S);b.flags|=128}if(F=b.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),te(Ia,Ia.current),T)break;return null;case 22:return b.lanes=0,t5(m,b,S,b.pendingProps);case 24:_d(b,Ga,m.memoizedState.cache)}return ru(m,b,S)}function u5(m,b,S){if(m!==null)if(m.memoizedProps!==b.pendingProps)Ka=!0;else{if(!OT(m,S)&&(b.flags&128)===0)return Ka=!1,Qse(m,b,S);Ka=(m.flags&131072)!==0}else Ka=!1,nr&&(b.flags&1048576)!==0&&HI(b,xx,b.index);switch(b.lanes=0,b.tag){case 16:e:{var T=b.pendingProps;if(m=ym(b.elementType),b.type=m,typeof m=="function")HA(m)?(T=_m(m,T),b.tag=1,b=i5(null,b,m,T,S)):(b.tag=0,b=PT(null,b,m,T,S));else{if(m!=null){var F=m.$$typeof;if(F===k){b.tag=11,b=Zz(null,b,m,T,S);break e}else if(F===C){b.tag=14,b=Jz(null,b,m,T,S);break e}}throw b=D(m)||m,Error(r(306,b,""))}}return b;case 0:return PT(m,b,b.type,b.pendingProps,S);case 1:return T=b.type,F=_m(T,b.pendingProps),i5(m,b,T,F,S);case 3:e:{if(je(b,b.stateNode.containerInfo),m===null)throw Error(r(387));T=b.pendingProps;var I=b.memoizedState;F=I.element,rT(m,b),kx(b,T,null,S);var re=b.memoizedState;if(T=re.cache,_d(b,Ga,T),T!==I.cache&&QA(b,[Ga],S,!0),Cx(),T=re.element,I.isDehydrated)if(I={element:T,isDehydrated:!1,cache:re.cache},b.updateQueue.baseState=I,b.memoizedState=I,b.flags&256){b=s5(m,b,T,S);break e}else if(T!==F){F=Uo(Error(r(424)),b),yx(F),b=s5(m,b,T,S);break e}else for(m=b.stateNode.containerInfo,m.nodeType===9?m=m.body:m=m.nodeName==="HTML"?m.ownerDocument.body:m,Zr=qo(m.firstChild),zi=b,nr=!0,wd=null,$o=!0,S=tz(b,null,T,S),b.child=S;S;)S.flags=S.flags&-3|4096,S=S.sibling;else{if(pm(),T===F){b=ru(m,b,S);break e}Bi(m,b,T,S)}b=b.child}return b;case 26:return _w(m,b),m===null?(S=wU(b.type,null,b.pendingProps,null))?b.memoizedState=S:nr||(S=b.type,m=b.pendingProps,T=Uw(ce.current).createElement(S),T[En]=b,T[dr]=m,Hi(T,S,m),Xe(T),b.stateNode=T):b.memoizedState=wU(b.type,m.memoizedProps,b.pendingProps,m.memoizedState),null;case 27:return oe(b),m===null&&nr&&(T=b.stateNode=xU(b.type,b.pendingProps,ce.current),zi=b,$o=!0,F=Zr,Ld(b.type)?(gM=F,Zr=qo(T.firstChild)):Zr=F),Bi(m,b,b.pendingProps.children,S),_w(m,b),m===null&&(b.flags|=4194304),b.child;case 5:return m===null&&nr&&((F=T=Zr)&&(T=Aoe(T,b.type,b.pendingProps,$o),T!==null?(b.stateNode=T,zi=b,Zr=qo(T.firstChild),$o=!1,F=!0):F=!1),F||Sd(b)),oe(b),F=b.type,I=b.pendingProps,re=m!==null?m.memoizedProps:null,T=I.children,dM(F,I)?T=null:re!==null&&dM(F,re)&&(b.flags|=32),b.memoizedState!==null&&(F=uT(m,b,Hse,null,null,S),Gx._currentValue=F),_w(m,b),Bi(m,b,T,S),b.child;case 6:return m===null&&nr&&((m=S=Zr)&&(S=Toe(S,b.pendingProps,$o),S!==null?(b.stateNode=S,zi=b,Zr=null,m=!0):m=!1),m||Sd(b)),null;case 13:return o5(m,b,S);case 4:return je(b,b.stateNode.containerInfo),T=b.pendingProps,m===null?b.child=wm(b,null,T,S):Bi(m,b,T,S),b.child;case 11:return Zz(m,b,b.type,b.pendingProps,S);case 7:return Bi(m,b,b.pendingProps,S),b.child;case 8:return Bi(m,b,b.pendingProps.children,S),b.child;case 12:return Bi(m,b,b.pendingProps.children,S),b.child;case 10:return T=b.pendingProps,_d(b,b.type,T.value),Bi(m,b,T.children,S),b.child;case 9:return F=b.type._context,T=b.pendingProps.children,bm(b),F=Ui(F),T=T(F),b.flags|=1,Bi(m,b,T,S),b.child;case 14:return Jz(m,b,b.type,b.pendingProps,S);case 15:return e5(m,b,b.type,b.pendingProps,S);case 19:return c5(m,b,S);case 31:return Yse(m,b,S);case 22:return t5(m,b,S,b.pendingProps);case 24:return bm(b),T=Ui(Ga),m===null?(F=eT(),F===null&&(F=Br,I=ZA(),F.pooledCache=I,I.refCount++,I!==null&&(F.pooledCacheLanes|=S),F=I),b.memoizedState={parent:T,cache:F},nT(b),_d(b,Ga,F)):((m.lanes&S)!==0&&(rT(m,b),kx(b,null,null,S),Cx()),F=m.memoizedState,I=b.memoizedState,F.parent!==T?(F={parent:T,cache:T},b.memoizedState=F,b.lanes===0&&(b.memoizedState=b.updateQueue.baseState=F),_d(b,Ga,T)):(T=I.cache,_d(b,Ga,T),T!==F.cache&&QA(b,[Ga],S,!0))),Bi(m,b,b.pendingProps.children,S),b.child;case 29:throw b.pendingProps}throw Error(r(156,b.tag))}function au(m){m.flags|=4}function IT(m,b,S,T,F){if((b=(m.mode&32)!==0)&&(b=!1),b){if(m.flags|=16777216,(F&335544128)===F)if(m.stateNode.complete)m.flags|=8192;else if(O5())m.flags|=8192;else throw vm=lw,tT}else m.flags&=-16777217}function d5(m,b){if(b.type!=="stylesheet"||(b.state.loading&4)!==0)m.flags&=-16777217;else if(m.flags|=16777216,!kU(b))if(O5())m.flags|=8192;else throw vm=lw,tT}function Cw(m,b){b!==null&&(m.flags|=4),m.flags&16384&&(b=m.tag!==22?At():536870912,m.lanes|=b,Pp|=b)}function jx(m,b){if(!nr)switch(m.tailMode){case"hidden":b=m.tail;for(var S=null;b!==null;)b.alternate!==null&&(S=b),b=b.sibling;S===null?m.tail=null:S.sibling=null;break;case"collapsed":S=m.tail;for(var T=null;S!==null;)S.alternate!==null&&(T=S),S=S.sibling;T===null?b||m.tail===null?m.tail=null:m.tail.sibling=null:T.sibling=null}}function Jr(m){var b=m.alternate!==null&&m.alternate.child===m.child,S=0,T=0;if(b)for(var F=m.child;F!==null;)S|=F.lanes|F.childLanes,T|=F.subtreeFlags&65011712,T|=F.flags&65011712,F.return=m,F=F.sibling;else for(F=m.child;F!==null;)S|=F.lanes|F.childLanes,T|=F.subtreeFlags,T|=F.flags,F.return=m,F=F.sibling;return m.subtreeFlags|=T,m.childLanes=S,b}function Zse(m,b,S){var T=b.pendingProps;switch(GA(b),b.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Jr(b),null;case 1:return Jr(b),null;case 3:return S=b.stateNode,T=null,m!==null&&(T=m.memoizedState.cache),b.memoizedState.cache!==T&&(b.flags|=2048),eu(Ga),he(),S.pendingContext&&(S.context=S.pendingContext,S.pendingContext=null),(m===null||m.child===null)&&(bp(b)?au(b):m===null||m.memoizedState.isDehydrated&&(b.flags&256)===0||(b.flags|=1024,KA())),Jr(b),null;case 26:var F=b.type,I=b.memoizedState;return m===null?(au(b),I!==null?(Jr(b),d5(b,I)):(Jr(b),IT(b,F,null,T,S))):I?I!==m.memoizedState?(au(b),Jr(b),d5(b,I)):(Jr(b),b.flags&=-16777217):(m=m.memoizedProps,m!==T&&au(b),Jr(b),IT(b,F,m,T,S)),null;case 27:if(_e(b),S=ce.current,F=b.type,m!==null&&b.stateNode!=null)m.memoizedProps!==T&&au(b);else{if(!T){if(b.stateNode===null)throw Error(r(166));return Jr(b),null}m=Z.current,bp(b)?VI(b):(m=xU(F,T,S),b.stateNode=m,au(b))}return Jr(b),null;case 5:if(_e(b),F=b.type,m!==null&&b.stateNode!=null)m.memoizedProps!==T&&au(b);else{if(!T){if(b.stateNode===null)throw Error(r(166));return Jr(b),null}if(I=Z.current,bp(b))VI(b);else{var re=Uw(ce.current);switch(I){case 1:I=re.createElementNS("http://www.w3.org/2000/svg",F);break;case 2:I=re.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;default:switch(F){case"svg":I=re.createElementNS("http://www.w3.org/2000/svg",F);break;case"math":I=re.createElementNS("http://www.w3.org/1998/Math/MathML",F);break;case"script":I=re.createElement("div"),I.innerHTML="<script><\/script>",I=I.removeChild(I.firstChild);break;case"select":I=typeof T.is=="string"?re.createElement("select",{is:T.is}):re.createElement("select"),T.multiple?I.multiple=!0:T.size&&(I.size=T.size);break;default:I=typeof T.is=="string"?re.createElement(F,{is:T.is}):re.createElement(F)}}I[En]=b,I[dr]=T;e:for(re=b.child;re!==null;){if(re.tag===5||re.tag===6)I.appendChild(re.stateNode);else if(re.tag!==4&&re.tag!==27&&re.child!==null){re.child.return=re,re=re.child;continue}if(re===b)break e;for(;re.sibling===null;){if(re.return===null||re.return===b)break e;re=re.return}re.sibling.return=re.return,re=re.sibling}b.stateNode=I;e:switch(Hi(I,F,T),F){case"button":case"input":case"select":case"textarea":T=!!T.autoFocus;break e;case"img":T=!0;break e;default:T=!1}T&&au(b)}}return Jr(b),IT(b,b.type,m===null?null:m.memoizedProps,b.pendingProps,S),null;case 6:if(m&&b.stateNode!=null)m.memoizedProps!==T&&au(b);else{if(typeof T!="string"&&b.stateNode===null)throw Error(r(166));if(m=ce.current,bp(b)){if(m=b.stateNode,S=b.memoizedProps,T=null,F=zi,F!==null)switch(F.tag){case 27:case 5:T=F.memoizedProps}m[En]=b,m=!!(m.nodeValue===S||T!==null&&T.suppressHydrationWarning===!0||oU(m.nodeValue,S)),m||Sd(b,!0)}else m=Uw(m).createTextNode(T),m[En]=b,b.stateNode=m}return Jr(b),null;case 31:if(S=b.memoizedState,m===null||m.memoizedState!==null){if(T=bp(b),S!==null){if(m===null){if(!T)throw Error(r(318));if(m=b.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(r(557));m[En]=b}else pm(),(b.flags&128)===0&&(b.memoizedState=null),b.flags|=4;Jr(b),m=!1}else S=KA(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=S),m=!0;if(!m)return b.flags&256?(xo(b),b):(xo(b),null);if((b.flags&128)!==0)throw Error(r(558))}return Jr(b),null;case 13:if(T=b.memoizedState,m===null||m.memoizedState!==null&&m.memoizedState.dehydrated!==null){if(F=bp(b),T!==null&&T.dehydrated!==null){if(m===null){if(!F)throw Error(r(318));if(F=b.memoizedState,F=F!==null?F.dehydrated:null,!F)throw Error(r(317));F[En]=b}else pm(),(b.flags&128)===0&&(b.memoizedState=null),b.flags|=4;Jr(b),F=!1}else F=KA(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=F),F=!0;if(!F)return b.flags&256?(xo(b),b):(xo(b),null)}return xo(b),(b.flags&128)!==0?(b.lanes=S,b):(S=T!==null,m=m!==null&&m.memoizedState!==null,S&&(T=b.child,F=null,T.alternate!==null&&T.alternate.memoizedState!==null&&T.alternate.memoizedState.cachePool!==null&&(F=T.alternate.memoizedState.cachePool.pool),I=null,T.memoizedState!==null&&T.memoizedState.cachePool!==null&&(I=T.memoizedState.cachePool.pool),I!==F&&(T.flags|=2048)),S!==m&&S&&(b.child.flags|=8192),Cw(b,b.updateQueue),Jr(b),null);case 4:return he(),m===null&&sM(b.stateNode.containerInfo),Jr(b),null;case 10:return eu(b.type),Jr(b),null;case 19:if(K(Ia),T=b.memoizedState,T===null)return Jr(b),null;if(F=(b.flags&128)!==0,I=T.rendering,I===null)if(F)jx(T,!1);else{if(Na!==0||m!==null&&(m.flags&128)!==0)for(m=b.child;m!==null;){if(I=hw(m),I!==null){for(b.flags|=128,jx(T,!1),m=I.updateQueue,b.updateQueue=m,Cw(b,m),b.subtreeFlags=0,m=S,S=b.child;S!==null;)zI(S,m),S=S.sibling;return te(Ia,Ia.current&1|2),nr&&Zc(b,T.treeForkCount),b.child}m=m.sibling}T.tail!==null&&R()>Pw&&(b.flags|=128,F=!0,jx(T,!1),b.lanes=4194304)}else{if(!F)if(m=hw(I),m!==null){if(b.flags|=128,F=!0,m=m.updateQueue,b.updateQueue=m,Cw(b,m),jx(T,!0),T.tail===null&&T.tailMode==="hidden"&&!I.alternate&&!nr)return Jr(b),null}else 2*R()-T.renderingStartTime>Pw&&S!==536870912&&(b.flags|=128,F=!0,jx(T,!1),b.lanes=4194304);T.isBackwards?(I.sibling=b.child,b.child=I):(m=T.last,m!==null?m.sibling=I:b.child=I,T.last=I)}return T.tail!==null?(m=T.tail,T.rendering=m,T.tail=m.sibling,T.renderingStartTime=R(),m.sibling=null,S=Ia.current,te(Ia,F?S&1|2:S&1),nr&&Zc(b,T.treeForkCount),m):(Jr(b),null);case 22:case 23:return xo(b),oT(),T=b.memoizedState!==null,m!==null?m.memoizedState!==null!==T&&(b.flags|=8192):T&&(b.flags|=8192),T?(S&536870912)!==0&&(b.flags&128)===0&&(Jr(b),b.subtreeFlags&6&&(b.flags|=8192)):Jr(b),S=b.updateQueue,S!==null&&Cw(b,S.retryQueue),S=null,m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),T=null,b.memoizedState!==null&&b.memoizedState.cachePool!==null&&(T=b.memoizedState.cachePool.pool),T!==S&&(b.flags|=2048),m!==null&&K(xm),null;case 24:return S=null,m!==null&&(S=m.memoizedState.cache),b.memoizedState.cache!==S&&(b.flags|=2048),eu(Ga),Jr(b),null;case 25:return null;case 30:return null}throw Error(r(156,b.tag))}function Jse(m,b){switch(GA(b),b.tag){case 1:return m=b.flags,m&65536?(b.flags=m&-65537|128,b):null;case 3:return eu(Ga),he(),m=b.flags,(m&65536)!==0&&(m&128)===0?(b.flags=m&-65537|128,b):null;case 26:case 27:case 5:return _e(b),null;case 31:if(b.memoizedState!==null){if(xo(b),b.alternate===null)throw Error(r(340));pm()}return m=b.flags,m&65536?(b.flags=m&-65537|128,b):null;case 13:if(xo(b),m=b.memoizedState,m!==null&&m.dehydrated!==null){if(b.alternate===null)throw Error(r(340));pm()}return m=b.flags,m&65536?(b.flags=m&-65537|128,b):null;case 19:return K(Ia),null;case 4:return he(),null;case 10:return eu(b.type),null;case 22:case 23:return xo(b),oT(),m!==null&&K(xm),m=b.flags,m&65536?(b.flags=m&-65537|128,b):null;case 24:return eu(Ga),null;case 25:return null;default:return null}}function h5(m,b){switch(GA(b),b.tag){case 3:eu(Ga),he();break;case 26:case 27:case 5:_e(b);break;case 4:he();break;case 31:b.memoizedState!==null&&xo(b);break;case 13:xo(b);break;case 19:K(Ia);break;case 10:eu(b.type);break;case 22:case 23:xo(b),oT(),m!==null&&K(xm);break;case 24:eu(Ga)}}function Dx(m,b){try{var S=b.updateQueue,T=S!==null?S.lastEffect:null;if(T!==null){var F=T.next;S=F;do{if((S.tag&m)===m){T=void 0;var I=S.create,re=S.inst;T=I(),re.destroy=T}S=S.next}while(S!==F)}}catch(Pe){_r(b,b.return,Pe)}}function Md(m,b,S){try{var T=b.updateQueue,F=T!==null?T.lastEffect:null;if(F!==null){var I=F.next;T=I;do{if((T.tag&m)===m){var re=T.inst,Pe=re.destroy;if(Pe!==void 0){re.destroy=void 0,F=b;var Ve=S,dt=Pe;try{dt()}catch(vt){_r(F,Ve,vt)}}}T=T.next}while(T!==I)}}catch(vt){_r(b,b.return,vt)}}function m5(m){var b=m.updateQueue;if(b!==null){var S=m.stateNode;try{rz(b,S)}catch(T){_r(m,m.return,T)}}}function f5(m,b,S){S.props=_m(m.type,m.memoizedProps),S.state=m.memoizedState;try{S.componentWillUnmount()}catch(T){_r(m,b,T)}}function Rx(m,b){try{var S=m.ref;if(S!==null){switch(m.tag){case 26:case 27:case 5:var T=m.stateNode;break;case 30:T=m.stateNode;break;default:T=m.stateNode}typeof S=="function"?m.refCleanup=S(T):S.current=T}}catch(F){_r(m,b,F)}}function cc(m,b){var S=m.ref,T=m.refCleanup;if(S!==null)if(typeof T=="function")try{T()}catch(F){_r(m,b,F)}finally{m.refCleanup=null,m=m.alternate,m!=null&&(m.refCleanup=null)}else if(typeof S=="function")try{S(null)}catch(F){_r(m,b,F)}else S.current=null}function p5(m){var b=m.type,S=m.memoizedProps,T=m.stateNode;try{e:switch(b){case"button":case"input":case"select":case"textarea":S.autoFocus&&T.focus();break e;case"img":S.src?T.src=S.src:S.srcSet&&(T.srcset=S.srcSet)}}catch(F){_r(m,m.return,F)}}function zT(m,b,S){try{var T=m.stateNode;woe(T,m.type,S,b),T[dr]=b}catch(F){_r(m,m.return,F)}}function g5(m){return m.tag===5||m.tag===3||m.tag===26||m.tag===27&&Ld(m.type)||m.tag===4}function UT(m){e:for(;;){for(;m.sibling===null;){if(m.return===null||g5(m.return))return null;m=m.return}for(m.sibling.return=m.return,m=m.sibling;m.tag!==5&&m.tag!==6&&m.tag!==18;){if(m.tag===27&&Ld(m.type)||m.flags&2||m.child===null||m.tag===4)continue e;m.child.return=m,m=m.child}if(!(m.flags&2))return m.stateNode}}function BT(m,b,S){var T=m.tag;if(T===5||T===6)m=m.stateNode,b?(S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S).insertBefore(m,b):(b=S.nodeType===9?S.body:S.nodeName==="HTML"?S.ownerDocument.body:S,b.appendChild(m),S=S._reactRootContainer,S!=null||b.onclick!==null||(b.onclick=Vt));else if(T!==4&&(T===27&&Ld(m.type)&&(S=m.stateNode,b=null),m=m.child,m!==null))for(BT(m,b,S),m=m.sibling;m!==null;)BT(m,b,S),m=m.sibling}function kw(m,b,S){var T=m.tag;if(T===5||T===6)m=m.stateNode,b?S.insertBefore(m,b):S.appendChild(m);else if(T!==4&&(T===27&&Ld(m.type)&&(S=m.stateNode),m=m.child,m!==null))for(kw(m,b,S),m=m.sibling;m!==null;)kw(m,b,S),m=m.sibling}function b5(m){var b=m.stateNode,S=m.memoizedProps;try{for(var T=m.type,F=b.attributes;F.length;)b.removeAttributeNode(F[0]);Hi(b,T,S),b[En]=m,b[dr]=S}catch(I){_r(m,m.return,I)}}var iu=!1,Xa=!1,HT=!1,x5=typeof WeakSet=="function"?WeakSet:Set,ki=null;function eoe(m,b){if(m=m.containerInfo,cM=Ww,m=PI(m),FA(m)){if("selectionStart"in m)var S={start:m.selectionStart,end:m.selectionEnd};else e:{S=(S=m.ownerDocument)&&S.defaultView||window;var T=S.getSelection&&S.getSelection();if(T&&T.rangeCount!==0){S=T.anchorNode;var F=T.anchorOffset,I=T.focusNode;T=T.focusOffset;try{S.nodeType,I.nodeType}catch{S=null;break e}var re=0,Pe=-1,Ve=-1,dt=0,vt=0,Ct=m,mt=null;t:for(;;){for(var gt;Ct!==S||F!==0&&Ct.nodeType!==3||(Pe=re+F),Ct!==I||T!==0&&Ct.nodeType!==3||(Ve=re+T),Ct.nodeType===3&&(re+=Ct.nodeValue.length),(gt=Ct.firstChild)!==null;)mt=Ct,Ct=gt;for(;;){if(Ct===m)break t;if(mt===S&&++dt===F&&(Pe=re),mt===I&&++vt===T&&(Ve=re),(gt=Ct.nextSibling)!==null)break;Ct=mt,mt=Ct.parentNode}Ct=gt}S=Pe===-1||Ve===-1?null:{start:Pe,end:Ve}}else S=null}S=S||{start:0,end:0}}else S=null;for(uM={focusedElem:m,selectionRange:S},Ww=!1,ki=b;ki!==null;)if(b=ki,m=b.child,(b.subtreeFlags&1028)!==0&&m!==null)m.return=b,ki=m;else for(;ki!==null;){switch(b=ki,I=b.alternate,m=b.flags,b.tag){case 0:if((m&4)!==0&&(m=b.updateQueue,m=m!==null?m.events:null,m!==null))for(S=0;S<m.length;S++)F=m[S],F.ref.impl=F.nextImpl;break;case 11:case 15:break;case 1:if((m&1024)!==0&&I!==null){m=void 0,S=b,F=I.memoizedProps,I=I.memoizedState,T=S.stateNode;try{var Qt=_m(S.type,F);m=T.getSnapshotBeforeUpdate(Qt,I),T.__reactInternalSnapshotBeforeUpdate=m}catch(hn){_r(S,S.return,hn)}}break;case 3:if((m&1024)!==0){if(m=b.stateNode.containerInfo,S=m.nodeType,S===9)mM(m);else if(S===1)switch(m.nodeName){case"HEAD":case"HTML":case"BODY":mM(m);break;default:m.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((m&1024)!==0)throw Error(r(163))}if(m=b.sibling,m!==null){m.return=b.return,ki=m;break}ki=b.return}}function y5(m,b,S){var T=S.flags;switch(S.tag){case 0:case 11:case 15:ou(m,S),T&4&&Dx(5,S);break;case 1:if(ou(m,S),T&4)if(m=S.stateNode,b===null)try{m.componentDidMount()}catch(re){_r(S,S.return,re)}else{var F=_m(S.type,b.memoizedProps);b=b.memoizedState;try{m.componentDidUpdate(F,b,m.__reactInternalSnapshotBeforeUpdate)}catch(re){_r(S,S.return,re)}}T&64&&m5(S),T&512&&Rx(S,S.return);break;case 3:if(ou(m,S),T&64&&(m=S.updateQueue,m!==null)){if(b=null,S.child!==null)switch(S.child.tag){case 27:case 5:b=S.child.stateNode;break;case 1:b=S.child.stateNode}try{rz(m,b)}catch(re){_r(S,S.return,re)}}break;case 27:b===null&&T&4&&b5(S);case 26:case 5:ou(m,S),b===null&&T&4&&p5(S),T&512&&Rx(S,S.return);break;case 12:ou(m,S);break;case 31:ou(m,S),T&4&&S5(m,S);break;case 13:ou(m,S),T&4&&_5(m,S),T&64&&(m=S.memoizedState,m!==null&&(m=m.dehydrated,m!==null&&(S=coe.bind(null,S),Moe(m,S))));break;case 22:if(T=S.memoizedState!==null||iu,!T){b=b!==null&&b.memoizedState!==null||Xa,F=iu;var I=Xa;iu=T,(Xa=b)&&!I?lu(m,S,(S.subtreeFlags&8772)!==0):ou(m,S),iu=F,Xa=I}break;case 30:break;default:ou(m,S)}}function v5(m){var b=m.alternate;b!==null&&(m.alternate=null,v5(b)),m.child=null,m.deletions=null,m.sibling=null,m.tag===5&&(b=m.stateNode,b!==null&&Ge(b)),m.stateNode=null,m.return=null,m.dependencies=null,m.memoizedProps=null,m.memoizedState=null,m.pendingProps=null,m.stateNode=null,m.updateQueue=null}var oa=null,Bs=!1;function su(m,b,S){for(S=S.child;S!==null;)w5(m,b,S),S=S.sibling}function w5(m,b,S){if(xe&&typeof xe.onCommitFiberUnmount=="function")try{xe.onCommitFiberUnmount(pe,S)}catch{}switch(S.tag){case 26:Xa||cc(S,b),su(m,b,S),S.memoizedState?S.memoizedState.count--:S.stateNode&&(S=S.stateNode,S.parentNode.removeChild(S));break;case 27:Xa||cc(S,b);var T=oa,F=Bs;Ld(S.type)&&(oa=S.stateNode,Bs=!1),su(m,b,S),$x(S.stateNode),oa=T,Bs=F;break;case 5:Xa||cc(S,b);case 6:if(T=oa,F=Bs,oa=null,su(m,b,S),oa=T,Bs=F,oa!==null)if(Bs)try{(oa.nodeType===9?oa.body:oa.nodeName==="HTML"?oa.ownerDocument.body:oa).removeChild(S.stateNode)}catch(I){_r(S,b,I)}else try{oa.removeChild(S.stateNode)}catch(I){_r(S,b,I)}break;case 18:oa!==null&&(Bs?(m=oa,mU(m.nodeType===9?m.body:m.nodeName==="HTML"?m.ownerDocument.body:m,S.stateNode),Ip(m)):mU(oa,S.stateNode));break;case 4:T=oa,F=Bs,oa=S.stateNode.containerInfo,Bs=!0,su(m,b,S),oa=T,Bs=F;break;case 0:case 11:case 14:case 15:Md(2,S,b),Xa||Md(4,S,b),su(m,b,S);break;case 1:Xa||(cc(S,b),T=S.stateNode,typeof T.componentWillUnmount=="function"&&f5(S,b,T)),su(m,b,S);break;case 21:su(m,b,S);break;case 22:Xa=(T=Xa)||S.memoizedState!==null,su(m,b,S),Xa=T;break;default:su(m,b,S)}}function S5(m,b){if(b.memoizedState===null&&(m=b.alternate,m!==null&&(m=m.memoizedState,m!==null))){m=m.dehydrated;try{Ip(m)}catch(S){_r(b,b.return,S)}}}function _5(m,b){if(b.memoizedState===null&&(m=b.alternate,m!==null&&(m=m.memoizedState,m!==null&&(m=m.dehydrated,m!==null))))try{Ip(m)}catch(S){_r(b,b.return,S)}}function toe(m){switch(m.tag){case 31:case 13:case 19:var b=m.stateNode;return b===null&&(b=m.stateNode=new x5),b;case 22:return m=m.stateNode,b=m._retryCache,b===null&&(b=m._retryCache=new x5),b;default:throw Error(r(435,m.tag))}}function Aw(m,b){var S=toe(m);b.forEach(function(T){if(!S.has(T)){S.add(T);var F=uoe.bind(null,m,T);T.then(F,F)}})}function Hs(m,b){var S=b.deletions;if(S!==null)for(var T=0;T<S.length;T++){var F=S[T],I=m,re=b,Pe=re;e:for(;Pe!==null;){switch(Pe.tag){case 27:if(Ld(Pe.type)){oa=Pe.stateNode,Bs=!1;break e}break;case 5:oa=Pe.stateNode,Bs=!1;break e;case 3:case 4:oa=Pe.stateNode.containerInfo,Bs=!0;break e}Pe=Pe.return}if(oa===null)throw Error(r(160));w5(I,re,F),oa=null,Bs=!1,I=F.alternate,I!==null&&(I.return=null),F.return=null}if(b.subtreeFlags&13886)for(b=b.child;b!==null;)N5(b,m),b=b.sibling}var El=null;function N5(m,b){var S=m.alternate,T=m.flags;switch(m.tag){case 0:case 11:case 14:case 15:Hs(b,m),$s(m),T&4&&(Md(3,m,m.return),Dx(3,m),Md(5,m,m.return));break;case 1:Hs(b,m),$s(m),T&512&&(Xa||S===null||cc(S,S.return)),T&64&&iu&&(m=m.updateQueue,m!==null&&(T=m.callbacks,T!==null&&(S=m.shared.hiddenCallbacks,m.shared.hiddenCallbacks=S===null?T:S.concat(T))));break;case 26:var F=El;if(Hs(b,m),$s(m),T&512&&(Xa||S===null||cc(S,S.return)),T&4){var I=S!==null?S.memoizedState:null;if(T=m.memoizedState,S===null)if(T===null)if(m.stateNode===null){e:{T=m.type,S=m.memoizedProps,F=F.ownerDocument||F;t:switch(T){case"title":I=F.getElementsByTagName("title")[0],(!I||I[ot]||I[En]||I.namespaceURI==="http://www.w3.org/2000/svg"||I.hasAttribute("itemprop"))&&(I=F.createElement(T),F.head.insertBefore(I,F.querySelector("head > title"))),Hi(I,T,S),I[En]=m,Xe(I),T=I;break e;case"link":var re=NU("link","href",F).get(T+(S.href||""));if(re){for(var Pe=0;Pe<re.length;Pe++)if(I=re[Pe],I.getAttribute("href")===(S.href==null||S.href===""?null:S.href)&&I.getAttribute("rel")===(S.rel==null?null:S.rel)&&I.getAttribute("title")===(S.title==null?null:S.title)&&I.getAttribute("crossorigin")===(S.crossOrigin==null?null:S.crossOrigin)){re.splice(Pe,1);break t}}I=F.createElement(T),Hi(I,T,S),F.head.appendChild(I);break;case"meta":if(re=NU("meta","content",F).get(T+(S.content||""))){for(Pe=0;Pe<re.length;Pe++)if(I=re[Pe],I.getAttribute("content")===(S.content==null?null:""+S.content)&&I.getAttribute("name")===(S.name==null?null:S.name)&&I.getAttribute("property")===(S.property==null?null:S.property)&&I.getAttribute("http-equiv")===(S.httpEquiv==null?null:S.httpEquiv)&&I.getAttribute("charset")===(S.charSet==null?null:S.charSet)){re.splice(Pe,1);break t}}I=F.createElement(T),Hi(I,T,S),F.head.appendChild(I);break;default:throw Error(r(468,T))}I[En]=m,Xe(I),T=I}m.stateNode=T}else CU(F,m.type,m.stateNode);else m.stateNode=_U(F,T,m.memoizedProps);else I!==T?(I===null?S.stateNode!==null&&(S=S.stateNode,S.parentNode.removeChild(S)):I.count--,T===null?CU(F,m.type,m.stateNode):_U(F,T,m.memoizedProps)):T===null&&m.stateNode!==null&&zT(m,m.memoizedProps,S.memoizedProps)}break;case 27:Hs(b,m),$s(m),T&512&&(Xa||S===null||cc(S,S.return)),S!==null&&T&4&&zT(m,m.memoizedProps,S.memoizedProps);break;case 5:if(Hs(b,m),$s(m),T&512&&(Xa||S===null||cc(S,S.return)),m.flags&32){F=m.stateNode;try{Ft(F,"")}catch(Qt){_r(m,m.return,Qt)}}T&4&&m.stateNode!=null&&(F=m.memoizedProps,zT(m,F,S!==null?S.memoizedProps:F)),T&1024&&(HT=!0);break;case 6:if(Hs(b,m),$s(m),T&4){if(m.stateNode===null)throw Error(r(162));T=m.memoizedProps,S=m.stateNode;try{S.nodeValue=T}catch(Qt){_r(m,m.return,Qt)}}break;case 3:if($w=null,F=El,El=Bw(b.containerInfo),Hs(b,m),El=F,$s(m),T&4&&S!==null&&S.memoizedState.isDehydrated)try{Ip(b.containerInfo)}catch(Qt){_r(m,m.return,Qt)}HT&&(HT=!1,C5(m));break;case 4:T=El,El=Bw(m.stateNode.containerInfo),Hs(b,m),$s(m),El=T;break;case 12:Hs(b,m),$s(m);break;case 31:Hs(b,m),$s(m),T&4&&(T=m.updateQueue,T!==null&&(m.updateQueue=null,Aw(m,T)));break;case 13:Hs(b,m),$s(m),m.child.flags&8192&&m.memoizedState!==null!=(S!==null&&S.memoizedState!==null)&&(Mw=R()),T&4&&(T=m.updateQueue,T!==null&&(m.updateQueue=null,Aw(m,T)));break;case 22:F=m.memoizedState!==null;var Ve=S!==null&&S.memoizedState!==null,dt=iu,vt=Xa;if(iu=dt||F,Xa=vt||Ve,Hs(b,m),Xa=vt,iu=dt,$s(m),T&8192)e:for(b=m.stateNode,b._visibility=F?b._visibility&-2:b._visibility|1,F&&(S===null||Ve||iu||Xa||Nm(m)),S=null,b=m;;){if(b.tag===5||b.tag===26){if(S===null){Ve=S=b;try{if(I=Ve.stateNode,F)re=I.style,typeof re.setProperty=="function"?re.setProperty("display","none","important"):re.display="none";else{Pe=Ve.stateNode;var Ct=Ve.memoizedProps.style,mt=Ct!=null&&Ct.hasOwnProperty("display")?Ct.display:null;Pe.style.display=mt==null||typeof mt=="boolean"?"":(""+mt).trim()}}catch(Qt){_r(Ve,Ve.return,Qt)}}}else if(b.tag===6){if(S===null){Ve=b;try{Ve.stateNode.nodeValue=F?"":Ve.memoizedProps}catch(Qt){_r(Ve,Ve.return,Qt)}}}else if(b.tag===18){if(S===null){Ve=b;try{var gt=Ve.stateNode;F?fU(gt,!0):fU(Ve.stateNode,!1)}catch(Qt){_r(Ve,Ve.return,Qt)}}}else if((b.tag!==22&&b.tag!==23||b.memoizedState===null||b===m)&&b.child!==null){b.child.return=b,b=b.child;continue}if(b===m)break e;for(;b.sibling===null;){if(b.return===null||b.return===m)break e;S===b&&(S=null),b=b.return}S===b&&(S=null),b.sibling.return=b.return,b=b.sibling}T&4&&(T=m.updateQueue,T!==null&&(S=T.retryQueue,S!==null&&(T.retryQueue=null,Aw(m,S))));break;case 19:Hs(b,m),$s(m),T&4&&(T=m.updateQueue,T!==null&&(m.updateQueue=null,Aw(m,T)));break;case 30:break;case 21:break;default:Hs(b,m),$s(m)}}function $s(m){var b=m.flags;if(b&2){try{for(var S,T=m.return;T!==null;){if(g5(T)){S=T;break}T=T.return}if(S==null)throw Error(r(160));switch(S.tag){case 27:var F=S.stateNode,I=UT(m);kw(m,I,F);break;case 5:var re=S.stateNode;S.flags&32&&(Ft(re,""),S.flags&=-33);var Pe=UT(m);kw(m,Pe,re);break;case 3:case 4:var Ve=S.stateNode.containerInfo,dt=UT(m);BT(m,dt,Ve);break;default:throw Error(r(161))}}catch(vt){_r(m,m.return,vt)}m.flags&=-3}b&4096&&(m.flags&=-4097)}function C5(m){if(m.subtreeFlags&1024)for(m=m.child;m!==null;){var b=m;C5(b),b.tag===5&&b.flags&1024&&b.stateNode.reset(),m=m.sibling}}function ou(m,b){if(b.subtreeFlags&8772)for(b=b.child;b!==null;)y5(m,b.alternate,b),b=b.sibling}function Nm(m){for(m=m.child;m!==null;){var b=m;switch(b.tag){case 0:case 11:case 14:case 15:Md(4,b,b.return),Nm(b);break;case 1:cc(b,b.return);var S=b.stateNode;typeof S.componentWillUnmount=="function"&&f5(b,b.return,S),Nm(b);break;case 27:$x(b.stateNode);case 26:case 5:cc(b,b.return),Nm(b);break;case 22:b.memoizedState===null&&Nm(b);break;case 30:Nm(b);break;default:Nm(b)}m=m.sibling}}function lu(m,b,S){for(S=S&&(b.subtreeFlags&8772)!==0,b=b.child;b!==null;){var T=b.alternate,F=m,I=b,re=I.flags;switch(I.tag){case 0:case 11:case 15:lu(F,I,S),Dx(4,I);break;case 1:if(lu(F,I,S),T=I,F=T.stateNode,typeof F.componentDidMount=="function")try{F.componentDidMount()}catch(dt){_r(T,T.return,dt)}if(T=I,F=T.updateQueue,F!==null){var Pe=T.stateNode;try{var Ve=F.shared.hiddenCallbacks;if(Ve!==null)for(F.shared.hiddenCallbacks=null,F=0;F<Ve.length;F++)nz(Ve[F],Pe)}catch(dt){_r(T,T.return,dt)}}S&&re&64&&m5(I),Rx(I,I.return);break;case 27:b5(I);case 26:case 5:lu(F,I,S),S&&T===null&&re&4&&p5(I),Rx(I,I.return);break;case 12:lu(F,I,S);break;case 31:lu(F,I,S),S&&re&4&&S5(F,I);break;case 13:lu(F,I,S),S&&re&4&&_5(F,I);break;case 22:I.memoizedState===null&&lu(F,I,S),Rx(I,I.return);break;case 30:break;default:lu(F,I,S)}b=b.sibling}}function $T(m,b){var S=null;m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),m=null,b.memoizedState!==null&&b.memoizedState.cachePool!==null&&(m=b.memoizedState.cachePool.pool),m!==S&&(m!=null&&m.refCount++,S!=null&&vx(S))}function VT(m,b){m=null,b.alternate!==null&&(m=b.alternate.memoizedState.cache),b=b.memoizedState.cache,b!==m&&(b.refCount++,m!=null&&vx(m))}function jl(m,b,S,T){if(b.subtreeFlags&10256)for(b=b.child;b!==null;)k5(m,b,S,T),b=b.sibling}function k5(m,b,S,T){var F=b.flags;switch(b.tag){case 0:case 11:case 15:jl(m,b,S,T),F&2048&&Dx(9,b);break;case 1:jl(m,b,S,T);break;case 3:jl(m,b,S,T),F&2048&&(m=null,b.alternate!==null&&(m=b.alternate.memoizedState.cache),b=b.memoizedState.cache,b!==m&&(b.refCount++,m!=null&&vx(m)));break;case 12:if(F&2048){jl(m,b,S,T),m=b.stateNode;try{var I=b.memoizedProps,re=I.id,Pe=I.onPostCommit;typeof Pe=="function"&&Pe(re,b.alternate===null?"mount":"update",m.passiveEffectDuration,-0)}catch(Ve){_r(b,b.return,Ve)}}else jl(m,b,S,T);break;case 31:jl(m,b,S,T);break;case 13:jl(m,b,S,T);break;case 23:break;case 22:I=b.stateNode,re=b.alternate,b.memoizedState!==null?I._visibility&2?jl(m,b,S,T):Fx(m,b):I._visibility&2?jl(m,b,S,T):(I._visibility|=2,Ap(m,b,S,T,(b.subtreeFlags&10256)!==0||!1)),F&2048&&$T(re,b);break;case 24:jl(m,b,S,T),F&2048&&VT(b.alternate,b);break;default:jl(m,b,S,T)}}function Ap(m,b,S,T,F){for(F=F&&((b.subtreeFlags&10256)!==0||!1),b=b.child;b!==null;){var I=m,re=b,Pe=S,Ve=T,dt=re.flags;switch(re.tag){case 0:case 11:case 15:Ap(I,re,Pe,Ve,F),Dx(8,re);break;case 23:break;case 22:var vt=re.stateNode;re.memoizedState!==null?vt._visibility&2?Ap(I,re,Pe,Ve,F):Fx(I,re):(vt._visibility|=2,Ap(I,re,Pe,Ve,F)),F&&dt&2048&&$T(re.alternate,re);break;case 24:Ap(I,re,Pe,Ve,F),F&&dt&2048&&VT(re.alternate,re);break;default:Ap(I,re,Pe,Ve,F)}b=b.sibling}}function Fx(m,b){if(b.subtreeFlags&10256)for(b=b.child;b!==null;){var S=m,T=b,F=T.flags;switch(T.tag){case 22:Fx(S,T),F&2048&&$T(T.alternate,T);break;case 24:Fx(S,T),F&2048&&VT(T.alternate,T);break;default:Fx(S,T)}b=b.sibling}}var Lx=8192;function Tp(m,b,S){if(m.subtreeFlags&Lx)for(m=m.child;m!==null;)A5(m,b,S),m=m.sibling}function A5(m,b,S){switch(m.tag){case 26:Tp(m,b,S),m.flags&Lx&&m.memoizedState!==null&&Boe(S,El,m.memoizedState,m.memoizedProps);break;case 5:Tp(m,b,S);break;case 3:case 4:var T=El;El=Bw(m.stateNode.containerInfo),Tp(m,b,S),El=T;break;case 22:m.memoizedState===null&&(T=m.alternate,T!==null&&T.memoizedState!==null?(T=Lx,Lx=16777216,Tp(m,b,S),Lx=T):Tp(m,b,S));break;default:Tp(m,b,S)}}function T5(m){var b=m.alternate;if(b!==null&&(m=b.child,m!==null)){b.child=null;do b=m.sibling,m.sibling=null,m=b;while(m!==null)}}function Ox(m){var b=m.deletions;if((m.flags&16)!==0){if(b!==null)for(var S=0;S<b.length;S++){var T=b[S];ki=T,P5(T,m)}T5(m)}if(m.subtreeFlags&10256)for(m=m.child;m!==null;)M5(m),m=m.sibling}function M5(m){switch(m.tag){case 0:case 11:case 15:Ox(m),m.flags&2048&&Md(9,m,m.return);break;case 3:Ox(m);break;case 12:Ox(m);break;case 22:var b=m.stateNode;m.memoizedState!==null&&b._visibility&2&&(m.return===null||m.return.tag!==13)?(b._visibility&=-3,Tw(m)):Ox(m);break;default:Ox(m)}}function Tw(m){var b=m.deletions;if((m.flags&16)!==0){if(b!==null)for(var S=0;S<b.length;S++){var T=b[S];ki=T,P5(T,m)}T5(m)}for(m=m.child;m!==null;){switch(b=m,b.tag){case 0:case 11:case 15:Md(8,b,b.return),Tw(b);break;case 22:S=b.stateNode,S._visibility&2&&(S._visibility&=-3,Tw(b));break;default:Tw(b)}m=m.sibling}}function P5(m,b){for(;ki!==null;){var S=ki;switch(S.tag){case 0:case 11:case 15:Md(8,S,b);break;case 23:case 22:if(S.memoizedState!==null&&S.memoizedState.cachePool!==null){var T=S.memoizedState.cachePool.pool;T!=null&&T.refCount++}break;case 24:vx(S.memoizedState.cache)}if(T=S.child,T!==null)T.return=S,ki=T;else e:for(S=m;ki!==null;){T=ki;var F=T.sibling,I=T.return;if(v5(T),T===S){ki=null;break e}if(F!==null){F.return=I,ki=F;break e}ki=I}}}var noe={getCacheForType:function(m){var b=Ui(Ga),S=b.data.get(m);return S===void 0&&(S=m(),b.data.set(m,S)),S},cacheSignal:function(){return Ui(Ga).controller.signal}},roe=typeof WeakMap=="function"?WeakMap:Map,fr=0,Br=null,Kn=null,Jn=0,Sr=0,yo=null,Pd=!1,Mp=!1,qT=!1,cu=0,Na=0,Ed=0,Cm=0,GT=0,vo=0,Pp=0,Ix=null,Vs=null,WT=!1,Mw=0,E5=0,Pw=1/0,Ew=null,jd=null,li=0,Dd=null,Ep=null,uu=0,KT=0,XT=null,j5=null,zx=0,YT=null;function wo(){return(fr&2)!==0&&Jn!==0?Jn&-Jn:G.T!==null?nM():vr()}function D5(){if(vo===0)if((Jn&536870912)===0||nr){var m=De;De<<=1,(De&3932160)===0&&(De=262144),vo=m}else vo=536870912;return m=bo.current,m!==null&&(m.flags|=32),vo}function qs(m,b,S){(m===Br&&(Sr===2||Sr===9)||m.cancelPendingCommit!==null)&&(jp(m,0),Rd(m,Jn,vo,!1)),It(m,S),((fr&2)===0||m!==Br)&&(m===Br&&((fr&2)===0&&(Cm|=S),Na===4&&Rd(m,Jn,vo,!1)),uc(m))}function R5(m,b,S){if((fr&6)!==0)throw Error(r(327));var T=!S&&(b&127)===0&&(b&m.expiredLanes)===0||$e(m,b),F=T?soe(m,b):ZT(m,b,!0),I=T;do{if(F===0){Mp&&!T&&Rd(m,b,0,!1);break}else{if(S=m.current.alternate,I&&!aoe(S)){F=ZT(m,b,!1),I=!1;continue}if(F===2){if(I=b,m.errorRecoveryDisabledLanes&I)var re=0;else re=m.pendingLanes&-536870913,re=re!==0?re:re&536870912?536870912:0;if(re!==0){b=re;e:{var Pe=m;F=Ix;var Ve=Pe.current.memoizedState.isDehydrated;if(Ve&&(jp(Pe,re).flags|=256),re=ZT(Pe,re,!1),re!==2){if(qT&&!Ve){Pe.errorRecoveryDisabledLanes|=I,Cm|=I,F=4;break e}I=Vs,Vs=F,I!==null&&(Vs===null?Vs=I:Vs.push.apply(Vs,I))}F=re}if(I=!1,F!==2)continue}}if(F===1){jp(m,0),Rd(m,b,0,!0);break}e:{switch(T=m,I=F,I){case 0:case 1:throw Error(r(345));case 4:if((b&4194048)!==b)break;case 6:Rd(T,b,vo,!Pd);break e;case 2:Vs=null;break;case 3:case 5:break;default:throw Error(r(329))}if((b&62914560)===b&&(F=Mw+300-R(),10<F)){if(Rd(T,b,vo,!Pd),Re(T,0,!0)!==0)break e;uu=b,T.timeoutHandle=dU(F5.bind(null,T,S,Vs,Ew,WT,b,vo,Cm,Pp,Pd,I,"Throttled",-0,0),F);break e}F5(T,S,Vs,Ew,WT,b,vo,Cm,Pp,Pd,I,null,-0,0)}}break}while(!0);uc(m)}function F5(m,b,S,T,F,I,re,Pe,Ve,dt,vt,Ct,mt,gt){if(m.timeoutHandle=-1,Ct=b.subtreeFlags,Ct&8192||(Ct&16785408)===16785408){Ct={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Vt},A5(b,I,Ct);var Qt=(I&62914560)===I?Mw-R():(I&4194048)===I?E5-R():0;if(Qt=Hoe(Ct,Qt),Qt!==null){uu=I,m.cancelPendingCommit=Qt($5.bind(null,m,b,I,S,T,F,re,Pe,Ve,vt,Ct,null,mt,gt)),Rd(m,I,re,!dt);return}}$5(m,b,I,S,T,F,re,Pe,Ve)}function aoe(m){for(var b=m;;){var S=b.tag;if((S===0||S===11||S===15)&&b.flags&16384&&(S=b.updateQueue,S!==null&&(S=S.stores,S!==null)))for(var T=0;T<S.length;T++){var F=S[T],I=F.getSnapshot;F=F.value;try{if(!po(I(),F))return!1}catch{return!1}}if(S=b.child,b.subtreeFlags&16384&&S!==null)S.return=b,b=S;else{if(b===m)break;for(;b.sibling===null;){if(b.return===null||b.return===m)return!0;b=b.return}b.sibling.return=b.return,b=b.sibling}}return!0}function Rd(m,b,S,T){b&=~GT,b&=~Cm,m.suspendedLanes|=b,m.pingedLanes&=~b,T&&(m.warmLanes|=b),T=m.expirationTimes;for(var F=b;0<F;){var I=31-ge(F),re=1<<I;T[I]=-1,F&=~re}S!==0&&Ue(m,S,b)}function jw(){return(fr&6)===0?(Ux(0),!1):!0}function QT(){if(Kn!==null){if(Sr===0)var m=Kn.return;else m=Kn,Jc=gm=null,mT(m),Sp=null,Sx=0,m=Kn;for(;m!==null;)h5(m.alternate,m),m=m.return;Kn=null}}function jp(m,b){var S=m.timeoutHandle;S!==-1&&(m.timeoutHandle=-1,Noe(S)),S=m.cancelPendingCommit,S!==null&&(m.cancelPendingCommit=null,S()),uu=0,QT(),Br=m,Kn=S=Qc(m.current,null),Jn=b,Sr=0,yo=null,Pd=!1,Mp=$e(m,b),qT=!1,Pp=vo=GT=Cm=Ed=Na=0,Vs=Ix=null,WT=!1,(b&8)!==0&&(b|=b&32);var T=m.entangledLanes;if(T!==0)for(m=m.entanglements,T&=b;0<T;){var F=31-ge(T),I=1<<F;b|=m[F],T&=~I}return cu=b,J0(),S}function L5(m,b){Mn=null,G.H=Px,b===wp||b===ow?(b=ZI(),Sr=3):b===tT?(b=ZI(),Sr=4):Sr=b===MT?8:b!==null&&typeof b=="object"&&typeof b.then=="function"?6:1,yo=b,Kn===null&&(Na=1,ww(m,Uo(b,m.current)))}function O5(){var m=bo.current;return m===null?!0:(Jn&4194048)===Jn?Vo===null:(Jn&62914560)===Jn||(Jn&536870912)!==0?m===Vo:!1}function I5(){var m=G.H;return G.H=Px,m===null?Px:m}function z5(){var m=G.A;return G.A=noe,m}function Dw(){Na=4,Pd||(Jn&4194048)!==Jn&&bo.current!==null||(Mp=!0),(Ed&134217727)===0&&(Cm&134217727)===0||Br===null||Rd(Br,Jn,vo,!1)}function ZT(m,b,S){var T=fr;fr|=2;var F=I5(),I=z5();(Br!==m||Jn!==b)&&(Ew=null,jp(m,b)),b=!1;var re=Na;e:do try{if(Sr!==0&&Kn!==null){var Pe=Kn,Ve=yo;switch(Sr){case 8:QT(),re=6;break e;case 3:case 2:case 9:case 6:bo.current===null&&(b=!0);var dt=Sr;if(Sr=0,yo=null,Dp(m,Pe,Ve,dt),S&&Mp){re=0;break e}break;default:dt=Sr,Sr=0,yo=null,Dp(m,Pe,Ve,dt)}}ioe(),re=Na;break}catch(vt){L5(m,vt)}while(!0);return b&&m.shellSuspendCounter++,Jc=gm=null,fr=T,G.H=F,G.A=I,Kn===null&&(Br=null,Jn=0,J0()),re}function ioe(){for(;Kn!==null;)U5(Kn)}function soe(m,b){var S=fr;fr|=2;var T=I5(),F=z5();Br!==m||Jn!==b?(Ew=null,Pw=R()+500,jp(m,b)):Mp=$e(m,b);e:do try{if(Sr!==0&&Kn!==null){b=Kn;var I=yo;t:switch(Sr){case 1:Sr=0,yo=null,Dp(m,b,I,1);break;case 2:case 9:if(YI(I)){Sr=0,yo=null,B5(b);break}b=function(){Sr!==2&&Sr!==9||Br!==m||(Sr=7),uc(m)},I.then(b,b);break e;case 3:Sr=7;break e;case 4:Sr=5;break e;case 7:YI(I)?(Sr=0,yo=null,B5(b)):(Sr=0,yo=null,Dp(m,b,I,7));break;case 5:var re=null;switch(Kn.tag){case 26:re=Kn.memoizedState;case 5:case 27:var Pe=Kn;if(re?kU(re):Pe.stateNode.complete){Sr=0,yo=null;var Ve=Pe.sibling;if(Ve!==null)Kn=Ve;else{var dt=Pe.return;dt!==null?(Kn=dt,Rw(dt)):Kn=null}break t}}Sr=0,yo=null,Dp(m,b,I,5);break;case 6:Sr=0,yo=null,Dp(m,b,I,6);break;case 8:QT(),Na=6;break e;default:throw Error(r(462))}}ooe();break}catch(vt){L5(m,vt)}while(!0);return Jc=gm=null,G.H=T,G.A=F,fr=S,Kn!==null?0:(Br=null,Jn=0,J0(),Na)}function ooe(){for(;Kn!==null&&!be();)U5(Kn)}function U5(m){var b=u5(m.alternate,m,cu);m.memoizedProps=m.pendingProps,b===null?Rw(m):Kn=b}function B5(m){var b=m,S=b.alternate;switch(b.tag){case 15:case 0:b=a5(S,b,b.pendingProps,b.type,void 0,Jn);break;case 11:b=a5(S,b,b.pendingProps,b.type.render,b.ref,Jn);break;case 5:mT(b);default:h5(S,b),b=Kn=zI(b,cu),b=u5(S,b,cu)}m.memoizedProps=m.pendingProps,b===null?Rw(m):Kn=b}function Dp(m,b,S,T){Jc=gm=null,mT(b),Sp=null,Sx=0;var F=b.return;try{if(Xse(m,F,b,S,Jn)){Na=1,ww(m,Uo(S,m.current)),Kn=null;return}}catch(I){if(F!==null)throw Kn=F,I;Na=1,ww(m,Uo(S,m.current)),Kn=null;return}b.flags&32768?(nr||T===1?m=!0:Mp||(Jn&536870912)!==0?m=!1:(Pd=m=!0,(T===2||T===9||T===3||T===6)&&(T=bo.current,T!==null&&T.tag===13&&(T.flags|=16384))),H5(b,m)):Rw(b)}function Rw(m){var b=m;do{if((b.flags&32768)!==0){H5(b,Pd);return}m=b.return;var S=Zse(b.alternate,b,cu);if(S!==null){Kn=S;return}if(b=b.sibling,b!==null){Kn=b;return}Kn=b=m}while(b!==null);Na===0&&(Na=5)}function H5(m,b){do{var S=Jse(m.alternate,m);if(S!==null){S.flags&=32767,Kn=S;return}if(S=m.return,S!==null&&(S.flags|=32768,S.subtreeFlags=0,S.deletions=null),!b&&(m=m.sibling,m!==null)){Kn=m;return}Kn=m=S}while(m!==null);Na=6,Kn=null}function $5(m,b,S,T,F,I,re,Pe,Ve){m.cancelPendingCommit=null;do Fw();while(li!==0);if((fr&6)!==0)throw Error(r(327));if(b!==null){if(b===m.current)throw Error(r(177));if(I=b.lanes|b.childLanes,I|=UA,kt(m,S,I,re,Pe,Ve),m===Br&&(Kn=Br=null,Jn=0),Ep=b,Dd=m,uu=S,KT=I,XT=F,j5=T,(b.subtreeFlags&10256)!==0||(b.flags&10256)!==0?(m.callbackNode=null,m.callbackPriority=0,doe(le,function(){return K5(),null})):(m.callbackNode=null,m.callbackPriority=0),T=(b.flags&13878)!==0,(b.subtreeFlags&13878)!==0||T){T=G.T,G.T=null,F=z.p,z.p=2,re=fr,fr|=4;try{eoe(m,b,S)}finally{fr=re,z.p=F,G.T=T}}li=1,V5(),q5(),G5()}}function V5(){if(li===1){li=0;var m=Dd,b=Ep,S=(b.flags&13878)!==0;if((b.subtreeFlags&13878)!==0||S){S=G.T,G.T=null;var T=z.p;z.p=2;var F=fr;fr|=4;try{N5(b,m);var I=uM,re=PI(m.containerInfo),Pe=I.focusedElem,Ve=I.selectionRange;if(re!==Pe&&Pe&&Pe.ownerDocument&&MI(Pe.ownerDocument.documentElement,Pe)){if(Ve!==null&&FA(Pe)){var dt=Ve.start,vt=Ve.end;if(vt===void 0&&(vt=dt),"selectionStart"in Pe)Pe.selectionStart=dt,Pe.selectionEnd=Math.min(vt,Pe.value.length);else{var Ct=Pe.ownerDocument||document,mt=Ct&&Ct.defaultView||window;if(mt.getSelection){var gt=mt.getSelection(),Qt=Pe.textContent.length,hn=Math.min(Ve.start,Qt),Er=Ve.end===void 0?hn:Math.min(Ve.end,Qt);!gt.extend&&hn>Er&&(re=Er,Er=hn,hn=re);var rt=TI(Pe,hn),Qe=TI(Pe,Er);if(rt&&Qe&&(gt.rangeCount!==1||gt.anchorNode!==rt.node||gt.anchorOffset!==rt.offset||gt.focusNode!==Qe.node||gt.focusOffset!==Qe.offset)){var ut=Ct.createRange();ut.setStart(rt.node,rt.offset),gt.removeAllRanges(),hn>Er?(gt.addRange(ut),gt.extend(Qe.node,Qe.offset)):(ut.setEnd(Qe.node,Qe.offset),gt.addRange(ut))}}}}for(Ct=[],gt=Pe;gt=gt.parentNode;)gt.nodeType===1&&Ct.push({element:gt,left:gt.scrollLeft,top:gt.scrollTop});for(typeof Pe.focus=="function"&&Pe.focus(),Pe=0;Pe<Ct.length;Pe++){var St=Ct[Pe];St.element.scrollLeft=St.left,St.element.scrollTop=St.top}}Ww=!!cM,uM=cM=null}finally{fr=F,z.p=T,G.T=S}}m.current=b,li=2}}function q5(){if(li===2){li=0;var m=Dd,b=Ep,S=(b.flags&8772)!==0;if((b.subtreeFlags&8772)!==0||S){S=G.T,G.T=null;var T=z.p;z.p=2;var F=fr;fr|=4;try{y5(m,b.alternate,b)}finally{fr=F,z.p=T,G.T=S}}li=3}}function G5(){if(li===4||li===3){li=0,O();var m=Dd,b=Ep,S=uu,T=j5;(b.subtreeFlags&10256)!==0||(b.flags&10256)!==0?li=5:(li=0,Ep=Dd=null,W5(m,m.pendingLanes));var F=m.pendingLanes;if(F===0&&(jd=null),Cn(S),b=b.stateNode,xe&&typeof xe.onCommitFiberRoot=="function")try{xe.onCommitFiberRoot(pe,b,void 0,(b.current.flags&128)===128)}catch{}if(T!==null){b=G.T,F=z.p,z.p=2,G.T=null;try{for(var I=m.onRecoverableError,re=0;re<T.length;re++){var Pe=T[re];I(Pe.value,{componentStack:Pe.stack})}}finally{G.T=b,z.p=F}}(uu&3)!==0&&Fw(),uc(m),F=m.pendingLanes,(S&261930)!==0&&(F&42)!==0?m===YT?zx++:(zx=0,YT=m):zx=0,Ux(0)}}function W5(m,b){(m.pooledCacheLanes&=b)===0&&(b=m.pooledCache,b!=null&&(m.pooledCache=null,vx(b)))}function Fw(){return V5(),q5(),G5(),K5()}function K5(){if(li!==5)return!1;var m=Dd,b=KT;KT=0;var S=Cn(uu),T=G.T,F=z.p;try{z.p=32>S?32:S,G.T=null,S=XT,XT=null;var I=Dd,re=uu;if(li=0,Ep=Dd=null,uu=0,(fr&6)!==0)throw Error(r(331));var Pe=fr;if(fr|=4,M5(I.current),k5(I,I.current,re,S),fr=Pe,Ux(0,!1),xe&&typeof xe.onPostCommitFiberRoot=="function")try{xe.onPostCommitFiberRoot(pe,I)}catch{}return!0}finally{z.p=F,G.T=T,W5(m,b)}}function X5(m,b,S){b=Uo(S,b),b=TT(m.stateNode,b,2),m=kd(m,b,2),m!==null&&(It(m,2),uc(m))}function _r(m,b,S){if(m.tag===3)X5(m,m,S);else for(;b!==null;){if(b.tag===3){X5(b,m,S);break}else if(b.tag===1){var T=b.stateNode;if(typeof b.type.getDerivedStateFromError=="function"||typeof T.componentDidCatch=="function"&&(jd===null||!jd.has(T))){m=Uo(S,m),S=Yz(2),T=kd(b,S,2),T!==null&&(Qz(S,T,b,m),It(T,2),uc(T));break}}b=b.return}}function JT(m,b,S){var T=m.pingCache;if(T===null){T=m.pingCache=new roe;var F=new Set;T.set(b,F)}else F=T.get(b),F===void 0&&(F=new Set,T.set(b,F));F.has(S)||(qT=!0,F.add(S),m=loe.bind(null,m,b,S),b.then(m,m))}function loe(m,b,S){var T=m.pingCache;T!==null&&T.delete(b),m.pingedLanes|=m.suspendedLanes&S,m.warmLanes&=~S,Br===m&&(Jn&S)===S&&(Na===4||Na===3&&(Jn&62914560)===Jn&&300>R()-Mw?(fr&2)===0&&jp(m,0):GT|=S,Pp===Jn&&(Pp=0)),uc(m)}function Y5(m,b){b===0&&(b=At()),m=mm(m,b),m!==null&&(It(m,b),uc(m))}function coe(m){var b=m.memoizedState,S=0;b!==null&&(S=b.retryLane),Y5(m,S)}function uoe(m,b){var S=0;switch(m.tag){case 31:case 13:var T=m.stateNode,F=m.memoizedState;F!==null&&(S=F.retryLane);break;case 19:T=m.stateNode;break;case 22:T=m.stateNode._retryCache;break;default:throw Error(r(314))}T!==null&&T.delete(b),Y5(m,S)}function doe(m,b){return Le(m,b)}var Lw=null,Rp=null,eM=!1,Ow=!1,tM=!1,Fd=0;function uc(m){m!==Rp&&m.next===null&&(Rp===null?Lw=Rp=m:Rp=Rp.next=m),Ow=!0,eM||(eM=!0,moe())}function Ux(m,b){if(!tM&&Ow){tM=!0;do for(var S=!1,T=Lw;T!==null;){if(m!==0){var F=T.pendingLanes;if(F===0)var I=0;else{var re=T.suspendedLanes,Pe=T.pingedLanes;I=(1<<31-ge(42|m)+1)-1,I&=F&~(re&~Pe),I=I&201326741?I&201326741|1:I?I|2:0}I!==0&&(S=!0,eU(T,I))}else I=Jn,I=Re(T,T===Br?I:0,T.cancelPendingCommit!==null||T.timeoutHandle!==-1),(I&3)===0||$e(T,I)||(S=!0,eU(T,I));T=T.next}while(S);tM=!1}}function hoe(){Q5()}function Q5(){Ow=eM=!1;var m=0;Fd!==0&&_oe()&&(m=Fd);for(var b=R(),S=null,T=Lw;T!==null;){var F=T.next,I=Z5(T,b);I===0?(T.next=null,S===null?Lw=F:S.next=F,F===null&&(Rp=S)):(S=T,(m!==0||(I&3)!==0)&&(Ow=!0)),T=F}li!==0&&li!==5||Ux(m),Fd!==0&&(Fd=0)}function Z5(m,b){for(var S=m.suspendedLanes,T=m.pingedLanes,F=m.expirationTimes,I=m.pendingLanes&-62914561;0<I;){var re=31-ge(I),Pe=1<<re,Ve=F[re];Ve===-1?((Pe&S)===0||(Pe&T)!==0)&&(F[re]=ht(Pe,b)):Ve<=b&&(m.expiredLanes|=Pe),I&=~Pe}if(b=Br,S=Jn,S=Re(m,m===b?S:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),T=m.callbackNode,S===0||m===b&&(Sr===2||Sr===9)||m.cancelPendingCommit!==null)return T!==null&&T!==null&&Ne(T),m.callbackNode=null,m.callbackPriority=0;if((S&3)===0||$e(m,S)){if(b=S&-S,b===m.callbackPriority)return b;switch(T!==null&&Ne(T),Cn(S)){case 2:case 8:S=fe;break;case 32:S=le;break;case 268435456:S=Ie;break;default:S=le}return T=J5.bind(null,m),S=Le(S,T),m.callbackPriority=b,m.callbackNode=S,b}return T!==null&&T!==null&&Ne(T),m.callbackPriority=2,m.callbackNode=null,2}function J5(m,b){if(li!==0&&li!==5)return m.callbackNode=null,m.callbackPriority=0,null;var S=m.callbackNode;if(Fw()&&m.callbackNode!==S)return null;var T=Jn;return T=Re(m,m===Br?T:0,m.cancelPendingCommit!==null||m.timeoutHandle!==-1),T===0?null:(R5(m,T,b),Z5(m,R()),m.callbackNode!=null&&m.callbackNode===S?J5.bind(null,m):null)}function eU(m,b){if(Fw())return null;R5(m,b,!0)}function moe(){Coe(function(){(fr&6)!==0?Le(J,hoe):Q5()})}function nM(){if(Fd===0){var m=yp;m===0&&(m=tt,tt<<=1,(tt&261888)===0&&(tt=256)),Fd=m}return Fd}function tU(m){return m==null||typeof m=="symbol"||typeof m=="boolean"?null:typeof m=="function"?m:Va(""+m)}function nU(m,b){var S=b.ownerDocument.createElement("input");return S.name=b.name,S.value=b.value,m.id&&S.setAttribute("form",m.id),b.parentNode.insertBefore(S,b),m=new FormData(m),S.parentNode.removeChild(S),m}function foe(m,b,S,T,F){if(b==="submit"&&S&&S.stateNode===F){var I=tU((F[dr]||null).action),re=T.submitter;re&&(b=(b=re[dr]||null)?tU(b.formAction):re.getAttribute("formAction"),b!==null&&(I=b,re=null));var Pe=new um("action","action",null,T,F);m.push({event:Pe,listeners:[{instance:null,listener:function(){if(T.defaultPrevented){if(Fd!==0){var Ve=re?nU(F,re):new FormData(F);ST(S,{pending:!0,data:Ve,method:F.method,action:I},null,Ve)}}else typeof I=="function"&&(Pe.preventDefault(),Ve=re?nU(F,re):new FormData(F),ST(S,{pending:!0,data:Ve,method:F.method,action:I},I,Ve))},currentTarget:F}]})}}for(var rM=0;rM<zA.length;rM++){var aM=zA[rM],poe=aM.toLowerCase(),goe=aM[0].toUpperCase()+aM.slice(1);Pl(poe,"on"+goe)}Pl(DI,"onAnimationEnd"),Pl(RI,"onAnimationIteration"),Pl(FI,"onAnimationStart"),Pl("dblclick","onDoubleClick"),Pl("focusin","onFocus"),Pl("focusout","onBlur"),Pl(jse,"onTransitionRun"),Pl(Dse,"onTransitionStart"),Pl(Rse,"onTransitionCancel"),Pl(LI,"onTransitionEnd"),at("onMouseEnter",["mouseout","mouseover"]),at("onMouseLeave",["mouseout","mouseover"]),at("onPointerEnter",["pointerout","pointerover"]),at("onPointerLeave",["pointerout","pointerover"]),pt("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),pt("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),pt("onBeforeInput",["compositionend","keypress","textInput","paste"]),pt("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),pt("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),pt("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Bx="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),boe=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Bx));function rU(m,b){b=(b&4)!==0;for(var S=0;S<m.length;S++){var T=m[S],F=T.event;T=T.listeners;e:{var I=void 0;if(b)for(var re=T.length-1;0<=re;re--){var Pe=T[re],Ve=Pe.instance,dt=Pe.currentTarget;if(Pe=Pe.listener,Ve!==I&&F.isPropagationStopped())break e;I=Pe,F.currentTarget=dt;try{I(F)}catch(vt){Z0(vt)}F.currentTarget=null,I=Ve}else for(re=0;re<T.length;re++){if(Pe=T[re],Ve=Pe.instance,dt=Pe.currentTarget,Pe=Pe.listener,Ve!==I&&F.isPropagationStopped())break e;I=Pe,F.currentTarget=dt;try{I(F)}catch(vt){Z0(vt)}F.currentTarget=null,I=Ve}}}}function Xn(m,b){var S=b[si];S===void 0&&(S=b[si]=new Set);var T=m+"__bubble";S.has(T)||(aU(b,m,2,!1),S.add(T))}function iM(m,b,S){var T=0;b&&(T|=4),aU(S,m,T,b)}var Iw="_reactListening"+Math.random().toString(36).slice(2);function sM(m){if(!m[Iw]){m[Iw]=!0,Te.forEach(function(S){S!=="selectionchange"&&(boe.has(S)||iM(S,!1,m),iM(S,!0,m))});var b=m.nodeType===9?m:m.ownerDocument;b===null||b[Iw]||(b[Iw]=!0,iM("selectionchange",!1,b))}}function aU(m,b,S,T){switch(DU(b)){case 2:var F=qoe;break;case 8:F=Goe;break;default:F=wM}S=F.bind(null,b,S,m),F=void 0,!mr||b!=="touchstart"&&b!=="touchmove"&&b!=="wheel"||(F=!0),T?F!==void 0?m.addEventListener(b,S,{capture:!0,passive:F}):m.addEventListener(b,S,!0):F!==void 0?m.addEventListener(b,S,{passive:F}):m.addEventListener(b,S,!1)}function oM(m,b,S,T,F){var I=T;if((b&1)===0&&(b&2)===0&&T!==null)e:for(;;){if(T===null)return;var re=T.tag;if(re===3||re===4){var Pe=T.stateNode.containerInfo;if(Pe===F)break;if(re===4)for(re=T.return;re!==null;){var Ve=re.tag;if((Ve===3||Ve===4)&&re.stateNode.containerInfo===F)return;re=re.return}for(;Pe!==null;){if(re=zt(Pe),re===null)return;if(Ve=re.tag,Ve===5||Ve===6||Ve===26||Ve===27){T=I=re;continue e}Pe=Pe.parentNode}}T=T.return}oi(function(){var dt=I,vt=Ss(S),Ct=[];e:{var mt=OI.get(m);if(mt!==void 0){var gt=um,Qt=m;switch(m){case"keypress":if(fa(S)===0)break e;case"keydown":case"keyup":gt=use;break;case"focusin":Qt="focus",gt=fo;break;case"focusout":Qt="blur",gt=fo;break;case"beforeblur":case"afterblur":gt=fo;break;case"click":if(S.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":gt=sa;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":gt=Yc;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":gt=mse;break;case DI:case RI:case FI:gt=PA;break;case LI:gt=pse;break;case"scroll":case"scrollend":gt=Y0;break;case"wheel":gt=bse;break;case"copy":case"cut":case"paste":gt=rse;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":gt=fI;break;case"toggle":case"beforetoggle":gt=yse}var hn=(b&4)!==0,Er=!hn&&(m==="scroll"||m==="scrollend"),rt=hn?mt!==null?mt+"Capture":null:mt;hn=[];for(var Qe=dt,ut;Qe!==null;){var St=Qe;if(ut=St.stateNode,St=St.tag,St!==5&&St!==26&&St!==27||ut===null||rt===null||(St=Sa(Qe,rt),St!=null&&hn.push(Hx(Qe,St,ut))),Er)break;Qe=Qe.return}0<hn.length&&(mt=new gt(mt,Qt,null,S,vt),Ct.push({event:mt,listeners:hn}))}}if((b&7)===0){e:{if(mt=m==="mouseover"||m==="pointerover",gt=m==="mouseout"||m==="pointerout",mt&&S!==xn&&(Qt=S.relatedTarget||S.fromElement)&&(zt(Qt)||Qt[Tr]))break e;if((gt||mt)&&(mt=vt.window===vt?vt:(mt=vt.ownerDocument)?mt.defaultView||mt.parentWindow:window,gt?(Qt=S.relatedTarget||S.toElement,gt=dt,Qt=Qt?zt(Qt):null,Qt!==null&&(Er=s(Qt),hn=Qt.tag,Qt!==Er||hn!==5&&hn!==27&&hn!==6)&&(Qt=null)):(gt=null,Qt=dt),gt!==Qt)){if(hn=sa,St="onMouseLeave",rt="onMouseEnter",Qe="mouse",(m==="pointerout"||m==="pointerover")&&(hn=fI,St="onPointerLeave",rt="onPointerEnter",Qe="pointer"),Er=gt==null?mt:He(gt),ut=Qt==null?mt:He(Qt),mt=new hn(St,Qe+"leave",gt,S,vt),mt.target=Er,mt.relatedTarget=ut,St=null,zt(vt)===dt&&(hn=new hn(rt,Qe+"enter",Qt,S,vt),hn.target=ut,hn.relatedTarget=Er,St=hn),Er=St,gt&&Qt)t:{for(hn=xoe,rt=gt,Qe=Qt,ut=0,St=rt;St;St=hn(St))ut++;St=0;for(var on=Qe;on;on=hn(on))St++;for(;0<ut-St;)rt=hn(rt),ut--;for(;0<St-ut;)Qe=hn(Qe),St--;for(;ut--;){if(rt===Qe||Qe!==null&&rt===Qe.alternate){hn=rt;break t}rt=hn(rt),Qe=hn(Qe)}hn=null}else hn=null;gt!==null&&iU(Ct,mt,gt,hn,!1),Qt!==null&&Er!==null&&iU(Ct,Er,Qt,hn,!0)}}e:{if(mt=dt?He(dt):window,gt=mt.nodeName&&mt.nodeName.toLowerCase(),gt==="select"||gt==="input"&&mt.type==="file")var or=SI;else if(vI(mt))if(_I)or=Mse;else{or=Ase;var tn=kse}else gt=mt.nodeName,!gt||gt.toLowerCase()!=="input"||mt.type!=="checkbox"&&mt.type!=="radio"?dt&&wr(dt.elementType)&&(or=SI):or=Tse;if(or&&(or=or(m,dt))){wI(Ct,or,S,vt);break e}tn&&tn(m,mt,dt),m==="focusout"&&dt&&mt.type==="number"&&dt.memoizedProps.value!=null&&va(mt,"number",mt.value)}switch(tn=dt?He(dt):window,m){case"focusin":(vI(tn)||tn.contentEditable==="true")&&(dp=tn,LA=dt,bx=null);break;case"focusout":bx=LA=dp=null;break;case"mousedown":OA=!0;break;case"contextmenu":case"mouseup":case"dragend":OA=!1,EI(Ct,S,vt);break;case"selectionchange":if(Ese)break;case"keydown":case"keyup":EI(Ct,S,vt)}var jn;if(jA)e:{switch(m){case"compositionstart":var er="onCompositionStart";break e;case"compositionend":er="onCompositionEnd";break e;case"compositionupdate":er="onCompositionUpdate";break e}er=void 0}else up?xI(m,S)&&(er="onCompositionEnd"):m==="keydown"&&S.keyCode===229&&(er="onCompositionStart");er&&(pI&&S.locale!=="ko"&&(up||er!=="onCompositionStart"?er==="onCompositionEnd"&&up&&(jn=Ur()):(qa=vt,Oa="value"in qa?qa.value:qa.textContent,up=!0)),tn=zw(dt,er),0<tn.length&&(er=new mI(er,m,null,S,vt),Ct.push({event:er,listeners:tn}),jn?er.data=jn:(jn=yI(S),jn!==null&&(er.data=jn)))),(jn=wse?Sse(m,S):_se(m,S))&&(er=zw(dt,"onBeforeInput"),0<er.length&&(tn=new mI("onBeforeInput","beforeinput",null,S,vt),Ct.push({event:tn,listeners:er}),tn.data=jn)),foe(Ct,m,dt,S,vt)}rU(Ct,b)})}function Hx(m,b,S){return{instance:m,listener:b,currentTarget:S}}function zw(m,b){for(var S=b+"Capture",T=[];m!==null;){var F=m,I=F.stateNode;if(F=F.tag,F!==5&&F!==26&&F!==27||I===null||(F=Sa(m,S),F!=null&&T.unshift(Hx(m,F,I)),F=Sa(m,b),F!=null&&T.push(Hx(m,F,I))),m.tag===3)return T;m=m.return}return[]}function xoe(m){if(m===null)return null;do m=m.return;while(m&&m.tag!==5&&m.tag!==27);return m||null}function iU(m,b,S,T,F){for(var I=b._reactName,re=[];S!==null&&S!==T;){var Pe=S,Ve=Pe.alternate,dt=Pe.stateNode;if(Pe=Pe.tag,Ve!==null&&Ve===T)break;Pe!==5&&Pe!==26&&Pe!==27||dt===null||(Ve=dt,F?(dt=Sa(S,I),dt!=null&&re.unshift(Hx(S,dt,Ve))):F||(dt=Sa(S,I),dt!=null&&re.push(Hx(S,dt,Ve)))),S=S.return}re.length!==0&&m.push({event:b,listeners:re})}var yoe=/\r\n?/g,voe=/\u0000|\uFFFD/g;function sU(m){return(typeof m=="string"?m:""+m).replace(yoe,`
  9. `).replace(voe,"")}function oU(m,b){return b=sU(b),sU(m)===b}function Pr(m,b,S,T,F,I){switch(S){case"children":typeof T=="string"?b==="body"||b==="textarea"&&T===""||Ft(m,T):(typeof T=="number"||typeof T=="bigint")&&b!=="body"&&Ft(m,""+T);break;case"className":Zt(m,"class",T);break;case"tabIndex":Zt(m,"tabindex",T);break;case"dir":case"role":case"viewBox":case"width":case"height":Zt(m,S,T);break;case"style":Zn(m,T,I);break;case"data":if(b!=="object"){Zt(m,"data",T);break}case"src":case"href":if(T===""&&(b!=="a"||S!=="href")){m.removeAttribute(S);break}if(T==null||typeof T=="function"||typeof T=="symbol"||typeof T=="boolean"){m.removeAttribute(S);break}T=Va(""+T),m.setAttribute(S,T);break;case"action":case"formAction":if(typeof T=="function"){m.setAttribute(S,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof I=="function"&&(S==="formAction"?(b!=="input"&&Pr(m,b,"name",F.name,F,null),Pr(m,b,"formEncType",F.formEncType,F,null),Pr(m,b,"formMethod",F.formMethod,F,null),Pr(m,b,"formTarget",F.formTarget,F,null)):(Pr(m,b,"encType",F.encType,F,null),Pr(m,b,"method",F.method,F,null),Pr(m,b,"target",F.target,F,null)));if(T==null||typeof T=="symbol"||typeof T=="boolean"){m.removeAttribute(S);break}T=Va(""+T),m.setAttribute(S,T);break;case"onClick":T!=null&&(m.onclick=Vt);break;case"onScroll":T!=null&&Xn("scroll",m);break;case"onScrollEnd":T!=null&&Xn("scrollend",m);break;case"dangerouslySetInnerHTML":if(T!=null){if(typeof T!="object"||!("__html"in T))throw Error(r(61));if(S=T.__html,S!=null){if(F.children!=null)throw Error(r(60));m.innerHTML=S}}break;case"multiple":m.multiple=T&&typeof T!="function"&&typeof T!="symbol";break;case"muted":m.muted=T&&typeof T!="function"&&typeof T!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(T==null||typeof T=="function"||typeof T=="boolean"||typeof T=="symbol"){m.removeAttribute("xlink:href");break}S=Va(""+T),m.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",S);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":T!=null&&typeof T!="function"&&typeof T!="symbol"?m.setAttribute(S,""+T):m.removeAttribute(S);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":T&&typeof T!="function"&&typeof T!="symbol"?m.setAttribute(S,""):m.removeAttribute(S);break;case"capture":case"download":T===!0?m.setAttribute(S,""):T!==!1&&T!=null&&typeof T!="function"&&typeof T!="symbol"?m.setAttribute(S,T):m.removeAttribute(S);break;case"cols":case"rows":case"size":case"span":T!=null&&typeof T!="function"&&typeof T!="symbol"&&!isNaN(T)&&1<=T?m.setAttribute(S,T):m.removeAttribute(S);break;case"rowSpan":case"start":T==null||typeof T=="function"||typeof T=="symbol"||isNaN(T)?m.removeAttribute(S):m.setAttribute(S,T);break;case"popover":Xn("beforetoggle",m),Xn("toggle",m),sn(m,"popover",T);break;case"xlinkActuate":un(m,"http://www.w3.org/1999/xlink","xlink:actuate",T);break;case"xlinkArcrole":un(m,"http://www.w3.org/1999/xlink","xlink:arcrole",T);break;case"xlinkRole":un(m,"http://www.w3.org/1999/xlink","xlink:role",T);break;case"xlinkShow":un(m,"http://www.w3.org/1999/xlink","xlink:show",T);break;case"xlinkTitle":un(m,"http://www.w3.org/1999/xlink","xlink:title",T);break;case"xlinkType":un(m,"http://www.w3.org/1999/xlink","xlink:type",T);break;case"xmlBase":un(m,"http://www.w3.org/XML/1998/namespace","xml:base",T);break;case"xmlLang":un(m,"http://www.w3.org/XML/1998/namespace","xml:lang",T);break;case"xmlSpace":un(m,"http://www.w3.org/XML/1998/namespace","xml:space",T);break;case"is":sn(m,"is",T);break;case"innerText":case"textContent":break;default:(!(2<S.length)||S[0]!=="o"&&S[0]!=="O"||S[1]!=="n"&&S[1]!=="N")&&(S=hr.get(S)||S,sn(m,S,T))}}function lM(m,b,S,T,F,I){switch(S){case"style":Zn(m,T,I);break;case"dangerouslySetInnerHTML":if(T!=null){if(typeof T!="object"||!("__html"in T))throw Error(r(61));if(S=T.__html,S!=null){if(F.children!=null)throw Error(r(60));m.innerHTML=S}}break;case"children":typeof T=="string"?Ft(m,T):(typeof T=="number"||typeof T=="bigint")&&Ft(m,""+T);break;case"onScroll":T!=null&&Xn("scroll",m);break;case"onScrollEnd":T!=null&&Xn("scrollend",m);break;case"onClick":T!=null&&(m.onclick=Vt);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!lt.hasOwnProperty(S))e:{if(S[0]==="o"&&S[1]==="n"&&(F=S.endsWith("Capture"),b=S.slice(2,F?S.length-7:void 0),I=m[dr]||null,I=I!=null?I[S]:null,typeof I=="function"&&m.removeEventListener(b,I,F),typeof T=="function")){typeof I!="function"&&I!==null&&(S in m?m[S]=null:m.hasAttribute(S)&&m.removeAttribute(S)),m.addEventListener(b,T,F);break e}S in m?m[S]=T:T===!0?m.setAttribute(S,""):sn(m,S,T)}}}function Hi(m,b,S){switch(b){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Xn("error",m),Xn("load",m);var T=!1,F=!1,I;for(I in S)if(S.hasOwnProperty(I)){var re=S[I];if(re!=null)switch(I){case"src":T=!0;break;case"srcSet":F=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(r(137,b));default:Pr(m,b,I,re,S,null)}}F&&Pr(m,b,"srcSet",S.srcSet,S,null),T&&Pr(m,b,"src",S.src,S,null);return;case"input":Xn("invalid",m);var Pe=I=re=F=null,Ve=null,dt=null;for(T in S)if(S.hasOwnProperty(T)){var vt=S[T];if(vt!=null)switch(T){case"name":F=vt;break;case"type":re=vt;break;case"checked":Ve=vt;break;case"defaultChecked":dt=vt;break;case"value":I=vt;break;case"defaultValue":Pe=vt;break;case"children":case"dangerouslySetInnerHTML":if(vt!=null)throw Error(r(137,b));break;default:Pr(m,b,T,vt,S,null)}}Sn(m,I,Pe,Ve,dt,re,F,!1);return;case"select":Xn("invalid",m),T=re=I=null;for(F in S)if(S.hasOwnProperty(F)&&(Pe=S[F],Pe!=null))switch(F){case"value":I=Pe;break;case"defaultValue":re=Pe;break;case"multiple":T=Pe;default:Pr(m,b,F,Pe,S,null)}b=I,S=re,m.multiple=!!T,b!=null?sr(m,!!T,b,!1):S!=null&&sr(m,!!T,S,!0);return;case"textarea":Xn("invalid",m),I=F=T=null;for(re in S)if(S.hasOwnProperty(re)&&(Pe=S[re],Pe!=null))switch(re){case"value":T=Pe;break;case"defaultValue":F=Pe;break;case"children":I=Pe;break;case"dangerouslySetInnerHTML":if(Pe!=null)throw Error(r(91));break;default:Pr(m,b,re,Pe,S,null)}xt(m,T,F,I);return;case"option":for(Ve in S)S.hasOwnProperty(Ve)&&(T=S[Ve],T!=null)&&(Ve==="selected"?m.selected=T&&typeof T!="function"&&typeof T!="symbol":Pr(m,b,Ve,T,S,null));return;case"dialog":Xn("beforetoggle",m),Xn("toggle",m),Xn("cancel",m),Xn("close",m);break;case"iframe":case"object":Xn("load",m);break;case"video":case"audio":for(T=0;T<Bx.length;T++)Xn(Bx[T],m);break;case"image":Xn("error",m),Xn("load",m);break;case"details":Xn("toggle",m);break;case"embed":case"source":case"link":Xn("error",m),Xn("load",m);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(dt in S)if(S.hasOwnProperty(dt)&&(T=S[dt],T!=null))switch(dt){case"children":case"dangerouslySetInnerHTML":throw Error(r(137,b));default:Pr(m,b,dt,T,S,null)}return;default:if(wr(b)){for(vt in S)S.hasOwnProperty(vt)&&(T=S[vt],T!==void 0&&lM(m,b,vt,T,S,void 0));return}}for(Pe in S)S.hasOwnProperty(Pe)&&(T=S[Pe],T!=null&&Pr(m,b,Pe,T,S,null))}function woe(m,b,S,T){switch(b){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var F=null,I=null,re=null,Pe=null,Ve=null,dt=null,vt=null;for(gt in S){var Ct=S[gt];if(S.hasOwnProperty(gt)&&Ct!=null)switch(gt){case"checked":break;case"value":break;case"defaultValue":Ve=Ct;default:T.hasOwnProperty(gt)||Pr(m,b,gt,null,T,Ct)}}for(var mt in T){var gt=T[mt];if(Ct=S[mt],T.hasOwnProperty(mt)&&(gt!=null||Ct!=null))switch(mt){case"type":I=gt;break;case"name":F=gt;break;case"checked":dt=gt;break;case"defaultChecked":vt=gt;break;case"value":re=gt;break;case"defaultValue":Pe=gt;break;case"children":case"dangerouslySetInnerHTML":if(gt!=null)throw Error(r(137,b));break;default:gt!==Ct&&Pr(m,b,mt,gt,T,Ct)}}ia(m,re,Pe,Ve,dt,vt,I,F);return;case"select":gt=re=Pe=mt=null;for(I in S)if(Ve=S[I],S.hasOwnProperty(I)&&Ve!=null)switch(I){case"value":break;case"multiple":gt=Ve;default:T.hasOwnProperty(I)||Pr(m,b,I,null,T,Ve)}for(F in T)if(I=T[F],Ve=S[F],T.hasOwnProperty(F)&&(I!=null||Ve!=null))switch(F){case"value":mt=I;break;case"defaultValue":Pe=I;break;case"multiple":re=I;default:I!==Ve&&Pr(m,b,F,I,T,Ve)}b=Pe,S=re,T=gt,mt!=null?sr(m,!!S,mt,!1):!!T!=!!S&&(b!=null?sr(m,!!S,b,!0):sr(m,!!S,S?[]:"",!1));return;case"textarea":gt=mt=null;for(Pe in S)if(F=S[Pe],S.hasOwnProperty(Pe)&&F!=null&&!T.hasOwnProperty(Pe))switch(Pe){case"value":break;case"children":break;default:Pr(m,b,Pe,null,T,F)}for(re in T)if(F=T[re],I=S[re],T.hasOwnProperty(re)&&(F!=null||I!=null))switch(re){case"value":mt=F;break;case"defaultValue":gt=F;break;case"children":break;case"dangerouslySetInnerHTML":if(F!=null)throw Error(r(91));break;default:F!==I&&Pr(m,b,re,F,T,I)}ma(m,mt,gt);return;case"option":for(var Qt in S)mt=S[Qt],S.hasOwnProperty(Qt)&&mt!=null&&!T.hasOwnProperty(Qt)&&(Qt==="selected"?m.selected=!1:Pr(m,b,Qt,null,T,mt));for(Ve in T)mt=T[Ve],gt=S[Ve],T.hasOwnProperty(Ve)&&mt!==gt&&(mt!=null||gt!=null)&&(Ve==="selected"?m.selected=mt&&typeof mt!="function"&&typeof mt!="symbol":Pr(m,b,Ve,mt,T,gt));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var hn in S)mt=S[hn],S.hasOwnProperty(hn)&&mt!=null&&!T.hasOwnProperty(hn)&&Pr(m,b,hn,null,T,mt);for(dt in T)if(mt=T[dt],gt=S[dt],T.hasOwnProperty(dt)&&mt!==gt&&(mt!=null||gt!=null))switch(dt){case"children":case"dangerouslySetInnerHTML":if(mt!=null)throw Error(r(137,b));break;default:Pr(m,b,dt,mt,T,gt)}return;default:if(wr(b)){for(var Er in S)mt=S[Er],S.hasOwnProperty(Er)&&mt!==void 0&&!T.hasOwnProperty(Er)&&lM(m,b,Er,void 0,T,mt);for(vt in T)mt=T[vt],gt=S[vt],!T.hasOwnProperty(vt)||mt===gt||mt===void 0&&gt===void 0||lM(m,b,vt,mt,T,gt);return}}for(var rt in S)mt=S[rt],S.hasOwnProperty(rt)&&mt!=null&&!T.hasOwnProperty(rt)&&Pr(m,b,rt,null,T,mt);for(Ct in T)mt=T[Ct],gt=S[Ct],!T.hasOwnProperty(Ct)||mt===gt||mt==null&&gt==null||Pr(m,b,Ct,mt,T,gt)}function lU(m){switch(m){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function Soe(){if(typeof performance.getEntriesByType=="function"){for(var m=0,b=0,S=performance.getEntriesByType("resource"),T=0;T<S.length;T++){var F=S[T],I=F.transferSize,re=F.initiatorType,Pe=F.duration;if(I&&Pe&&lU(re)){for(re=0,Pe=F.responseEnd,T+=1;T<S.length;T++){var Ve=S[T],dt=Ve.startTime;if(dt>Pe)break;var vt=Ve.transferSize,Ct=Ve.initiatorType;vt&&lU(Ct)&&(Ve=Ve.responseEnd,re+=vt*(Ve<Pe?1:(Pe-dt)/(Ve-dt)))}if(--T,b+=8*(I+re)/(F.duration/1e3),m++,10<m)break}}if(0<m)return b/m/1e6}return navigator.connection&&(m=navigator.connection.downlink,typeof m=="number")?m:5}var cM=null,uM=null;function Uw(m){return m.nodeType===9?m:m.ownerDocument}function cU(m){switch(m){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function uU(m,b){if(m===0)switch(b){case"svg":return 1;case"math":return 2;default:return 0}return m===1&&b==="foreignObject"?0:m}function dM(m,b){return m==="textarea"||m==="noscript"||typeof b.children=="string"||typeof b.children=="number"||typeof b.children=="bigint"||typeof b.dangerouslySetInnerHTML=="object"&&b.dangerouslySetInnerHTML!==null&&b.dangerouslySetInnerHTML.__html!=null}var hM=null;function _oe(){var m=window.event;return m&&m.type==="popstate"?m===hM?!1:(hM=m,!0):(hM=null,!1)}var dU=typeof setTimeout=="function"?setTimeout:void 0,Noe=typeof clearTimeout=="function"?clearTimeout:void 0,hU=typeof Promise=="function"?Promise:void 0,Coe=typeof queueMicrotask=="function"?queueMicrotask:typeof hU<"u"?function(m){return hU.resolve(null).then(m).catch(koe)}:dU;function koe(m){setTimeout(function(){throw m})}function Ld(m){return m==="head"}function mU(m,b){var S=b,T=0;do{var F=S.nextSibling;if(m.removeChild(S),F&&F.nodeType===8)if(S=F.data,S==="/$"||S==="/&"){if(T===0){m.removeChild(F),Ip(b);return}T--}else if(S==="$"||S==="$?"||S==="$~"||S==="$!"||S==="&")T++;else if(S==="html")$x(m.ownerDocument.documentElement);else if(S==="head"){S=m.ownerDocument.head,$x(S);for(var I=S.firstChild;I;){var re=I.nextSibling,Pe=I.nodeName;I[ot]||Pe==="SCRIPT"||Pe==="STYLE"||Pe==="LINK"&&I.rel.toLowerCase()==="stylesheet"||S.removeChild(I),I=re}}else S==="body"&&$x(m.ownerDocument.body);S=F}while(S);Ip(b)}function fU(m,b){var S=m;m=0;do{var T=S.nextSibling;if(S.nodeType===1?b?(S._stashedDisplay=S.style.display,S.style.display="none"):(S.style.display=S._stashedDisplay||"",S.getAttribute("style")===""&&S.removeAttribute("style")):S.nodeType===3&&(b?(S._stashedText=S.nodeValue,S.nodeValue=""):S.nodeValue=S._stashedText||""),T&&T.nodeType===8)if(S=T.data,S==="/$"){if(m===0)break;m--}else S!=="$"&&S!=="$?"&&S!=="$~"&&S!=="$!"||m++;S=T}while(S)}function mM(m){var b=m.firstChild;for(b&&b.nodeType===10&&(b=b.nextSibling);b;){var S=b;switch(b=b.nextSibling,S.nodeName){case"HTML":case"HEAD":case"BODY":mM(S),Ge(S);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(S.rel.toLowerCase()==="stylesheet")continue}m.removeChild(S)}}function Aoe(m,b,S,T){for(;m.nodeType===1;){var F=S;if(m.nodeName.toLowerCase()!==b.toLowerCase()){if(!T&&(m.nodeName!=="INPUT"||m.type!=="hidden"))break}else if(T){if(!m[ot])switch(b){case"meta":if(!m.hasAttribute("itemprop"))break;return m;case"link":if(I=m.getAttribute("rel"),I==="stylesheet"&&m.hasAttribute("data-precedence"))break;if(I!==F.rel||m.getAttribute("href")!==(F.href==null||F.href===""?null:F.href)||m.getAttribute("crossorigin")!==(F.crossOrigin==null?null:F.crossOrigin)||m.getAttribute("title")!==(F.title==null?null:F.title))break;return m;case"style":if(m.hasAttribute("data-precedence"))break;return m;case"script":if(I=m.getAttribute("src"),(I!==(F.src==null?null:F.src)||m.getAttribute("type")!==(F.type==null?null:F.type)||m.getAttribute("crossorigin")!==(F.crossOrigin==null?null:F.crossOrigin))&&I&&m.hasAttribute("async")&&!m.hasAttribute("itemprop"))break;return m;default:return m}}else if(b==="input"&&m.type==="hidden"){var I=F.name==null?null:""+F.name;if(F.type==="hidden"&&m.getAttribute("name")===I)return m}else return m;if(m=qo(m.nextSibling),m===null)break}return null}function Toe(m,b,S){if(b==="")return null;for(;m.nodeType!==3;)if((m.nodeType!==1||m.nodeName!=="INPUT"||m.type!=="hidden")&&!S||(m=qo(m.nextSibling),m===null))return null;return m}function pU(m,b){for(;m.nodeType!==8;)if((m.nodeType!==1||m.nodeName!=="INPUT"||m.type!=="hidden")&&!b||(m=qo(m.nextSibling),m===null))return null;return m}function fM(m){return m.data==="$?"||m.data==="$~"}function pM(m){return m.data==="$!"||m.data==="$?"&&m.ownerDocument.readyState!=="loading"}function Moe(m,b){var S=m.ownerDocument;if(m.data==="$~")m._reactRetry=b;else if(m.data!=="$?"||S.readyState!=="loading")b();else{var T=function(){b(),S.removeEventListener("DOMContentLoaded",T)};S.addEventListener("DOMContentLoaded",T),m._reactRetry=T}}function qo(m){for(;m!=null;m=m.nextSibling){var b=m.nodeType;if(b===1||b===3)break;if(b===8){if(b=m.data,b==="$"||b==="$!"||b==="$?"||b==="$~"||b==="&"||b==="F!"||b==="F")break;if(b==="/$"||b==="/&")return null}}return m}var gM=null;function gU(m){m=m.nextSibling;for(var b=0;m;){if(m.nodeType===8){var S=m.data;if(S==="/$"||S==="/&"){if(b===0)return qo(m.nextSibling);b--}else S!=="$"&&S!=="$!"&&S!=="$?"&&S!=="$~"&&S!=="&"||b++}m=m.nextSibling}return null}function bU(m){m=m.previousSibling;for(var b=0;m;){if(m.nodeType===8){var S=m.data;if(S==="$"||S==="$!"||S==="$?"||S==="$~"||S==="&"){if(b===0)return m;b--}else S!=="/$"&&S!=="/&"||b++}m=m.previousSibling}return null}function xU(m,b,S){switch(b=Uw(S),m){case"html":if(m=b.documentElement,!m)throw Error(r(452));return m;case"head":if(m=b.head,!m)throw Error(r(453));return m;case"body":if(m=b.body,!m)throw Error(r(454));return m;default:throw Error(r(451))}}function $x(m){for(var b=m.attributes;b.length;)m.removeAttributeNode(b[0]);Ge(m)}var Go=new Map,yU=new Set;function Bw(m){return typeof m.getRootNode=="function"?m.getRootNode():m.nodeType===9?m:m.ownerDocument}var du=z.d;z.d={f:Poe,r:Eoe,D:joe,C:Doe,L:Roe,m:Foe,X:Ooe,S:Loe,M:Ioe};function Poe(){var m=du.f(),b=jw();return m||b}function Eoe(m){var b=ye(m);b!==null&&b.tag===5&&b.type==="form"?Lz(b):du.r(m)}var Fp=typeof document>"u"?null:document;function vU(m,b,S){var T=Fp;if(T&&typeof b=="string"&&b){var F=Rn(b);F='link[rel="'+m+'"][href="'+F+'"]',typeof S=="string"&&(F+='[crossorigin="'+S+'"]'),yU.has(F)||(yU.add(F),m={rel:m,crossOrigin:S,href:b},T.querySelector(F)===null&&(b=T.createElement("link"),Hi(b,"link",m),Xe(b),T.head.appendChild(b)))}}function joe(m){du.D(m),vU("dns-prefetch",m,null)}function Doe(m,b){du.C(m,b),vU("preconnect",m,b)}function Roe(m,b,S){du.L(m,b,S);var T=Fp;if(T&&m&&b){var F='link[rel="preload"][as="'+Rn(b)+'"]';b==="image"&&S&&S.imageSrcSet?(F+='[imagesrcset="'+Rn(S.imageSrcSet)+'"]',typeof S.imageSizes=="string"&&(F+='[imagesizes="'+Rn(S.imageSizes)+'"]')):F+='[href="'+Rn(m)+'"]';var I=F;switch(b){case"style":I=Lp(m);break;case"script":I=Op(m)}Go.has(I)||(m=h({rel:"preload",href:b==="image"&&S&&S.imageSrcSet?void 0:m,as:b},S),Go.set(I,m),T.querySelector(F)!==null||b==="style"&&T.querySelector(Vx(I))||b==="script"&&T.querySelector(qx(I))||(b=T.createElement("link"),Hi(b,"link",m),Xe(b),T.head.appendChild(b)))}}function Foe(m,b){du.m(m,b);var S=Fp;if(S&&m){var T=b&&typeof b.as=="string"?b.as:"script",F='link[rel="modulepreload"][as="'+Rn(T)+'"][href="'+Rn(m)+'"]',I=F;switch(T){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":I=Op(m)}if(!Go.has(I)&&(m=h({rel:"modulepreload",href:m},b),Go.set(I,m),S.querySelector(F)===null)){switch(T){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(S.querySelector(qx(I)))return}T=S.createElement("link"),Hi(T,"link",m),Xe(T),S.head.appendChild(T)}}}function Loe(m,b,S){du.S(m,b,S);var T=Fp;if(T&&m){var F=Ye(T).hoistableStyles,I=Lp(m);b=b||"default";var re=F.get(I);if(!re){var Pe={loading:0,preload:null};if(re=T.querySelector(Vx(I)))Pe.loading=5;else{m=h({rel:"stylesheet",href:m,"data-precedence":b},S),(S=Go.get(I))&&bM(m,S);var Ve=re=T.createElement("link");Xe(Ve),Hi(Ve,"link",m),Ve._p=new Promise(function(dt,vt){Ve.onload=dt,Ve.onerror=vt}),Ve.addEventListener("load",function(){Pe.loading|=1}),Ve.addEventListener("error",function(){Pe.loading|=2}),Pe.loading|=4,Hw(re,b,T)}re={type:"stylesheet",instance:re,count:1,state:Pe},F.set(I,re)}}}function Ooe(m,b){du.X(m,b);var S=Fp;if(S&&m){var T=Ye(S).hoistableScripts,F=Op(m),I=T.get(F);I||(I=S.querySelector(qx(F)),I||(m=h({src:m,async:!0},b),(b=Go.get(F))&&xM(m,b),I=S.createElement("script"),Xe(I),Hi(I,"link",m),S.head.appendChild(I)),I={type:"script",instance:I,count:1,state:null},T.set(F,I))}}function Ioe(m,b){du.M(m,b);var S=Fp;if(S&&m){var T=Ye(S).hoistableScripts,F=Op(m),I=T.get(F);I||(I=S.querySelector(qx(F)),I||(m=h({src:m,async:!0,type:"module"},b),(b=Go.get(F))&&xM(m,b),I=S.createElement("script"),Xe(I),Hi(I,"link",m),S.head.appendChild(I)),I={type:"script",instance:I,count:1,state:null},T.set(F,I))}}function wU(m,b,S,T){var F=(F=ce.current)?Bw(F):null;if(!F)throw Error(r(446));switch(m){case"meta":case"title":return null;case"style":return typeof S.precedence=="string"&&typeof S.href=="string"?(b=Lp(S.href),S=Ye(F).hoistableStyles,T=S.get(b),T||(T={type:"style",instance:null,count:0,state:null},S.set(b,T)),T):{type:"void",instance:null,count:0,state:null};case"link":if(S.rel==="stylesheet"&&typeof S.href=="string"&&typeof S.precedence=="string"){m=Lp(S.href);var I=Ye(F).hoistableStyles,re=I.get(m);if(re||(F=F.ownerDocument||F,re={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},I.set(m,re),(I=F.querySelector(Vx(m)))&&!I._p&&(re.instance=I,re.state.loading=5),Go.has(m)||(S={rel:"preload",as:"style",href:S.href,crossOrigin:S.crossOrigin,integrity:S.integrity,media:S.media,hrefLang:S.hrefLang,referrerPolicy:S.referrerPolicy},Go.set(m,S),I||zoe(F,m,S,re.state))),b&&T===null)throw Error(r(528,""));return re}if(b&&T!==null)throw Error(r(529,""));return null;case"script":return b=S.async,S=S.src,typeof S=="string"&&b&&typeof b!="function"&&typeof b!="symbol"?(b=Op(S),S=Ye(F).hoistableScripts,T=S.get(b),T||(T={type:"script",instance:null,count:0,state:null},S.set(b,T)),T):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,m))}}function Lp(m){return'href="'+Rn(m)+'"'}function Vx(m){return'link[rel="stylesheet"]['+m+"]"}function SU(m){return h({},m,{"data-precedence":m.precedence,precedence:null})}function zoe(m,b,S,T){m.querySelector('link[rel="preload"][as="style"]['+b+"]")?T.loading=1:(b=m.createElement("link"),T.preload=b,b.addEventListener("load",function(){return T.loading|=1}),b.addEventListener("error",function(){return T.loading|=2}),Hi(b,"link",S),Xe(b),m.head.appendChild(b))}function Op(m){return'[src="'+Rn(m)+'"]'}function qx(m){return"script[async]"+m}function _U(m,b,S){if(b.count++,b.instance===null)switch(b.type){case"style":var T=m.querySelector('style[data-href~="'+Rn(S.href)+'"]');if(T)return b.instance=T,Xe(T),T;var F=h({},S,{"data-href":S.href,"data-precedence":S.precedence,href:null,precedence:null});return T=(m.ownerDocument||m).createElement("style"),Xe(T),Hi(T,"style",F),Hw(T,S.precedence,m),b.instance=T;case"stylesheet":F=Lp(S.href);var I=m.querySelector(Vx(F));if(I)return b.state.loading|=4,b.instance=I,Xe(I),I;T=SU(S),(F=Go.get(F))&&bM(T,F),I=(m.ownerDocument||m).createElement("link"),Xe(I);var re=I;return re._p=new Promise(function(Pe,Ve){re.onload=Pe,re.onerror=Ve}),Hi(I,"link",T),b.state.loading|=4,Hw(I,S.precedence,m),b.instance=I;case"script":return I=Op(S.src),(F=m.querySelector(qx(I)))?(b.instance=F,Xe(F),F):(T=S,(F=Go.get(I))&&(T=h({},S),xM(T,F)),m=m.ownerDocument||m,F=m.createElement("script"),Xe(F),Hi(F,"link",T),m.head.appendChild(F),b.instance=F);case"void":return null;default:throw Error(r(443,b.type))}else b.type==="stylesheet"&&(b.state.loading&4)===0&&(T=b.instance,b.state.loading|=4,Hw(T,S.precedence,m));return b.instance}function Hw(m,b,S){for(var T=S.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),F=T.length?T[T.length-1]:null,I=F,re=0;re<T.length;re++){var Pe=T[re];if(Pe.dataset.precedence===b)I=Pe;else if(I!==F)break}I?I.parentNode.insertBefore(m,I.nextSibling):(b=S.nodeType===9?S.head:S,b.insertBefore(m,b.firstChild))}function bM(m,b){m.crossOrigin==null&&(m.crossOrigin=b.crossOrigin),m.referrerPolicy==null&&(m.referrerPolicy=b.referrerPolicy),m.title==null&&(m.title=b.title)}function xM(m,b){m.crossOrigin==null&&(m.crossOrigin=b.crossOrigin),m.referrerPolicy==null&&(m.referrerPolicy=b.referrerPolicy),m.integrity==null&&(m.integrity=b.integrity)}var $w=null;function NU(m,b,S){if($w===null){var T=new Map,F=$w=new Map;F.set(S,T)}else F=$w,T=F.get(S),T||(T=new Map,F.set(S,T));if(T.has(m))return T;for(T.set(m,null),S=S.getElementsByTagName(m),F=0;F<S.length;F++){var I=S[F];if(!(I[ot]||I[En]||m==="link"&&I.getAttribute("rel")==="stylesheet")&&I.namespaceURI!=="http://www.w3.org/2000/svg"){var re=I.getAttribute(b)||"";re=m+re;var Pe=T.get(re);Pe?Pe.push(I):T.set(re,[I])}}return T}function CU(m,b,S){m=m.ownerDocument||m,m.head.insertBefore(S,b==="title"?m.querySelector("head > title"):null)}function Uoe(m,b,S){if(S===1||b.itemProp!=null)return!1;switch(m){case"meta":case"title":return!0;case"style":if(typeof b.precedence!="string"||typeof b.href!="string"||b.href==="")break;return!0;case"link":if(typeof b.rel!="string"||typeof b.href!="string"||b.href===""||b.onLoad||b.onError)break;return b.rel==="stylesheet"?(m=b.disabled,typeof b.precedence=="string"&&m==null):!0;case"script":if(b.async&&typeof b.async!="function"&&typeof b.async!="symbol"&&!b.onLoad&&!b.onError&&b.src&&typeof b.src=="string")return!0}return!1}function kU(m){return!(m.type==="stylesheet"&&(m.state.loading&3)===0)}function Boe(m,b,S,T){if(S.type==="stylesheet"&&(typeof T.media!="string"||matchMedia(T.media).matches!==!1)&&(S.state.loading&4)===0){if(S.instance===null){var F=Lp(T.href),I=b.querySelector(Vx(F));if(I){b=I._p,b!==null&&typeof b=="object"&&typeof b.then=="function"&&(m.count++,m=Vw.bind(m),b.then(m,m)),S.state.loading|=4,S.instance=I,Xe(I);return}I=b.ownerDocument||b,T=SU(T),(F=Go.get(F))&&bM(T,F),I=I.createElement("link"),Xe(I);var re=I;re._p=new Promise(function(Pe,Ve){re.onload=Pe,re.onerror=Ve}),Hi(I,"link",T),S.instance=I}m.stylesheets===null&&(m.stylesheets=new Map),m.stylesheets.set(S,b),(b=S.state.preload)&&(S.state.loading&3)===0&&(m.count++,S=Vw.bind(m),b.addEventListener("load",S),b.addEventListener("error",S))}}var yM=0;function Hoe(m,b){return m.stylesheets&&m.count===0&&Gw(m,m.stylesheets),0<m.count||0<m.imgCount?function(S){var T=setTimeout(function(){if(m.stylesheets&&Gw(m,m.stylesheets),m.unsuspend){var I=m.unsuspend;m.unsuspend=null,I()}},6e4+b);0<m.imgBytes&&yM===0&&(yM=62500*Soe());var F=setTimeout(function(){if(m.waitingForImages=!1,m.count===0&&(m.stylesheets&&Gw(m,m.stylesheets),m.unsuspend)){var I=m.unsuspend;m.unsuspend=null,I()}},(m.imgBytes>yM?50:800)+b);return m.unsuspend=S,function(){m.unsuspend=null,clearTimeout(T),clearTimeout(F)}}:null}function Vw(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Gw(this,this.stylesheets);else if(this.unsuspend){var m=this.unsuspend;this.unsuspend=null,m()}}}var qw=null;function Gw(m,b){m.stylesheets=null,m.unsuspend!==null&&(m.count++,qw=new Map,b.forEach($oe,m),qw=null,Vw.call(m))}function $oe(m,b){if(!(b.state.loading&4)){var S=qw.get(m);if(S)var T=S.get(null);else{S=new Map,qw.set(m,S);for(var F=m.querySelectorAll("link[data-precedence],style[data-precedence]"),I=0;I<F.length;I++){var re=F[I];(re.nodeName==="LINK"||re.getAttribute("media")!=="not all")&&(S.set(re.dataset.precedence,re),T=re)}T&&S.set(null,T)}F=b.instance,re=F.getAttribute("data-precedence"),I=S.get(re)||T,I===T&&S.set(null,F),S.set(re,F),this.count++,T=Vw.bind(this),F.addEventListener("load",T),F.addEventListener("error",T),I?I.parentNode.insertBefore(F,I.nextSibling):(m=m.nodeType===9?m.head:m,m.insertBefore(F,m.firstChild)),b.state.loading|=4}}var Gx={$$typeof:N,Provider:null,Consumer:null,_currentValue:W,_currentValue2:W,_threadCount:0};function Voe(m,b,S,T,F,I,re,Pe,Ve){this.tag=1,this.containerInfo=m,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=Dt(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Dt(0),this.hiddenUpdates=Dt(null),this.identifierPrefix=T,this.onUncaughtError=F,this.onCaughtError=I,this.onRecoverableError=re,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=Ve,this.incompleteTransitions=new Map}function AU(m,b,S,T,F,I,re,Pe,Ve,dt,vt,Ct){return m=new Voe(m,b,S,re,Ve,dt,vt,Ct,Pe),b=1,I===!0&&(b|=24),I=go(3,null,null,b),m.current=I,I.stateNode=m,b=ZA(),b.refCount++,m.pooledCache=b,b.refCount++,I.memoizedState={element:T,isDehydrated:S,cache:b},nT(I),m}function TU(m){return m?(m=fp,m):fp}function MU(m,b,S,T,F,I){F=TU(F),T.context===null?T.context=F:T.pendingContext=F,T=Cd(b),T.payload={element:S},I=I===void 0?null:I,I!==null&&(T.callback=I),S=kd(m,T,b),S!==null&&(qs(S,m,b),Nx(S,m,b))}function PU(m,b){if(m=m.memoizedState,m!==null&&m.dehydrated!==null){var S=m.retryLane;m.retryLane=S!==0&&S<b?S:b}}function vM(m,b){PU(m,b),(m=m.alternate)&&PU(m,b)}function EU(m){if(m.tag===13||m.tag===31){var b=mm(m,67108864);b!==null&&qs(b,m,67108864),vM(m,67108864)}}function jU(m){if(m.tag===13||m.tag===31){var b=wo();b=Gt(b);var S=mm(m,b);S!==null&&qs(S,m,b),vM(m,b)}}var Ww=!0;function qoe(m,b,S,T){var F=G.T;G.T=null;var I=z.p;try{z.p=2,wM(m,b,S,T)}finally{z.p=I,G.T=F}}function Goe(m,b,S,T){var F=G.T;G.T=null;var I=z.p;try{z.p=8,wM(m,b,S,T)}finally{z.p=I,G.T=F}}function wM(m,b,S,T){if(Ww){var F=SM(T);if(F===null)oM(m,b,T,Kw,S),RU(m,T);else if(Koe(F,m,b,S,T))T.stopPropagation();else if(RU(m,T),b&4&&-1<Woe.indexOf(m)){for(;F!==null;){var I=ye(F);if(I!==null)switch(I.tag){case 3:if(I=I.stateNode,I.current.memoizedState.isDehydrated){var re=Ae(I.pendingLanes);if(re!==0){var Pe=I;for(Pe.pendingLanes|=2,Pe.entangledLanes|=2;re;){var Ve=1<<31-ge(re);Pe.entanglements[1]|=Ve,re&=~Ve}uc(I),(fr&6)===0&&(Pw=R()+500,Ux(0))}}break;case 31:case 13:Pe=mm(I,2),Pe!==null&&qs(Pe,I,2),jw(),vM(I,2)}if(I=SM(T),I===null&&oM(m,b,T,Kw,S),I===F)break;F=I}F!==null&&T.stopPropagation()}else oM(m,b,T,null,S)}}function SM(m){return m=Ss(m),_M(m)}var Kw=null;function _M(m){if(Kw=null,m=zt(m),m!==null){var b=s(m);if(b===null)m=null;else{var S=b.tag;if(S===13){if(m=o(b),m!==null)return m;m=null}else if(S===31){if(m=l(b),m!==null)return m;m=null}else if(S===3){if(b.stateNode.current.memoizedState.isDehydrated)return b.tag===3?b.stateNode.containerInfo:null;m=null}else b!==m&&(m=null)}}return Kw=m,null}function DU(m){switch(m){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(q()){case J:return 2;case fe:return 8;case le:case Be:return 32;case Ie:return 268435456;default:return 32}default:return 32}}var NM=!1,Od=null,Id=null,zd=null,Wx=new Map,Kx=new Map,Ud=[],Woe="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function RU(m,b){switch(m){case"focusin":case"focusout":Od=null;break;case"dragenter":case"dragleave":Id=null;break;case"mouseover":case"mouseout":zd=null;break;case"pointerover":case"pointerout":Wx.delete(b.pointerId);break;case"gotpointercapture":case"lostpointercapture":Kx.delete(b.pointerId)}}function Xx(m,b,S,T,F,I){return m===null||m.nativeEvent!==I?(m={blockedOn:b,domEventName:S,eventSystemFlags:T,nativeEvent:I,targetContainers:[F]},b!==null&&(b=ye(b),b!==null&&EU(b)),m):(m.eventSystemFlags|=T,b=m.targetContainers,F!==null&&b.indexOf(F)===-1&&b.push(F),m)}function Koe(m,b,S,T,F){switch(b){case"focusin":return Od=Xx(Od,m,b,S,T,F),!0;case"dragenter":return Id=Xx(Id,m,b,S,T,F),!0;case"mouseover":return zd=Xx(zd,m,b,S,T,F),!0;case"pointerover":var I=F.pointerId;return Wx.set(I,Xx(Wx.get(I)||null,m,b,S,T,F)),!0;case"gotpointercapture":return I=F.pointerId,Kx.set(I,Xx(Kx.get(I)||null,m,b,S,T,F)),!0}return!1}function FU(m){var b=zt(m.target);if(b!==null){var S=s(b);if(S!==null){if(b=S.tag,b===13){if(b=o(S),b!==null){m.blockedOn=b,Qn(m.priority,function(){jU(S)});return}}else if(b===31){if(b=l(S),b!==null){m.blockedOn=b,Qn(m.priority,function(){jU(S)});return}}else if(b===3&&S.stateNode.current.memoizedState.isDehydrated){m.blockedOn=S.tag===3?S.stateNode.containerInfo:null;return}}}m.blockedOn=null}function Xw(m){if(m.blockedOn!==null)return!1;for(var b=m.targetContainers;0<b.length;){var S=SM(m.nativeEvent);if(S===null){S=m.nativeEvent;var T=new S.constructor(S.type,S);xn=T,S.target.dispatchEvent(T),xn=null}else return b=ye(S),b!==null&&EU(b),m.blockedOn=S,!1;b.shift()}return!0}function LU(m,b,S){Xw(m)&&S.delete(b)}function Xoe(){NM=!1,Od!==null&&Xw(Od)&&(Od=null),Id!==null&&Xw(Id)&&(Id=null),zd!==null&&Xw(zd)&&(zd=null),Wx.forEach(LU),Kx.forEach(LU)}function Yw(m,b){m.blockedOn===b&&(m.blockedOn=null,NM||(NM=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Xoe)))}var Qw=null;function OU(m){Qw!==m&&(Qw=m,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Qw===m&&(Qw=null);for(var b=0;b<m.length;b+=3){var S=m[b],T=m[b+1],F=m[b+2];if(typeof T!="function"){if(_M(T||S)===null)continue;break}var I=ye(S);I!==null&&(m.splice(b,3),b-=3,ST(I,{pending:!0,data:F,method:S.method,action:T},T,F))}}))}function Ip(m){function b(Ve){return Yw(Ve,m)}Od!==null&&Yw(Od,m),Id!==null&&Yw(Id,m),zd!==null&&Yw(zd,m),Wx.forEach(b),Kx.forEach(b);for(var S=0;S<Ud.length;S++){var T=Ud[S];T.blockedOn===m&&(T.blockedOn=null)}for(;0<Ud.length&&(S=Ud[0],S.blockedOn===null);)FU(S),S.blockedOn===null&&Ud.shift();if(S=(m.ownerDocument||m).$$reactFormReplay,S!=null)for(T=0;T<S.length;T+=3){var F=S[T],I=S[T+1],re=F[dr]||null;if(typeof I=="function")re||OU(S);else if(re){var Pe=null;if(I&&I.hasAttribute("formAction")){if(F=I,re=I[dr]||null)Pe=re.formAction;else if(_M(F)!==null)continue}else Pe=re.action;typeof Pe=="function"?S[T+1]=Pe:(S.splice(T,3),T-=3),OU(S)}}}function IU(){function m(I){I.canIntercept&&I.info==="react-transition"&&I.intercept({handler:function(){return new Promise(function(re){return F=re})},focusReset:"manual",scroll:"manual"})}function b(){F!==null&&(F(),F=null),T||setTimeout(S,20)}function S(){if(!T&&!navigation.transition){var I=navigation.currentEntry;I&&I.url!=null&&navigation.navigate(I.url,{state:I.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var T=!1,F=null;return navigation.addEventListener("navigate",m),navigation.addEventListener("navigatesuccess",b),navigation.addEventListener("navigateerror",b),setTimeout(S,100),function(){T=!0,navigation.removeEventListener("navigate",m),navigation.removeEventListener("navigatesuccess",b),navigation.removeEventListener("navigateerror",b),F!==null&&(F(),F=null)}}}function CM(m){this._internalRoot=m}Zw.prototype.render=CM.prototype.render=function(m){var b=this._internalRoot;if(b===null)throw Error(r(409));var S=b.current,T=wo();MU(S,T,m,b,null,null)},Zw.prototype.unmount=CM.prototype.unmount=function(){var m=this._internalRoot;if(m!==null){this._internalRoot=null;var b=m.containerInfo;MU(m.current,2,null,m,null,null),jw(),b[Tr]=null}};function Zw(m){this._internalRoot=m}Zw.prototype.unstable_scheduleHydration=function(m){if(m){var b=vr();m={blockedOn:null,target:m,priority:b};for(var S=0;S<Ud.length&&b!==0&&b<Ud[S].priority;S++);Ud.splice(S,0,m),S===0&&FU(m)}};var zU=e.version;if(zU!=="19.2.4")throw Error(r(527,zU,"19.2.4"));z.findDOMNode=function(m){var b=m._reactInternals;if(b===void 0)throw typeof m.render=="function"?Error(r(188)):(m=Object.keys(m).join(","),Error(r(268,m)));return m=u(b),m=m!==null?d(m):null,m=m===null?null:m.stateNode,m};var Yoe={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:G,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Jw=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Jw.isDisabled&&Jw.supportsFiber)try{pe=Jw.inject(Yoe),xe=Jw}catch{}}return Qx.createRoot=function(m,b){if(!a(m))throw Error(r(299));var S=!1,T="",F=Gz,I=Wz,re=Kz;return b!=null&&(b.unstable_strictMode===!0&&(S=!0),b.identifierPrefix!==void 0&&(T=b.identifierPrefix),b.onUncaughtError!==void 0&&(F=b.onUncaughtError),b.onCaughtError!==void 0&&(I=b.onCaughtError),b.onRecoverableError!==void 0&&(re=b.onRecoverableError)),b=AU(m,1,!1,null,null,S,T,null,F,I,re,IU),m[Tr]=b.current,sM(m),new CM(b)},Qx.hydrateRoot=function(m,b,S){if(!a(m))throw Error(r(299));var T=!1,F="",I=Gz,re=Wz,Pe=Kz,Ve=null;return S!=null&&(S.unstable_strictMode===!0&&(T=!0),S.identifierPrefix!==void 0&&(F=S.identifierPrefix),S.onUncaughtError!==void 0&&(I=S.onUncaughtError),S.onCaughtError!==void 0&&(re=S.onCaughtError),S.onRecoverableError!==void 0&&(Pe=S.onRecoverableError),S.formState!==void 0&&(Ve=S.formState)),b=AU(m,1,!0,b,S??null,T,F,Ve,I,re,Pe,IU),b.context=TU(null),S=b.current,T=wo(),T=Gt(T),F=Cd(T),F.callback=null,kd(S,F,T),S=T,b.current.lanes=S,It(b,S),uc(b),m[Tr]=b.current,sM(m),new Zw(b)},Qx.version="19.2.4",Qx}var XU;function ole(){if(XU)return TM.exports;XU=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),TM.exports=sle(),TM.exports}var lle=ole();const yn=t=>typeof t=="string",Zx=()=>{let t,e;const n=new Promise((r,a)=>{t=r,e=a});return n.resolve=t,n.reject=e,n},YU=t=>t==null?"":""+t,cle=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},ule=/###/g,QU=t=>t&&t.indexOf("###")>-1?t.replace(ule,"."):t,ZU=t=>!t||yn(t),By=(t,e,n)=>{const r=yn(e)?e.split("."):e;let a=0;for(;a<r.length-1;){if(ZU(t))return{};const s=QU(r[a]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++a}return ZU(t)?{}:{obj:t,k:QU(r[a])}},JU=(t,e,n)=>{const{obj:r,k:a}=By(t,e,Object);if(r!==void 0||e.length===1){r[a]=n;return}let s=e[e.length-1],o=e.slice(0,e.length-1),l=By(t,o,Object);for(;l.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),l=By(t,o,Object),l?.obj&&typeof l.obj[`${l.k}.${s}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${s}`]=n},dle=(t,e,n,r)=>{const{obj:a,k:s}=By(t,e,Object);a[s]=a[s]||[],a[s].push(n)},f1=(t,e)=>{const{obj:n,k:r}=By(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},hle=(t,e,n)=>{const r=f1(t,n);return r!==void 0?r:f1(e,n)},bK=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?yn(t[r])||t[r]instanceof String||yn(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):bK(t[r],e[r],n):t[r]=e[r]);return t},zp=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var mle={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const fle=t=>yn(t)?t.replace(/[&<>"'\/]/g,e=>mle[e]):t;class ple{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const gle=[" ",",","?","!",";"],ble=new ple(20),xle=(t,e,n)=>{e=e||"",n=n||"";const r=gle.filter(o=>e.indexOf(o)<0&&n.indexOf(o)<0);if(r.length===0)return!0;const a=ble.getRegExp(`(${r.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!a.test(t);if(!s){const o=t.indexOf(n);o>0&&!a.test(t.substring(0,o))&&(s=!0)}return s},U2=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let a=t;for(let s=0;s<r.length;){if(!a||typeof a!="object")return;let o,l="";for(let c=s;c<r.length;++c)if(c!==s&&(l+=n),l+=r[c],o=a[l],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&c<r.length-1)continue;s+=c-s+1;break}a=o}return a},mv=t=>t?.replace("_","-"),yle={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class p1{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||yle,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,a){return a&&!this.debug?null:(yn(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new p1(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new p1(this.logger,e)}}var Cc=new p1;let IC=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const a=this.observers[r].get(n)||0;this.observers[r].set(n,a+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([a,s])=>{for(let o=0;o<s;o++)a(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([a,s])=>{for(let o=0;o<s;o++)a.apply(a,[e,...n])})}};class eB extends IC{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,a={}){const s=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,o=a.ignoreJSONStructure!==void 0?a.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;e.indexOf(".")>-1?l=e.split("."):(l=[e,n],r&&(Array.isArray(r)?l.push(...r):yn(r)&&s?l.push(...r.split(s)):l.push(r)));const c=f1(this.data,l);return!c&&!n&&!r&&e.indexOf(".")>-1&&(e=l[0],n=l[1],r=l.slice(2).join(".")),c||!o||!yn(r)?c:U2(this.data?.[e]?.[n],r,s)}addResource(e,n,r,a,s={silent:!1}){const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let l=[e,n];r&&(l=l.concat(o?r.split(o):r)),e.indexOf(".")>-1&&(l=e.split("."),a=n,n=l[1]),this.addNamespaces(n),JU(this.data,l,a),s.silent||this.emit("added",e,n,r,a)}addResources(e,n,r,a={silent:!1}){for(const s in r)(yn(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});a.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,a,s,o={silent:!1,skipCopy:!1}){let l=[e,n];e.indexOf(".")>-1&&(l=e.split("."),a=r,r=n,n=l[1]),this.addNamespaces(n);let c=f1(this.data,l)||{};o.skipCopy||(r=JSON.parse(JSON.stringify(r))),a?bK(c,r,s):c={...c,...r},JU(this.data,l,c),o.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(a=>n[a]&&Object.keys(n[a]).length>0)}toJSON(){return this.data}}var xK={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,a){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,a)??e}),e}};const yK=Symbol("i18next/PATH_KEY");function vle(){const t=[],e=Object.create(null);let n;return e.get=(r,a)=>(n?.revoke?.(),a===yK?t:(t.push(a),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function B2(t,e){const{[yK]:n}=t(vle());return n.join(e?.keySeparator??".")}const tB={},jM=t=>!yn(t)&&typeof t!="boolean"&&typeof t!="number";class g1 extends IC{constructor(e,n={}){super(),cle(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Cc.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const a=this.resolve(e,r);if(a?.res===void 0)return!1;const s=jM(a.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const a=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const o=r&&e.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!xle(e,r,a);if(o&&!l){const c=e.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:e,namespaces:yn(s)?[s]:s};const u=e.split(r);(r!==a||r===a&&this.options.ns.indexOf(u[0])>-1)&&(s=u.shift()),e=u.join(a)}return{key:e,namespaces:yn(s)?[s]:s}}translate(e,n,r){let a=typeof n=="object"?{...n}:n;if(typeof a!="object"&&this.options.overloadTranslationOptionHandler&&(a=this.options.overloadTranslationOptionHandler(arguments)),typeof a=="object"&&(a={...a}),a||(a={}),e==null)return"";typeof e=="function"&&(e=B2(e,{...this.options,...a})),Array.isArray(e)||(e=[String(e)]);const s=a.returnDetails!==void 0?a.returnDetails:this.options.returnDetails,o=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,{key:l,namespaces:c}=this.extractFromKey(e[e.length-1],a),u=c[c.length-1];let d=a.nsSeparator!==void 0?a.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const h=a.lng||this.language,f=a.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h?.toLowerCase()==="cimode")return f?s?{res:`${u}${d}${l}`,usedKey:l,exactUsedKey:l,usedLng:h,usedNS:u,usedParams:this.getUsedParamsDetails(a)}:`${u}${d}${l}`:s?{res:l,usedKey:l,exactUsedKey:l,usedLng:h,usedNS:u,usedParams:this.getUsedParamsDetails(a)}:l;const p=this.resolve(e,a);let x=p?.res;const v=p?.usedKey||l,g=p?.exactUsedKey||l,y=["[object Number]","[object Function]","[object RegExp]"],_=a.joinArrays!==void 0?a.joinArrays:this.options.joinArrays,N=!this.i18nFormat||this.i18nFormat.handleAsObject,k=a.count!==void 0&&!yn(a.count),A=g1.hasDefaultValue(a),M=k?this.pluralResolver.getSuffix(h,a.count,a):"",C=a.ordinal&&k?this.pluralResolver.getSuffix(h,a.count,{ordinal:!1}):"",j=k&&!a.ordinal&&a.count===0,P=j&&a[`defaultValue${this.options.pluralSeparator}zero`]||a[`defaultValue${M}`]||a[`defaultValue${C}`]||a.defaultValue;let E=x;N&&!x&&A&&(E=P);const U=jM(E),L=Object.prototype.toString.apply(E);if(N&&E&&U&&y.indexOf(L)<0&&!(yn(_)&&Array.isArray(E))){if(!a.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const B=this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,E,{...a,ns:c}):`key '${l} (${this.language})' returned an object instead of string.`;return s?(p.res=B,p.usedParams=this.getUsedParamsDetails(a),p):B}if(o){const B=Array.isArray(E),D=B?[]:{},$=B?g:v;for(const G in E)if(Object.prototype.hasOwnProperty.call(E,G)){const z=`${$}${o}${G}`;A&&!x?D[G]=this.translate(z,{...a,defaultValue:jM(P)?P[G]:void 0,joinArrays:!1,ns:c}):D[G]=this.translate(z,{...a,joinArrays:!1,ns:c}),D[G]===z&&(D[G]=E[G])}x=D}}else if(N&&yn(_)&&Array.isArray(x))x=x.join(_),x&&(x=this.extendTranslation(x,e,a,r));else{let B=!1,D=!1;!this.isValidLookup(x)&&A&&(B=!0,x=P),this.isValidLookup(x)||(D=!0,x=l);const G=(a.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&D?void 0:x,z=A&&P!==x&&this.options.updateMissing;if(D||B||z){if(this.logger.log(z?"updateKey":"missingKey",h,u,l,z?P:x),o){const H=this.resolve(l,{...a,keySeparator:!1});H&&H.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let W=[];const X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,a.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(let H=0;H<X.length;H++)W.push(X[H]);else this.options.saveMissingTo==="all"?W=this.languageUtils.toResolveHierarchy(a.lng||this.language):W.push(a.lng||this.language);const ae=(H,K,te)=>{const Z=A&&te!==x?te:G;this.options.missingKeyHandler?this.options.missingKeyHandler(H,u,K,Z,z,a):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(H,u,K,Z,z,a),this.emit("missingKey",H,u,K,x)};this.options.saveMissing&&(this.options.saveMissingPlurals&&k?W.forEach(H=>{const K=this.pluralResolver.getSuffixes(H,a);j&&a[`defaultValue${this.options.pluralSeparator}zero`]&&K.indexOf(`${this.options.pluralSeparator}zero`)<0&&K.push(`${this.options.pluralSeparator}zero`),K.forEach(te=>{ae([H],l+te,a[`defaultValue${te}`]||P)})}):ae(W,l,P))}x=this.extendTranslation(x,e,a,p,r),D&&x===l&&this.options.appendNamespaceToMissingKey&&(x=`${u}${d}${l}`),(D||B)&&this.options.parseMissingKeyHandler&&(x=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${l}`:l,B?x:void 0,a))}return s?(p.res=x,p.usedParams=this.getUsedParamsDetails(a),p):x}extendTranslation(e,n,r,a,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||a.usedLng,a.usedNS,a.usedKey,{resolved:a});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const c=yn(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const h=e.match(this.interpolator.nestingRegexp);u=h&&h.length}let d=r.replace&&!yn(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),e=this.interpolator.interpolate(e,d,r.lng||this.language||a.usedLng,r),c){const h=e.match(this.interpolator.nestingRegexp),f=h&&h.length;u<f&&(r.nest=!1)}!r.lng&&a&&a.res&&(r.lng=this.language||a.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>s?.[0]===h[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${n[0]}`),null):this.translate(...h,n),r)),r.interpolation&&this.interpolator.reset()}const o=r.postProcess||this.options.postProcess,l=yn(o)?[o]:o;return e!=null&&l?.length&&r.applyPostProcessor!==!1&&(e=xK.handle(l,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...a,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,a,s,o,l;return yn(e)&&(e=[e]),e.forEach(c=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(c,n),d=u.key;a=d;let h=u.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));const f=n.count!==void 0&&!yn(n.count),p=f&&!n.ordinal&&n.count===0,x=n.context!==void 0&&(yn(n.context)||typeof n.context=="number")&&n.context!=="",v=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);h.forEach(g=>{this.isValidLookup(r)||(l=g,!tB[`${v[0]}-${g}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(l)&&(tB[`${v[0]}-${g}`]=!0,this.logger.warn(`key "${a}" for languages "${v.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),v.forEach(y=>{if(this.isValidLookup(r))return;o=y;const _=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(_,d,y,g,n);else{let k;f&&(k=this.pluralResolver.getSuffix(y,n.count,n));const A=`${this.options.pluralSeparator}zero`,M=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(n.ordinal&&k.indexOf(M)===0&&_.push(d+k.replace(M,this.options.pluralSeparator)),_.push(d+k),p&&_.push(d+A)),x){const C=`${d}${this.options.contextSeparator||"_"}${n.context}`;_.push(C),f&&(n.ordinal&&k.indexOf(M)===0&&_.push(C+k.replace(M,this.options.pluralSeparator)),_.push(C+k),p&&_.push(C+A))}}let N;for(;N=_.pop();)this.isValidLookup(r)||(s=N,r=this.getResource(y,g,N,n))}))})}),{res:r,usedKey:a,exactUsedKey:s,usedLng:o,usedNS:l}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,a={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,a):this.resourceStore.getResource(e,n,r,a)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!yn(e.replace);let a=r?e.replace:e;if(r&&typeof e.count<"u"&&(a.count=e.count),this.options.interpolation.defaultVariables&&(a={...this.options.interpolation.defaultVariables,...a}),!r){a={...a};for(const s of n)delete a[s]}return a}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&n===r.substring(0,n.length)&&e[r]!==void 0)return!0;return!1}}class nB{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Cc.create("languageUtils")}getScriptPartFromCode(e){if(e=mv(e),!e||e.indexOf("-")<0)return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=mv(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(yn(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const a=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(a))&&(n=a)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const a=this.getScriptPartFromCode(r);if(this.isSupportedCode(a))return n=a;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),yn(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),a=[],s=o=>{o&&(this.isSupportedCode(o)?a.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return yn(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(e))):yn(e)&&s(this.formatLanguageCode(e)),r.forEach(o=>{a.indexOf(o)<0&&s(this.formatLanguageCode(o))}),a}}const rB={zero:0,one:1,two:2,few:3,many:4,other:5},aB={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class wle{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Cc.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=mv(e==="dev"?"en":e),a=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:a});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(r,{type:a})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),aB;if(!e.match(/-|_/))return aB;const c=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(c,n)}return this.pluralRulesCache[s]=o,o}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(a=>`${n}${a}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((a,s)=>rB[a]-rB[s]).map(a=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${a}`):[]}getSuffix(e,n,r={}){const a=this.getRule(e,r);return a?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${a.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const iB=(t,e,n,r=".",a=!0)=>{let s=hle(t,e,n);return!s&&a&&yn(n)&&(s=U2(t,n,r),s===void 0&&(s=U2(e,n,r))),s},DM=t=>t.replace(/\$/g,"$$$$");class Sle{constructor(e={}){this.logger=Cc.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:a,prefix:s,prefixEscaped:o,suffix:l,suffixEscaped:c,formatSeparator:u,unescapeSuffix:d,unescapePrefix:h,nestingPrefix:f,nestingPrefixEscaped:p,nestingSuffix:x,nestingSuffixEscaped:v,nestingOptionsSeparator:g,maxReplaces:y,alwaysFormat:_}=e.interpolation;this.escape=n!==void 0?n:fle,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=a!==void 0?a:!1,this.prefix=s?zp(s):o||"{{",this.suffix=l?zp(l):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":h||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=f?zp(f):p||zp("$t("),this.nestingSuffix=x?zp(x):v||zp(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=y||1e3,this.alwaysFormat=_!==void 0?_:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,a){let s,o,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=p=>{if(p.indexOf(this.formatSeparator)<0){const y=iB(n,c,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,r,{...a,...n,interpolationkey:p}):y}const x=p.split(this.formatSeparator),v=x.shift().trim(),g=x.join(this.formatSeparator).trim();return this.format(iB(n,c,v,this.options.keySeparator,this.options.ignoreJSONStructure),g,r,{...a,...n,interpolationkey:v})};this.resetRegExp();const d=a?.missingInterpolationHandler||this.options.missingInterpolationHandler,h=a?.interpolation?.skipOnVariables!==void 0?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>DM(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?DM(this.escape(p)):DM(p)}].forEach(p=>{for(l=0;s=p.regex.exec(e);){const x=s[1].trim();if(o=u(x),o===void 0)if(typeof d=="function"){const g=d(e,s,a);o=yn(g)?g:""}else if(a&&Object.prototype.hasOwnProperty.call(a,x))o="";else if(h){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${x} for interpolating ${e}`),o="";else!yn(o)&&!this.useRawValueToEscape&&(o=YU(o));const v=p.safeValue(o);if(e=e.replace(s[0],v),h?(p.regex.lastIndex+=o.length,p.regex.lastIndex-=s[0].length):p.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),e}nest(e,n,r={}){let a,s,o;const l=(c,u)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const h=c.split(new RegExp(`${d}[ ]*{`));let f=`{${h[1]}`;c=h[0],f=this.interpolate(f,o);const p=f.match(/'/g),x=f.match(/"/g);((p?.length??0)%2===0&&!x||x.length%2!==0)&&(f=f.replace(/'/g,'"'));try{o=JSON.parse(f),u&&(o={...u,...o})}catch(v){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,v),`${c}${d}${f}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,c};for(;a=this.nestingRegexp.exec(e);){let c=[];o={...r},o=o.replace&&!yn(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const u=/{.*}/.test(a[1])?a[1].lastIndexOf("}")+1:a[1].indexOf(this.formatSeparator);if(u!==-1&&(c=a[1].slice(u).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),a[1]=a[1].slice(0,u)),s=n(l.call(this,a[1].trim(),o),o),s&&a[0]===e&&!yn(s))return s;yn(s)||(s=YU(s)),s||(this.logger.warn(`missed to resolve ${a[1]} for nesting ${e}`),s=""),c.length&&(s=c.reduce((d,h)=>this.format(d,h,r.lng,{...r,interpolationkey:a[1].trim()}),s.trim())),e=e.replace(a[0],s),this.regexp.lastIndex=0}return e}}const _le=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const r=t.split("(");e=r[0].toLowerCase().trim();const a=r[1].substring(0,r[1].length-1);e==="currency"&&a.indexOf(":")<0?n.currency||(n.currency=a.trim()):e==="relativetime"&&a.indexOf(":")<0?n.range||(n.range=a.trim()):a.split(";").forEach(o=>{if(o){const[l,...c]=o.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),d=l.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:e,formatOptions:n}},sB=t=>{const e={};return(n,r,a)=>{let s=a;a&&a.interpolationkey&&a.formatParams&&a.formatParams[a.interpolationkey]&&a[a.interpolationkey]&&(s={...s,[a.interpolationkey]:void 0});const o=r+JSON.stringify(s);let l=e[o];return l||(l=t(mv(r),a),e[o]=l),l(n)}},Nle=t=>(e,n,r)=>t(mv(n),r)(e);class Cle{constructor(e={}){this.logger=Cc.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?sB:Nle;this.formats={number:r((a,s)=>{const o=new Intl.NumberFormat(a,{...s});return l=>o.format(l)}),currency:r((a,s)=>{const o=new Intl.NumberFormat(a,{...s,style:"currency"});return l=>o.format(l)}),datetime:r((a,s)=>{const o=new Intl.DateTimeFormat(a,{...s});return l=>o.format(l)}),relativetime:r((a,s)=>{const o=new Intl.RelativeTimeFormat(a,{...s});return l=>o.format(l,s.range||"day")}),list:r((a,s)=>{const o=new Intl.ListFormat(a,{...s});return l=>o.format(l)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=sB(n)}format(e,n,r,a={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(l=>l.indexOf(")")>-1)){const l=s.findIndex(c=>c.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,l)].join(this.formatSeparator)}return s.reduce((l,c)=>{const{formatName:u,formatOptions:d}=_le(c);if(this.formats[u]){let h=l;try{const f=a?.formatParams?.[a.interpolationkey]||{},p=f.locale||f.lng||a.locale||a.lng||r;h=this.formats[u](l,p,{...d,...a,...f})}catch(f){this.logger.warn(f)}return h}else this.logger.warn(`there was no format function for ${u}`);return l},e)}}const kle=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Ale extends IC{constructor(e,n,r,a={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=a,this.logger=Cc.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=a.maxParallelReads||10,this.readingCalls=0,this.maxRetries=a.maxRetries>=0?a.maxRetries:5,this.retryTimeout=a.retryTimeout>=1?a.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,a.backend,a)}queueLoad(e,n,r,a){const s={},o={},l={},c={};return e.forEach(u=>{let d=!0;n.forEach(h=>{const f=`${u}|${h}`;!r.reload&&this.store.hasResourceBundle(u,h)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?o[f]===void 0&&(o[f]=!0):(this.state[f]=1,d=!1,o[f]===void 0&&(o[f]=!0),s[f]===void 0&&(s[f]=!0),c[h]===void 0&&(c[h]=!0)))}),d||(l[u]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:a}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(e,n,r){const a=e.split("|"),s=a[0],o=a[1];n&&this.emit("failedLoading",s,o,n),!n&&r&&this.store.addResourceBundle(s,o,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const l={};this.queue.forEach(c=>{dle(c.loaded,[s],o),kle(c,e),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{l[u]||(l[u]={});const d=c.loaded[u];d.length&&d.forEach(h=>{l[u][h]===void 0&&(l[u][h]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(e,n,r,a=0,s=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:a,wait:s,callback:o});return}this.readingCalls++;const l=(u,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const h=this.waitingReads.shift();this.read(h.lng,h.ns,h.fcName,h.tried,h.wait,h.callback)}if(u&&d&&a<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,r,a+1,s*2,o)},s);return}o(u,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const u=c(e,n);u&&typeof u.then=="function"?u.then(d=>l(null,d)).catch(l):l(null,u)}catch(u){l(u)}return}return c(e,n,l)}prepareLoading(e,n,r={},a){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),a&&a();yn(e)&&(e=this.languageUtils.toResolveHierarchy(e)),yn(n)&&(n=[n]);const s=this.queueLoad(e,n,r,a);if(!s.toLoad.length)return s.pending.length||a(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),a=r[0],s=r[1];this.read(a,s,"read",void 0,void 0,(o,l)=>{o&&this.logger.warn(`${n}loading namespace ${s} for language ${a} failed`,o),!o&&l&&this.logger.log(`${n}loaded namespace ${s} for language ${a}`,l),this.loaded(e,o,l)})}saveMissing(e,n,r,a,s,o={},l=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const c={...o,isUpdate:s},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(e,n,r,a,c):d=u(e,n,r,a),d&&typeof d.then=="function"?d.then(h=>l(null,h)).catch(l):l(null,d)}catch(d){l(d)}else u(e,n,r,a,l,c)}!e||!e[0]||this.store.addResource(e[0],n,r,a)}}}const oB=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),yn(t[1])&&(e.defaultValue=t[1]),yn(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),lB=t=>(yn(t.ns)&&(t.ns=[t.ns]),yn(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),yn(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),tS=()=>{},Tle=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class Hy extends IC{constructor(e={},n){if(super(),this.options=lB(e),this.services={},this.logger=Cc,this.modules={external:[]},Tle(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(yn(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const r=oB();this.options={...r,...this.options,...lB(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator);const a=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Cc.init(a(this.modules.logger),this.options):Cc.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=Cle;const d=new nB(this.options);this.store=new eB(this.options.resources,this.options);const h=this.services;h.logger=Cc,h.resourceStore=this.store,h.languageUtils=d,h.pluralResolver=new wle(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(h.formatter=a(u),h.formatter.init&&h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new Sle(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new Ale(a(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",(p,...x)=>{this.emit(p,...x)}),this.modules.languageDetector&&(h.languageDetector=a(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=a(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new g1(this.services,this.options),this.translator.on("*",(p,...x)=>{this.emit(p,...x)}),this.modules.external.forEach(p=>{p.init&&p.init(this)})}if(this.format=this.options.interpolation.format,n||(n=tS),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const l=Zx(),c=()=>{const u=(d,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(h),n(d,h)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?c():setTimeout(c,0),l}loadResources(e,n=tS){let r=n;const a=yn(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(a?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],o=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(u=>{u!=="cimode"&&s.indexOf(u)<0&&s.push(u)})};a?o(a):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>o(c)),this.options.preload?.forEach?.(l=>o(l)),this.services.backendConnector.load(s,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(e,n,r){const a=Zx();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=tS),this.services.backendConnector.reload(e,n,s=>{a.resolve(),r(s)}),a}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&xK.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Zx();this.emit("languageChanging",e);const a=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},s=(l,c)=>{c?this.isLanguageChangingTo===e&&(a(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve((...u)=>this.t(...u)),n&&n(l,(...u)=>this.t(...u))},o=l=>{!e&&!l&&this.services.languageDetector&&(l=[]);const c=yn(l)?l:l&&l[0],u=this.store.hasLanguageSomeTranslations(c)?c:this.services.languageUtils.getBestMatchFromCodes(yn(l)?[l]:l);u&&(this.language||a(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{s(d,u)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),r}getFixedT(e,n,r){const a=(s,o,...l)=>{let c;typeof o!="object"?c=this.options.overloadTranslationOptionHandler([s,o].concat(l)):c={...o},c.lng=c.lng||a.lng,c.lngs=c.lngs||a.lngs,c.ns=c.ns||a.ns,c.keyPrefix!==""&&(c.keyPrefix=c.keyPrefix||r||a.keyPrefix);const u=this.options.keySeparator||".";let d;return c.keyPrefix&&Array.isArray(s)?d=s.map(h=>(typeof h=="function"&&(h=B2(h,{...this.options,...o})),`${c.keyPrefix}${u}${h}`)):(typeof s=="function"&&(s=B2(s,{...this.options,...o})),d=c.keyPrefix?`${c.keyPrefix}${u}${s}`:s),this.t(d,c)};return yn(e)?a.lng=e:a.lngs=e,a.ns=n,a.keyPrefix=r,a}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],a=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const o=(l,c)=>{const u=this.services.backendConnector.state[`${l}|${c}`];return u===-1||u===0||u===2};if(n.precheck){const l=n.precheck(this,o);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(r,e)&&(!a||o(s,e)))}loadNamespaces(e,n){const r=Zx();return this.options.ns?(yn(e)&&(e=[e]),e.forEach(a=>{this.options.ns.indexOf(a)<0&&this.options.ns.push(a)}),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=Zx();yn(e)&&(e=[e]);const a=this.options.preload||[],s=e.filter(o=>a.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=a.concat(s),this.loadResources(o=>{r.resolve(),n&&n(o)}),r):(n&&n(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const a=new Intl.Locale(e);if(a&&a.getTextInfo){const s=a.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new nB(oB());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new Hy(e,n);return r.createInstance=Hy.createInstance,r}cloneInstance(e={},n=tS){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const a={...this.options,...e,isClone:!0},s=new Hy(a);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(l=>{s[l]=this[l]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const l=Object.keys(this.store.data).reduce((c,u)=>(c[u]={...this.store.data[u]},c[u]=Object.keys(c[u]).reduce((d,h)=>(d[h]={...c[u][h]},d),c[u]),c),{});s.store=new eB(l,a),s.services.resourceStore=s.store}return s.translator=new g1(s.services,a),s.translator.on("*",(l,...c)=>{s.emit(l,...c)}),s.init(a,n),s.translator.options=a,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const zs=Hy.createInstance();zs.createInstance;zs.dir;zs.init;zs.loadResources;zs.reloadResources;zs.use;zs.changeLanguage;zs.getFixedT;zs.t;zs.exists;zs.setDefaultNamespace;zs.hasLoadedNamespace;zs.loadNamespaces;zs.loadLanguages;const Mle=(t,e,n,r)=>{const a=[n,{code:e,...r||{}}];if(t?.services?.logger?.forward)return t.services.logger.forward(a,"warn","react-i18next::",!0);kf(a[0])&&(a[0]=`react-i18next:: ${a[0]}`),t?.services?.logger?.warn?t.services.logger.warn(...a):console?.warn&&console.warn(...a)},cB={},vK=(t,e,n,r)=>{kf(n)&&cB[n]||(kf(n)&&(cB[n]=new Date),Mle(t,e,n,r))},wK=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},H2=(t,e,n)=>{t.loadNamespaces(e,wK(t,n))},uB=(t,e,n,r)=>{if(kf(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return H2(t,n,r);n.forEach(a=>{t.options.ns.indexOf(a)<0&&t.options.ns.push(a)}),t.loadLanguages(e,wK(t,r))},Ple=(t,e,n={})=>!e.languages||!e.languages.length?(vK(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(r,a)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!a(r.isLanguageChangingTo,t))return!1}}),kf=t=>typeof t=="string",Ele=t=>typeof t=="object"&&t!==null,jle=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Dle={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Rle=t=>Dle[t],Fle=t=>t.replace(jle,Rle);let $2={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Fle,transDefaultProps:void 0};const Lle=(t={})=>{$2={...$2,...t}},Ole=()=>$2;let SK;const Ile=t=>{SK=t},zle=()=>SK,Ule={type:"3rdParty",init(t){Lle(t.options.react),Ile(t)}},Ble=w.createContext();class Hle{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var RM={exports:{}},FM={};var dB;function $le(){if(dB)return FM;dB=1;var t=zb();function e(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,a=t.useEffect,s=t.useLayoutEffect,o=t.useDebugValue;function l(h,f){var p=f(),x=r({inst:{value:p,getSnapshot:f}}),v=x[0].inst,g=x[1];return s(function(){v.value=p,v.getSnapshot=f,c(v)&&g({inst:v})},[h,p,f]),a(function(){return c(v)&&g({inst:v}),h(function(){c(v)&&g({inst:v})})},[h]),o(p),p}function c(h){var f=h.getSnapshot;h=h.value;try{var p=f();return!n(h,p)}catch{return!0}}function u(h,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return FM.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,FM}var hB;function _K(){return hB||(hB=1,RM.exports=$le()),RM.exports}var oF=_K();const Vle=(t,e)=>kf(e)?e:Ele(e)&&kf(e.defaultValue)?e.defaultValue:Array.isArray(t)?t[t.length-1]:t,qle={t:Vle,ready:!1},Gle=()=>()=>{},Ot=(t,e={})=>{const{i18n:n}=e,{i18n:r,defaultNS:a}=w.useContext(Ble)||{},s=n||r||zle();s&&!s.reportNamespaces&&(s.reportNamespaces=new Hle),s||vK(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=w.useMemo(()=>({...Ole(),...s?.options?.react,...e}),[s,e]),{useSuspense:l,keyPrefix:c}=o,u=a||s?.options?.defaultNS,d=kf(u)?[u]:u||["translation"],h=w.useMemo(()=>d,d);s?.reportNamespaces?.addUsedNamespaces?.(h);const f=w.useRef(0),p=w.useCallback(P=>{if(!s)return Gle;const{bindI18n:E,bindI18nStore:U}=o,L=()=>{f.current+=1,P()};return E&&s.on(E,L),U&&s.store.on(U,L),()=>{E&&E.split(" ").forEach(B=>s.off(B,L)),U&&U.split(" ").forEach(B=>s.store.off(B,L))}},[s,o]),x=w.useRef(),v=w.useCallback(()=>{if(!s)return qle;const P=!!(s.isInitialized||s.initializedStoreOnce)&&h.every($=>Ple($,s,o)),E=e.lng||s.language,U=f.current,L=x.current;if(L&&L.ready===P&&L.lng===E&&L.keyPrefix===c&&L.revision===U)return L;const D={t:s.getFixedT(E,o.nsMode==="fallback"?h:h[0],c),ready:P,lng:E,keyPrefix:c,revision:U};return x.current=D,D},[s,h,c,o,e.lng]),[g,y]=w.useState(0),{t:_,ready:N}=oF.useSyncExternalStore(p,v,v);w.useEffect(()=>{if(s&&!N&&!l){const P=()=>y(E=>E+1);e.lng?uB(s,e.lng,h,P):H2(s,h,P)}},[s,e.lng,h,N,l,g]);const k=s||{},A=w.useRef(null),M=w.useRef(),C=P=>{const E=Object.getOwnPropertyDescriptors(P);E.__original&&delete E.__original;const U=Object.create(Object.getPrototypeOf(P),E);if(!Object.prototype.hasOwnProperty.call(U,"__original"))try{Object.defineProperty(U,"__original",{value:P,writable:!1,enumerable:!1,configurable:!1})}catch{}return U},j=w.useMemo(()=>{const P=k,E=P?.language;let U=P;P&&(A.current&&A.current.__original===P?M.current!==E?(U=C(P),A.current=U,M.current=E):U=A.current:(U=C(P),A.current=U,M.current=E));const L=[_,U,N];return L.t=_,L.i18n=U,L.ready=N,L},[_,k,N,k.resolvedLanguage,k.language,k.languages]);if(s&&l&&!N)throw new Promise(P=>{const E=()=>P();e.lng?uB(s,e.lng,h,E):H2(s,h,E)});return j},{slice:Wle,forEach:Kle}=[];function Xle(t){return Kle.call(Wle.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Yle(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const mB=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Qle=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let s=`${t}=${a}`;if(r.maxAge>0){const o=r.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(r.domain){if(!mB.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!mB.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(s+="; Partitioned"),s},fB={create(t,e,n,r){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+n*60*1e3)),r&&(a.domain=r),document.cookie=Qle(t,e,a)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let a=n[r];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var Zle={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return fB.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:a,cookieOptions:s}=e;n&&typeof document<"u"&&fB.create(n,t,r,a,s)}},Jle={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const s=r.substring(1).split("&");for(let o=0;o<s.length;o++){const l=s[o].indexOf("=");l>0&&s[o].substring(0,l)===e&&(n=s[o].substring(l+1))}}return n}},ece={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:a}=window.location;if(a&&a.length>2){const s=a.substring(1);if(e){const o=s.split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(r=o[l].substring(c+1))}}if(r)return r;if(!r&&n>-1){const o=a.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let Up=null;const pB=()=>{if(Up!==null)return Up;try{if(Up=typeof window<"u"&&window.localStorage!==null,!Up)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Up=!1}return Up};var tce={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&pB())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&pB()&&window.localStorage.setItem(n,t)}};let Bp=null;const gB=()=>{if(Bp!==null)return Bp;try{if(Bp=typeof window<"u"&&window.sessionStorage!==null,!Bp)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Bp=!1}return Bp};var nce={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&gB())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&gB()&&window.sessionStorage.setItem(n,t)}},rce={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:a}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),a&&e.push(a)}return e.length>0?e:void 0}},ace={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},ice={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof e=="number"?e:0]?.replace("/",""):void 0}},sce={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let NK=!1;try{document.cookie,NK=!0}catch{}const CK=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];NK||CK.splice(1,1);const oce=()=>({order:CK,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class kK{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=Xle(n,this.options||{},oce()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Zle),this.addDetector(Jle),this.addDetector(tce),this.addDetector(nce),this.addDetector(rce),this.addDetector(ace),this.addDetector(ice),this.addDetector(sce),this.addDetector(ece)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(r=>{if(this.detectors[r]){let a=this.detectors[r].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(n=n.concat(a))}}),n=n.filter(r=>r!=null&&!Yle(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}kK.type="languageDetector";const lce={nav:{printers:"Printers",archives:"Archives",queue:"Queue",stats:"Statistics",profiles:"Profiles",maintenance:"Maintenance",projects:"Projects",inventory:"Filament",files:"File Manager",settings:"Settings",system:"System",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",update:"Update",updateAvailable:"Update available: v{{version}}",updateAvailableBanner:"Version {{version}} is available!",viewUpdate:"View update",viewOnGithub:"View on GitHub",keyboardShortcuts:"Keyboard shortcuts (?)",switchToLight:"Switch to light mode",switchToDark:"Switch to dark mode",smartSwitches:"Smart Switches",logout:"Logout"},common:{save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",edit:"Edit",add:"Add",close:"Close",confirm:"Confirm",loading:"Loading...",error:"Error",success:"Success",warning:"Warning",enabled:"Enabled",disabled:"Disabled",yes:"Yes",no:"No",on:"On",off:"Off",all:"All",none:"None",search:"Search",filter:"Filter",sort:"Sort",refresh:"Refresh",download:"Download",upload:"Upload",actions:"Actions",status:"Status",name:"Name",description:"Description",date:"Date",time:"Time",hours:"hours",minutes:"minutes",seconds:"seconds",days:"days",enable:"Enable",disable:"Disable",permissions:"Permissions",noPrinters:"No printers configured",noData:"No data available",linkNotFound:"Link not found",required:"Required",optional:"Optional",dismiss:"Dismiss",apply:"Apply",reset:"Reset",export:"Export",import:"Import",clear:"Clear",selectAll:"Select All",deselectAll:"Deselect All",noChange:"— No change —",unchanged:"Unchanged",unassigned:"Unassigned",unknown:"Unknown",unknownError:"Unknown error",today:"Today",tomorrow:"Tomorrow",asap:"ASAP",overdue:"Overdue",now:"Now",collapse:"Collapse",expand:"Expand",viewArchive:"View archive",viewInFileManager:"View in File Manager",addedBy:"Added by {{username}}",prints:"prints",more:"+{{count}} more",ascending:"Ascending",descending:"Descending",printer:"Printer",remove:"Remove",type:"Type",print:"Print",rename:"Rename",move:"Move",create:"Create",duplicate:"Duplicate",left:"Left",right:"Right"},printers:{title:"Printers",addPrinter:"Add Printer",editPrinter:"Edit Printer",deletePrinter:"Delete Printer",printerName:"Printer Name",serialNumber:"Serial Number",ipAddress:"IP Address / Hostname",accessCode:"Access Code",model:"Model",nozzleCount:"Nozzle Count",autoArchive:"Auto Archive",status:{available:"Available",idle:"Idle",printing:"Printing",paused:"Paused",offline:"Offline",error:"Error",finished:"Finished",unknown:"Unknown"},temperatures:{nozzle:"Nozzle",bed:"Bed",chamber:"Chamber"},progress:"{{percent}}% complete",timeRemaining:"{{time}} remaining",deleteConfirm:'Are you sure you want to delete "{{name}}"?',maintenanceOk:"Maintenance OK",maintenanceWarning:"{{count}} warning",maintenanceWarning_plural:"{{count}} warnings",maintenanceDue:"{{count}} due",maintenanceDue_plural:"{{count}} due",sort:{name:"Name",status:"Status",model:"Model",location:"Location",ascending:"Sort ascending",descending:"Sort descending"},cardSize:{small:"Small cards",medium:"Medium cards",large:"Large cards",extraLarge:"Extra large cards"},hideOffline:"Hide offline",nextAvailable:"Next available",powerOn:"Power On",offlinePrintersWithPlugs:"Offline printers with smart plugs",noPrintersConfigured:"No printers configured yet",readyToPrint:"Ready to print",external:"External",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Delete print archives",noLabel:"No label",printPreview:"Print preview",width:"Width",height:"Height",noObjectsFound:"No objects found",objectsLoadedOnPrintStart:"Objects are loaded when a print starts",willBeSkipped:"Will be skipped",name:"Name",serialCannotBeChanged:"Serial number cannot be changed",locationHelp:"Used to group printers and filter queue jobs",wifiSignal:{veryWeak:"Very weak",weak:"Weak",fair:"Fair",good:"Good",excellent:"Excellent"},maintenanceUpToDate:"All maintenance up to date - Click to view",chamberLightOn:"Turn on chamber light",chamberLightOff:"Turn off chamber light",browseFiles:"Browse printer files",autoOffAfterPrint:"Auto power-off after print",autoOffExecuted:"Auto-off was executed - turn printer on to reset",hmsErrors:"HMS Errors",viewHmsErrors:"View {{count}} HMS error(s)",resume:"Resume",pause:"Pause",stop:"Stop",camera:"Camera",skipObject:"Skip Object",reconnect:"Reconnect",mqttDebug:"MQTT Debug",activeNozzle:"Active: {{nozzle}} nozzle",nozzleRack:"Nozzle Rack",nozzleDocked:"Docked",nozzleMounted:"Mounted",nozzleActive:"Active",nozzleIdle:"Idle",nozzleDiameter:"Diameter",nozzleType:"Type",nozzleStatus:"Status",nozzleFilament:"Filament",nozzleWear:"Wear",nozzleMaxTemp:"Max Temp",nozzleSerial:"Serial",nozzleHardenedSteel:"Hardened Steel",nozzleStainlessSteel:"Stainless Steel",nozzleTungstenCarbide:"Tungsten Carbide",nozzleFlow:"Flow",nozzleHighFlow:"High Flow",nozzleStandardFlow:"Standard",firmwareUpdate:"Firmware Update",firmwareInstructions:"On the printer's touchscreen, go to",firmwareNav:"Navigate to",settings:"Settings",firmware:"Firmware",discoverPrinters:"Discover Printers",searching:"Searching...",manualEntry:"Manual Entry",addFromCloud:"Add from Cloud",toast:{printerDeleted:"Printer deleted",printerAdded:"Printer added",printerUpdated:"Printer updated",failedToDelete:"Failed to delete printer",failedToAdd:"Failed to add printer",failedToUpdate:"Failed to update printer",commandSent:"Command sent",failedToSendCommand:"Failed to send command",turnedOn:"{{name}} turned on",failedToPowerOn:"Failed to power on {{name}}",scriptTriggered:"Script triggered",printStopped:"Print stopped",printPaused:"Print paused",printResumed:"Print resumed",referenceDeleted:"Reference deleted",detectionAreaSaved:"Detection area saved",failedToRunScript:"Failed to run script",failedToStopPrint:"Failed to stop print",failedToPausePrint:"Failed to pause print",failedToResumePrint:"Failed to resume print",failedToControlChamberLight:"Failed to control chamber light",failedToUpdateSetting:"Failed to update setting",failedToSkipObjects:"Failed to skip objects",failedToRereadRfid:"Failed to re-read RFID",failedToCheckPlate:"Failed to check plate",failedToUpdateLabel:"Failed to update label",failedToDeleteReference:"Failed to delete reference",failedToSaveDetectionArea:"Failed to save detection area",plateCheckEnabled:"Plate check enabled",plateCheckDisabled:"Plate check disabled",calibrationSaved:"Calibration saved!",calibrationFailed:"Calibration failed",rfidRereadInitiated:"RFID re-read initiated"},connection:{connected:"Connected",offline:"Offline"},queue:{inQueue:"{{count}} print in queue",inQueue_plural:"{{count}} prints in queue"},controls:"Controls",rfid:{reread:"Re-read RFID"},permission:{noAdd:"You do not have permission to add printers",noEdit:"You do not have permission to edit printers",noDelete:"You do not have permission to delete printers",noControl:"You do not have permission to control printers",noFiles:"You do not have permission to access printer files",noAmsRfid:"You do not have permission to re-read AMS RFID",noSmartPlugControl:"You do not have permission to control smart plugs"},modal:{addTitle:"Add Printer",editTitle:"Edit Printer",myPrinter:"My Printer",selectModel:"Select model...",locationGroup:"Location / Group (optional)",locationPlaceholder:"e.g., Workshop, Office, Basement",autoArchiveLabel:"Auto-archive completed prints",fromPrinterSettings:"From printer settings",modelOptional:"Model (optional)",saveChanges:"Save Changes"},skipObjects:{tooltip:"Skip objects",onlyWhilePrinting:"Skip objects (only while printing)",requiresMultiple:"Skip objects (requires 2+ objects)",title:"Skip Objects",matchIdsInfo:"Match IDs with your printer display",printerShowsIds:"The printer screen shows object IDs on the build plate",skipSelected:"Skip Selected",skipping:"Skipping...",noObjectsSelected:"No objects selected",selectObjectsToSkip:"Select objects you want to skip from the current print",skipped:"skipped",objectsSkipped:"Objects skipped",activeCount:"{{count}} active",waitForLayer:"Wait for layer 2+ to skip objects (currently layer {{layer}})",skip:"Skip",confirmTitle:"Skip Object?",confirmMessage:'Are you sure you want to skip "{{name}}"? This cannot be undone.'},confirm:{deleteTitle:"Delete Printer",deleteMessage:'Are you sure you want to delete "{{name}}"? This will remove all connection settings.',deleteArchivesNote:"All print history for this printer will be permanently deleted.",keepArchivesNote:"Print history will be kept but no longer associated with this printer.",stopTitle:"Stop Print",stopMessage:'Are you sure you want to stop the current print on "{{name}}"? This will cancel the print job.',stopButton:"Stop Print",pauseTitle:"Pause Print",pauseMessage:'Are you sure you want to pause the current print on "{{name}}"?',pauseButton:"Pause Print",resumeTitle:"Resume Print",resumeMessage:'Are you sure you want to resume the print on "{{name}}"?',resumeButton:"Resume Print",powerOnTitle:"Power On Printer",powerOnMessage:'Are you sure you want to turn ON the power for "{{name}}"?',powerOnButton:"Power On",powerOffTitle:"Power Off Printer",powerOffMessage:'Are you sure you want to turn OFF the power for "{{name}}"?',powerOffWarning:'WARNING: "{{name}}" is currently printing! Are you sure you want to turn OFF the power? This will interrupt the print and may damage the printer.',powerOffButton:"Power Off"},discovery:{title:"Discover Printers",searching:"Searching...",scanning:"Scanning...",scanProgress:"Scanning... {{scanned}}/{{total}}",foundPrinters:"Found {{count}} printer(s)",noPrintersFound:"No printers found",noPrintersFoundSubnet:"No printers found in the specified subnet.",noPrintersFoundNetwork:"No printers found on the network.",allConfigured:"All discovered printers are already configured.",alreadyAdded:"Already added",select:"Select",manualEntry:"Manual Entry",addFromCloud:"Add from Cloud",subnetToScan:"Subnet to scan",dockerNote:"Docker detected. Enter your printer's subnet in CIDR notation. Requires network_mode: host in docker-compose.yml.",scanSubnet:"Scan Subnet for Printers",discoverNetwork:"Discover Printers on Network",scanningSubnet:"Scanning subnet for Bambu printers...",scanningNetwork:"Scanning network...",serialRequired:"Serial required",unknown:"Unknown",failedToStart:"Failed to start discovery"},filaments:"Filaments",openCameraOverlay:"Open camera overlay",openCameraWindow:"Open camera in new window",firmwareUpdateAvailable:"Firmware update available: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Up to date",firmwareUpdateButton:"Update",plateDetection:{noPermission:"You do not have permission to update printers",enabledClick:"Plate check enabled - Click to disable",disabledClick:"Plate check disabled - Click to enable",manageCalibration:"Manage plate detection calibration",calibrationRequired:"Calibration Required",calibrationInstructions:"Please ensure the build plate is <strong>completely empty</strong>, then click Calibrate.",calibrationDescription:"Calibration captures a reference image of the empty plate. Future checks will compare against this reference to detect objects.",calibrationTip:"<strong>Tip:</strong> You can store up to 5 calibrations for different plates. The system automatically uses the best match when checking.",plateEmpty:"Plate appears empty",objectsDetected:"Objects detected on plate",confidence:"Confidence",difference:"Difference",analysisPreview:"Analysis preview:",analysisLegend:"Green box = detection area, Red overlay = differences from calibration",savedReferences:"Saved References ({{count}}/{{max}})",deleteReference:"Delete reference",labelPlaceholder:"Label...",clickToEdit:"{{label}} - Click to edit",clickToAddLabel:"Click to add label"},fans:{partCooling:"Part Cooling Fan",auxiliary:"Auxiliary Fan",chamber:"Chamber Fan"},clickToViewHmsErrors:"Click to view HMS errors",estimatedCompletion:"Estimated completion time",slotOptions:"Slot options",firmwareModal:{title:"Firmware Update",titleUpToDate:"Firmware Info",currentVersion:"Current:",latestVersion:"Latest:",releaseNotes:"Release Notes",checkingPrereqs:"Checking prerequisites...",sdCardReady:"SD card ready. Click below to upload firmware.",uploadedSuccess:"Firmware uploaded to SD card!",applyInstructions:"To apply the update on your printer:",step1:"On the printer's touchscreen, go to <strong>Settings</strong>",step2:"Navigate to <strong>Firmware</strong>",step3:"Select <strong>Update from SD card</strong>",step4:"The update will take 10-20 minutes",done:"Done",starting:"Starting...",uploadFirmware:"Upload Firmware",uploadFailed:"Failed to start upload: {{error}}",uploadedToast:"Firmware uploaded! Trigger update from printer screen."},accessCodePlaceholder:"Leave empty to keep current",roi:{title:"Detection Area (ROI)",xStart:"X Start",yStart:"Y Start",width:"Width",height:"Height",instruction:"Adjust the detection area to focus on the build plate. The green box in the preview shows the current area."},developerModeWarning:"Developer LAN mode is not enabled on: {{names}}. Some features may not work.",howToEnable:"How to enable"},archives:{title:"Print Archives",searchPlaceholder:"Search archives...",filterByPrinter:"Filter by printer",filterByStatus:"Filter by status",sortBy:"Sort by",sortNewest:"Newest first",sortOldest:"Oldest first",sortName:"Name",sortDuration:"Duration",sortLargest:"Largest first",sortSmallest:"Smallest first",sortSize:"Size",noArchives:"No archives found",noArchivesSearch:"No archives match your search",noArchivesYet:"No archives yet",loadingArchives:"Loading archives...",releaseToUpload:"Release to upload",showAll:"Show all",showFavoritesOnly:"Show favorites only",gridView:"Grid view",listView:"List view",calendarView:"Calendar view",logView:"Print Log",manageTags:"Manage Tags",showFailedPrints:"Show failed prints",hideFailedPrints:"Hide failed prints",printTime:"Print Time",filamentUsed:"Filament Used",cost:"Cost",reprint:"Reprint",preview:"Preview",deleteArchive:"Delete Archive",deleteConfirm:"Are you sure you want to delete this archive?",favorite:"Favorite",unfavorite:"Remove from favorites",viewDetails:"View Details",status:{completed:"Completed",failed:"Failed",stopped:"Stopped"},toast:{source3mfAttached:"Source 3MF attached: {{filename}}",failedUploadSource3mf:"Failed to upload source 3MF",source3mfRemoved:"Source 3MF removed",failedRemoveSource3mf:"Failed to remove source 3MF",f3dAttached:"F3D attached: {{filename}}",failedUploadF3d:"Failed to upload F3D",f3dRemoved:"F3D removed",failedRemoveF3d:"Failed to remove F3D",timelapseAttached:"Timelapse attached: {{filename}}",timelapseAlreadyAttached:"Timelapse already attached",noMatchingTimelapse:"No matching timelapse found",failedScanTimelapse:"Failed to scan for timelapse",failedAttachTimelapse:"Failed to attach timelapse",timelapseRemoved:"Timelapse removed",failedRemoveTimelapse:"Failed to remove timelapse",timelapseUploaded:"Timelapse uploaded: {{filename}}",failedUploadTimelapse:"Failed to upload timelapse",archiveDeleted:"Archive deleted",failedDeleteArchive:"Failed to delete archive",addedToFavorites:"Added to favorites",removedFromFavorites:"Removed from favorites",projectUpdated:"Project updated",failedUpdateProject:"Failed to update project",linkCopied:"Link copied to clipboard",failedCopyLink:"Failed to copy link",photoDeleted:"Photo deleted",failedDeletePhoto:"Failed to delete photo",failedDeleteArchives:"Failed to delete archives",failedUpdateFavorites:"Failed to update favorites",exportDownloaded:"Export downloaded",exportFailed:"Export failed"},menu:{print:"Print",schedule:"Schedule",openInBambuStudio:"Open in Slicer",slice:"Slice",externalLink:"External Link",viewOnMakerWorld:"View on MakerWorld",preview3d:"3D Preview",viewTimelapse:"View Timelapse",scanForTimelapse:"Scan for Timelapse",uploadTimelapse:"Upload Timelapse",removeTimelapse:"Remove Timelapse",downloadSource3mf:"Download Source 3MF",uploadSource3mf:"Upload Source 3MF",replaceSource3mf:"Replace Source 3MF",removeSource3mf:"Remove Source 3MF",uploadF3d:"Upload F3D",replaceF3d:"Replace F3D",downloadF3d:"Download F3D",removeF3d:"Remove F3D",download:"Download",copyDownloadLink:"Copy Download Link",qrCode:"QR Code",viewPhotos:"View Photos",viewPhotosCount:"View Photos ({{count}})",projectPage:"Project Page",addToFavorites:"Add to Favorites",removeFromFavorites:"Remove from Favorites",edit:"Edit",goToProject:"Go to Project: {{name}}",addToProject:"Add to Project",removeFromProject:"Remove from Project",loading:"Loading...",noProjectsAvailable:"No projects available",select:"Select",deselect:"Deselect",delete:"Delete"},permission:{noReprint:"You do not have permission to reprint this archive",noAddToQueue:"You do not have permission to add to queue",noUpdateArchives:"You do not have permission to update archives",noUploadFiles:"You do not have permission to upload files",noDownload:"You do not have permission to download archives",noCopyLink:"You do not have permission to copy download links",noDelete:"You do not have permission to delete this archive",noCreate:"You do not have permission to create archives"},card:{previousPlate:"Previous plate",nextPlate:"Next plate",plateNumber:"Plate {{index}}",moreOptions:"Right-click for more options",addToFavorites:"Add to favorites",removeFromFavorites:"Remove from favorites",cancelled:"cancelled",failed:"failed",duplicate:"duplicate",duplicateTitle:"This model has been printed before",openSource3mf:"Open source 3MF in Bambu Studio (right-click for more options)",downloadF3d:"Download Fusion 360 design file",viewTimelapse:"View timelapse",viewPhoto:"View 1 photo",viewPhotos:"View {{count}} photos",openFolder:"Open folder: {{name}}",slicedFile:"Sliced file - ready to print",sourceFile:"Source file only - no AMS mapping available",gcode:"GCODE",source:"SOURCE",project:"Project: {{name}}",estimated:"Estimated: {{time}}",actual:"Actual: {{time}}",accuracy:"Accuracy: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} layer",layers:"{{count}} layers",object:"{{count}} object",objects:"{{count}} objects",slicedFor:"Sliced for {{model}}",uploadedBy:"Uploaded By",noPermissionReprint:"You do not have permission to reprint",noFileForReprint:"No 3MF file available — the file could not be downloaded from the printer when the print was recorded",noPermissionEdit:"You do not have permission to edit archives",noPermissionDelete:"You do not have permission to delete archives",reprint:"Reprint",schedulePrint:"Schedule Print",schedule:"Schedule",openInBambuStudio:"Open in Slicer",openInBambuStudioToSlice:"Open in Slicer to slice",slice:"Slice",externalLink:"External Link",makerWorld:"MakerWorld: {{designer}}",viewProject:"View project",noExternalLink:"No external link",preview3d:"3D Preview",download:"Download",edit:"Edit",delete:"Delete"},modal:{deleteArchive:"Delete Archive",deleteConfirm:'Are you sure you want to delete "{{name}}"? This action cannot be undone.',deleteButton:"Delete",removeSource3mf:"Remove Source 3MF",removeSource3mfConfirm:'Are you sure you want to remove the source 3MF file from "{{name}}"? This will delete the original slicer project file.',removeButton:"Remove",removeF3d:"Remove F3D",removeF3dConfirm:'Are you sure you want to remove the Fusion 360 design file from "{{name}}"?',removeTimelapse:"Remove Timelapse",removeTimelapseConfirm:'Are you sure you want to remove the timelapse video from "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Select Timelapse",selectTimelapseDesc:"No auto-match found. Select the timelapse for this print:",deleteArchives:"Delete Archives",deleteArchivesConfirm:"Are you sure you want to delete {{count}} archive(s)? This action cannot be undone.",deleteCount:"Delete {{count}}"},page:{title:"Archives",printsCount:"{{filtered}} of {{total}} prints",dropFilesHere:"Drop .3mf files here",releaseToUpload:"Release to upload",only3mfSupported:"Only .3mf files are supported",close:"Close",selected:"{{count}} selected",selectAll:"Select All",tags:"Tags",project:"Project",favorite:"Favorite",delete:"Delete",toggledFavorites:"Toggled favorites for {{count}} archive(s)",failedUpdateFavorites:"Failed to update favorites",archivesDeleted:"{{count}} archive(s) deleted",failedDeleteArchives:"Failed to delete archives",photoDeleted:"Photo deleted",failedDeletePhoto:"Failed to delete photo"},list:{name:"Name",printer:"Printer",date:"Date",size:"Size",actions:"Actions",hasTimelapse:"Has timelapse"},log:{date:"Date",printName:"Print Name",printer:"Printer",user:"User",status:"Status",duration:"Duration",filament:"Filament",allPrinters:"All Printers",allUsers:"All Users",allStatuses:"All Statuses",cancelled:"Cancelled",skipped:"Skipped",dateFrom:"From",dateTo:"To",noEntries:"No print log entries found",showing:"Showing {{count}} of {{total}} entries",rowsPerPage:"Rows",page:"Page",prev:"Prev",next:"Next",clearLog:"Clear Log",clearLogTitle:"Clear Print Log",clearLogConfirm:"All print log entries will be permanently deleted. Archives and queue items are not affected. This action cannot be undone. Are you sure?",clearLogButton:"Clear All",cleared:"{{count}} log entries cleared",clearFailed:"Failed to clear print log"}},queue:{title:"Print Queue",subtitle:"Schedule and manage your print jobs",addToQueue:"Add to Queue",print:"Print",reprint:"Re-print",schedulePrint:"Schedule Print",editQueueItem:"Edit Queue Item",printToPrinters:"Print to {{count}} Printers",queueToPrinters:"Queue to {{count}} Printers",sending:"Sending...",sendingProgress:"Sending {{current}}/{{total}}...",adding:"Adding...",addingProgress:"Adding {{current}}/{{total}}...",savingProgress:"Saving {{current}}/{{total}}...",clearQueue:"Clear Queue",clearHistory:"Clear History",emptyQueue:"Queue is empty",position:"Position",scheduledTime:"Scheduled Time",moveUp:"Move Up",moveDown:"Move Down",startNow:"Start Now",printingInProgress:"Printing in progress...",viewArchive:"View archive",viewInFileManager:"View in File Manager",itemCount:"{{count}} item",itemCount_plural:"{{count}} items",dragToReorder:"Drag to reorder (ASAP only)",reorderHint:"Position only affects ASAP items. Scheduled items run at their set time.",addedBy:"Added by {{name}}",nextInQueue:"Next in queue",clearPlate:"Clear Plate & Start Next",clearPlateSuccess:"Plate cleared — ready for next print",plateReady:"Plate cleared — ready for next print",plateNumber:"Plate {{index}}",sections:{currentlyPrinting:"Currently Printing",queued:"Queued",history:"History"},status:{pending:"Pending",waiting:"Waiting",printing:"Printing",paused:"Paused",completed:"Completed",failed:"Failed",skipped:"Skipped",cancelled:"Cancelled"},summary:{printing:"Printing",queued:"Queued",totalTime:"Total Queue Time",totalWeight:"Total Queue Weight",history:"History"},filter:{allPrinters:"All Printers",unassigned:"Unassigned",allStatus:"All Status",allLocations:"All Locations",any:"Any"},sort:{byPosition:"Sort by Position",byName:"Sort by Name",byPrinter:"Sort by Printer",bySchedule:"Sort by Schedule",byDate:"Sort by Date",ascendingOldest:"Ascending (oldest first)",descendingNewest:"Descending (newest first)"},badges:{staged:"Staged",requiresPrevious:"Requires previous success",autoPowerOff:"Auto power off"},empty:{title:"No prints scheduled",description:'Schedule a print from the Archives page using the "Schedule" option in the context menu, or drag and drop files to get started.'},time:{asap:"ASAP",overdue:"Overdue",now:"Now",lessThanMinute:"In less than a minute",inMinutes:"In {{count}} min",inHours:"In {{count}} hours"},actions:{stopPrint:"Stop Print",startPrint:"Start Print",requeue:"Re-queue"},bulkEdit:{title:"Edit {{count}} Item",title_plural:"Edit {{count}} Items",description:"Only changed settings will be applied to selected items.",printer:"Printer",noChange:"— No change —",queueOptions:"Queue Options",staged:"Staged (manual start)",autoPowerOff:"Auto power off after print",requirePrevious:"Require previous success",printOptions:"Print Options",bedLevelling:"Bed levelling",flowCalibration:"Flow calibration",vibrationCalibration:"Vibration calibration",layerInspection:"First layer inspection",timelapse:"Timelapse",useAms:"Use AMS",applyChanges:"Apply Changes",selectAll:"Select All",deselectAll:"Deselect All",selected:"{{count}} selected",editSelected:"Edit Selected",cancelSelected:"Cancel Selected"},confirm:{cancelTitle:"Cancel Scheduled Print",cancelMessage:'Are you sure you want to cancel "{{name}}"?',stopTitle:"Stop Print",stopMessage:'Are you sure you want to stop the current print "{{name}}"? This will cancel the print job on the printer.',removeTitle:"Remove from History",removeMessage:'Are you sure you want to remove "{{name}}" from the queue history?',clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to remove all {{count}} item(s) from the history?",cancelButton:"Cancel Print",stopButton:"Stop Print",thisPrint:"this print",thisItem:"this item"},toast:{cancelled:"Queue item cancelled",cancelFailed:"Failed to cancel item",removed:"Queue item removed",removeFailed:"Failed to remove item",stopped:"Print stopped",stopFailed:"Failed to stop print",released:"Print released to queue",startFailed:"Failed to start print",reorderFailed:"Failed to reorder queue",historyCleared:"Cleared {{count}} history item(s)",clearHistoryFailed:"Failed to clear history",updateFailed:"Failed to update items",bulkCancelled:"Cancelled {{count}} item(s)",bulkCancelFailed:"Failed to cancel items"},permissions:{noStopPrint:"You do not have permission to stop prints",noStartPrint:"You do not have permission to start prints",noEdit:"You do not have permission to edit this queue item",noCancel:"You do not have permission to cancel this queue item",noRequeue:"You do not have permission to re-queue items",noRemove:"You do not have permission to remove this queue item",noClearHistory:"You do not have permission to clear all history",noEditItems:"You do not have permission to edit queue items",noCancelItems:"You do not have permission to cancel queue items"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded"}},stats:{title:"Dashboard",subtitle:"Drag widgets to rearrange. Click the eye icon to hide.",overview:"Overview",totalPrints:"Total Prints",successRate:"Success Rate",totalPrintTime:"Total Print Time",printTime:"Print Time",totalFilament:"Total Filament Used",filamentUsed:"Filament Used",filamentCost:"Filament Cost",totalCost:"Total Cost",energyUsed:"Energy Used",energyCost:"Energy Cost",averagePrintTime:"Average Print Time",printsPerDay:"Prints per Day",byPrinter:"By Printer",printsByPrinter:"Prints by Printer",byMaterial:"By Material",byMonth:"By Month",last7Days:"Last 7 Days",last30Days:"Last 30 Days",last90Days:"Last 90 Days",allTime:"All Time",quickStats:"Quick Stats",printActivity:"Print Activity",filamentTypes:"Filament Types",filamentTrends:"Filament Trends",failureAnalysis:"Failure Analysis",timeAccuracy:"Time Accuracy",successful:"Successful:",failed:"Failed:",perfectEstimate:"100% = perfect estimate",noTimeAccuracyData:"No time accuracy data yet",noFilamentData:"No filament data available",noPrinterData:"No printer data available",noPrintData:"No print data available",noPrintDataLast30Days:"No print data in the last 30 days",failureReasons:"Failure Reasons",topFailureReasons:"Top Failure Reasons",failedPrintsCount:"{{failed}} / {{total}} prints failed",lastWeekRate:"Last week: {{rate}}%",resetLayout:"Reset Layout",recalculateCosts:"Recalculate Costs",recalculateCostsHint:"Recalculate all archive costs using current filament prices",exportStats:"Export Stats",exportAsCsv:"Export as CSV",exportAsExcel:"Export as Excel",hiddenCount:"{{count}} Hidden",exportDownloaded:"Export downloaded",exportFailed:"Export failed",layoutReset:"Layout reset",recalculatedCosts:"Recalculated costs for {{count}} archives",recalculateFailed:"Failed to recalculate costs",loadingStats:"Loading statistics...",noPermissionResetLayout:"You do not have permission to reset layout",noPermissionRecalculate:"You do not have permission to recalculate costs"},maintenance:{title:"Maintenance",overview:"Overview",allOk:"All maintenance up to date",dueCount:"{{count}} item due",dueCount_plural:"{{count}} items due",warningCount:"{{count}} warning",warningCount_plural:"{{count}} warnings",totalPrintTime:"Total Print Time",nextMaintenance:"Next Maintenance",nothingDue:"Nothing due",tasks:"Tasks",lastPerformed:"Last performed",interval:"Interval",hoursRemaining:"{{hours}}h remaining",hoursOverdue:"{{hours}}h overdue",markDone:"Mark as Done",performMaintenance:"Perform Maintenance",history:"History",noHistory:"No maintenance history",editPrintHours:"Edit Print Hours",currentHours:"Current Hours",statusTab:"Status",settingsTab:"Settings",overdueCount:"{{count}} overdue",dueSoonCount:"{{count}} due soon",dueSoon:"Due soon",allGood:"All good",overdueBy:"Overdue by {{duration}}",dueIn:"Due in {{duration}}",timeLeft:"{{duration}} left",day:"1 day",days:"{{count}} days",week:"1 week",weeks:"{{count}} weeks",month:"1 month",months:"{{count}} months",year:"1 year",maintenanceTypes:"Maintenance Types",maintenanceTypesDescription:"System types and your custom maintenance tasks",addCustomType:"Add Custom Type",restoreDefaults:"Restore Default Tasks",intervalType:"Interval Type",intervalValue:"Interval ({{type}})",icon:"Icon",documentationLink:"Documentation Link (optional)",assignToPrinters:"Assign to Printers",selectAtLeastOnePrinter:"Select at least one printer",addType:"Add Type",custom:"Custom",printHours:"Print Hours",calendarDays:"Calendar Days",exampleName:"e.g., Replace HEPA Filter",viewDocumentation:"View documentation",timeBasedInterval:"Time-based interval",intervalOverrides:"Interval Overrides",intervalOverridesDescription:"Customize intervals for specific printers",assignedToPrinters:"Assigned to printers:",noPrintersAssigned:"No printers assigned",addPrinterShort:"Add:",printersAssignedClick:"{{count}} printer(s) assigned - click to manage",removeFromPrinter:"Remove from this printer",types:{lubricateCarbonRods:"Lubricate Carbon Rods",lubricateRails:"Lubricate Linear Rails",cleanNozzle:"Clean Nozzle/Hotend",checkBelts:"Check Belt Tension",cleanBuildPlate:"Clean Build Plate",checkExtruder:"Check Extruder Gears",checkCooling:"Check Cooling Fans",generalInspection:"General Inspection",cleanCarbonRods:"Clean Carbon Rods",cleanLinearRails:"Clean Linear Rails",checkPtfeTube:"Check PTFE Tube",replaceHepaFilter:"Replace HEPA Filter",replaceCarbonFilter:"Replace Carbon Filter",lubricateLeftNozzleRail:"Lubricate Left Nozzle Rail"},maintenanceComplete:"Maintenance marked as complete",typeUpdated:"Maintenance type updated",typeDeleted:"Maintenance type deleted",defaultsRestored:"Restored {{count}} default task(s)",printHoursUpdated:"Print hours updated",printerAssigned:"Printer assigned",printerRemoved:"Printer removed",deleteTypeConfirm:'Delete "{{name}}"?',deleteSystemTypeTitle:"Delete default maintenance task?",deleteSystemTypeMessage:'Are you sure you want to delete the default maintenance task "{{name}}"?',noPermissionUpdate:"You do not have permission to update maintenance items",noPermissionPerform:"You do not have permission to perform maintenance",noPermissionEditTypes:"You do not have permission to edit maintenance types",noPermissionDeleteTypes:"You do not have permission to delete maintenance types",noPermissionEditHours:"You do not have permission to edit print hours",noPermissionRemovePrinter:"You do not have permission to remove printer assignments",noPermissionAssignPrinter:"You do not have permission to assign printers",noPermissionEditIntervals:"You do not have permission to edit intervals",configureSettings:"Configure maintenance types and intervals"},settings:{title:"Settings",general:"General",tabs:{general:"General",smartPlugs:"Smart Plugs",notifications:"Notifications",filament:"Filament",network:"Network",apiKeys:"API Keys",virtualPrinter:"Virtual Printer",users:"Authentication",backup:"Backup",emailAuth:"Email Authentication"},email:{smtpSettings:"SMTP Configuration",smtpHost:"SMTP Server",smtpPort:"SMTP Port",security:"Security",authentication:"Authentication",username:"Username",password:"Password",fromEmail:"From Email",fromName:"From Name",testConnection:"Test SMTP Connection",testRecipient:"Test Recipient Email",sendTest:"Send Test Email",sending:"Sending...",save:"Save Settings",saving:"Saving...",advancedAuth:"Advanced Authentication",advancedAuthEnabled:"Advanced Authentication is enabled",advancedAuthEnabledDesc:"Email-based user management features are active. New users will receive auto-generated passwords via email, and users can reset their passwords through the forgot password feature.",advancedAuthDisabled:"Advanced Authentication is disabled",advancedAuthDisabledDesc:"Enable advanced authentication to activate email-based features for user management.",enable:"Enable",disable:"Disable",feature1:"Passwords are auto-generated and emailed to new users",feature2:"Users can login with username or email",feature3:"Forgot password feature is available",feature4:"Admins can reset user passwords via email",errors:{requiredFields:"Please fill in all required fields",usernameRequired:"Username is required when authentication is enabled",enterTestEmail:"Please enter a test email address",smtpServerAndEmail:"Please fill in SMTP Server and From Email before testing",usernamePasswordRequired:"Username and Password are required when authentication is enabled",configureSmtpFirst:"Please configure and test SMTP settings first"},success:{settingsSaved:"SMTP settings saved successfully"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"None (Port 25)"},authOptions:{enabled:"Enabled",disabled:"Disabled"}},appearance:"Appearance",notifications:"Notifications",smartPlugs:"Smart Plugs",spoolman:"Spoolman",updates:"Updates",language:"Language",languageDescription:"Select your preferred language",theme:"Theme",themeLight:"Light",themeDark:"Dark",themeSystem:"System",defaultView:"Default View",defaultViewDescription:"Page to show when opening the app",checkForUpdates:"Check for Updates",autoUpdate:"Auto Update",currentVersion:"Current Version",latestVersion:"Latest Version",upToDate:"You are up to date",updateAvailable:"Update available",notificationLanguage:"Notification Language",notificationLanguageDescription:"Language for push notifications",bedCooledThreshold:"Bed Cooled Threshold",bedCooledThresholdDescription:"Temperature below which the bed is considered cooled after a print",notificationProviders:"Notification Providers",addProvider:"Add Provider",editProvider:"Edit Provider",providerType:"Provider Type",testNotification:"Test Notification",testSuccess:"Test notification sent successfully",testFailed:"Failed to send test notification",quietHours:"Quiet Hours",quietHoursDescription:"Do not disturb during these hours",quietHoursStart:"Start",quietHoursEnd:"End",events:{title:"Notification Events",printStart:"Print Started",printComplete:"Print Completed",printFailed:"Print Failed",printStopped:"Print Stopped",printProgress:"Progress Milestones",printProgressDescription:"Notify at 25%, 50%, 75%",printerOffline:"Printer Offline",printerError:"Printer Error",filamentLow:"Low Filament",maintenanceDue:"Maintenance Due",maintenanceDueDescription:"Notify when maintenance is needed"},smartPlug:{title:"Smart Plugs",add:"Add Smart Plug",edit:"Edit Smart Plug",name:"Name",ipAddress:"IP Address",linkedPrinter:"Linked Printer",autoOn:"Auto Power On",autoOnDescription:"Turn on when print starts",autoOff:"Auto Power Off",autoOffDescription:"Turn off after print completes",offDelay:"Off Delay",offDelayMinutes:"Minutes after print",offDelayTemp:"When nozzle below temperature",currentState:"Current State",turnOn:"Turn On",turnOff:"Turn Off"},filamentTracking:"Filament Tracking",filamentTrackingDesc:"Choose how to track your filament spools. You can use the built-in inventory or connect an external Spoolman server.",trackingModeBuiltIn:"Built-in Inventory",trackingModeBuiltInDesc:"RFID auto-matching and usage tracking included",trackingModeSpoolmanDesc:"External filament management server",builtInFeatureRfid:"Automatically detects Bambu Lab RFID spools in AMS",builtInFeatureUsage:"Tracks filament consumption per print",builtInFeatureCatalog:"Manage spools, colors, and K-factor profiles",builtInFeatureThirdParty:"Third-party spools can be assigned to inventory spools",amsSyncButton:"Sync Weights from AMS",amsSyncTitle:"Sync Spool Weights from AMS",amsSyncMessage:"This will overwrite all inventory spool weights with the current AMS remain% values from connected printers. Use this to recover from corrupted weight data. Printers must be online.",amsSyncing:"Syncing...",amsSyncSuccess:"{{synced}} spool(s) synced, {{skipped}} skipped",amsSyncError:"Failed to sync weights from AMS",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL of your Spoolman server (e.g., http://localhost:7912)",spoolmanConnected:"Connected",spoolmanDisconnected:"Disconnected",status:"Status",connect:"Connect",disconnect:"Disconnect",howSyncWorks:"How Sync Works",syncInfoRfidOnly:"Only official Bambu Lab spools with RFID are synced",syncInfoAutoCreate:"New spools are auto-created in Spoolman on first sync",syncInfoThirdPartySkipped:"Non-Bambu Lab spools (third-party, refilled) are skipped",linkingExistingSpools:"Linking Existing Spools",linkingExistingSpoolsDesc:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".',syncMode:"Sync Mode",syncModeAuto:"Automatic",syncModeManual:"Manual Only",syncModeAutoDesc:"AMS data syncs automatically when changes are detected",syncModeManualDesc:"Only sync when manually triggered",syncAmsData:"Sync AMS Data",syncAmsDataDesc:"Manually sync printer AMS data to Spoolman",allPrinters:"All Printers",noDefaultPrinter:"No default (ask each time)",sidebarOrder:"Sidebar order",saveThumbnails:"Save thumbnails",captureFinishPhoto:"Capture finish photo",noPrintersConfigured:"No printers configured",archiveMode:{always:"Always create archive entry",never:"Never create archive entry",ask:"Ask each time"},checkForUpdatesLabel:"Check for updates",checkPrinterFirmware:"Check printer firmware",includeBetaUpdates:"Include beta versions",includeBetaUpdatesDesc:"Notify about beta and prerelease versions when checking for updates",enableRetry:"Enable retry",homeAssistantDescription:"Control smart plugs via Home Assistant",environmentManagedLabel:"(Environment Managed)",autoEnabledViaEnv:"Automatically enabled via environment variables",urlFromEnvReadOnly:"Value set by HA_URL environment variable (read-only)",tokenFromEnvReadOnly:"Value set by HA_TOKEN environment variable (read-only)",mqttConnectedTo:"Connected to",prometheusDescription:"Expose printer data in Prometheus format",noSmartPlugsTitle:"No smart plugs configured",noSmartPlugsDescription:"Add a Tasmota-based smart plug to track energy usage and automate power control.",noProvidersTitle:"No providers configured",noProvidersDescription:"Add a provider to receive alerts.",noTemplatesAvailable:"No templates available. Restart the backend to seed default templates.",apiPermissionView:"View printer status and queue",apiPermissionEdit:"Add and remove items from print queue",apiKeysEmptyTitle:"No API keys",apiKeysEmptyDescription:"Create an API key to integrate with external services.",noUsersFound:"No users found",noGroupsFound:"No groups found",noGroupsAvailable:"No groups available",passwordsDoNotMatch:"Passwords do not match",systemGroupWarning:"System group names cannot be changed",authDisabledTitle:"Authentication is Disabled",authDisabledFeature1:"Require login to access the system",authDisabledFeature2:"Create multiple users with group-based permissions",authDisabledFeature3:"Control access with 50+ granular permissions",userHasCreated:"This user has created:",userItemsQuestion:"What would you like to do with these items?",deleteUserConfirm:"Are you sure you want to delete this user?",actionCannotBeUndone:"This action cannot be undone.",addFirstSmartPlug:"Add Your First Smart Plug",providers:"Providers",log:"Log",testAll:"Test All",testResults:"Test Results",testPassedCount:"{{count}} passed",testFailedCount:"{{count}} failed",messageTemplates:"Message Templates",messageTemplatesDescription:"Customize notification messages for each event.",apiKeys:"API Keys",apiKeysDescription:"Create API keys for external integrations and webhooks.",createKey:"Create Key",apiKeyCreated:"API Key Created Successfully",apiKeyCopyWarning:"Copy this key now - it won't be shown again!",useInApiBrowser:"Use in API Browser",createNewApiKey:"Create New API Key",keyName:"Key Name",keyNamePlaceholder:"e.g., Home Assistant, OctoPrint",readStatus:"Read Status",readStatusDescription:"View printer status and queue",manageQueue:"Manage Queue",manageQueueDescription:"Add and remove items from print queue",controlPrinter:"Control Printer",controlPrinterDescription:"Pause, resume, and stop prints",unnamedKey:"Unnamed Key",lastUsed:"Last used",read:"Read",control:"Control",createFirstKey:"Create Your First Key",webhookEndpoints:"Webhook Endpoints",webhookApiKeyHint:"Use your API key in the X-API-Key header.",webhook:{getAllStatus:"Get all printer status",getSpecificStatus:"Get specific printer status",addToQueue:"Add to print queue",pausePrint:"Pause print",resumePrint:"Resume print",stopPrint:"Stop print"},apiBrowser:"API Browser",apiBrowserDescription:"Explore and test all available API endpoints.",apiKeyForTesting:"API Key for Testing",apiKeyPlaceholder:"Paste your API key here to test authenticated endpoints...",apiKeyHint:"This key will be sent as X-API-Key header with requests.",deleteApiKeyTitle:"Delete API Key",deleteApiKeyMessage:"Are you sure you want to delete this API key? Any integrations using this key will stop working.",deleteKey:"Delete Key",amsDisplayThresholds:"AMS Display Thresholds",amsThresholdsDescription:"Configure color thresholds for AMS humidity and temperature indicators.",humidity:"Humidity",goodGreen:"Good (green)",fairOrange:"Fair (orange)",aboveFairBad:"Above fair threshold shows as red (bad)",temperature:"Temperature",goodBlue:"Good (blue)",aboveFairHot:"Above fair threshold shows as red (hot)",historyRetention:"History Retention",keepSensorHistory:"Keep sensor history for",historyRetentionDescription:"Older humidity and temperature data will be automatically deleted",printModal:"Print Modal",expandCustomMapping:"Expand custom mapping by default",expandCustomMappingDescription:"When printing to multiple printers, show per-printer AMS mapping expanded",authentication:"Authentication",authEnabledDescription:"Your instance is secured with user authentication",authDisabledDescription:"Enable to require login and manage user access",authDisabledMessage:"Enable authentication to create user accounts, manage permissions, and secure your Bambuddy instance.",enableAuthentication:"Enable Authentication",currentUser:"Current User",changePassword:"Change Password",admin:"Admin",users:"Users",addUser:"Add User",groups:"Groups",addGroup:"Add Group",system:"System",noDescription:"No description",userCount:"{{count}} users",permissionCount:"{{count}} permissions",createUser:"Create User",username:"Username",enterUsername:"Enter username",password:"Password",enterPassword:"Enter password (min 6 characters)",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm password",viewReleaseOnGitHub:"View release on GitHub",turnAllPlugsOn:"Turn all plugs on",turnAllPlugsOff:"Turn all plugs off",clearNotificationLogs:"Clear Notification Logs",clearLogsMessage:"This will permanently delete all notification logs older than 30 days. This action cannot be undone.",clearLogs:"Clear Logs",resetUiPreferences:"Reset UI Preferences",resetUiPreferencesMessage:"This will reset all UI preferences to defaults: sidebar order, theme, dashboard layout, view modes, and sorting preferences. Your printers, archives, and server settings will NOT be affected. The page will reload after clearing.",resetPreferences:"Reset Preferences",deleteGroupTitle:"Delete Group",deleteGroupMessage:"Are you sure you want to delete this group? Users in this group will lose these permissions.",deleteGroup:"Delete Group",disableAuthenticationTitle:"Disable Authentication",disableAuthenticationMessage:"Are you sure you want to disable authentication? This will make your Bambuddy instance accessible without login. All users will remain in the database but authentication will be disabled.",disableAuthentication:"Disable Authentication",configureBambuddy:"Configure Bambuddy",systemDefault:"System Default",archiveSettings:"Archive Settings",newWindow:"New Window",embeddedOverlay:"Embedded Overlay",preferredSlicer:"Preferred Slicer",preferredSlicerDescription:"Choose which slicer application to open files with",externalCameras:"External Cameras",costTracking:"Cost Tracking",printsOnly:"Prints Only",totalConsumption:"Total Consumption",dataManagement:"Data Management",storageUsage:"Storage Usage",storageUsageDescription:"Breakdown of data usage by category",storageUsageTotal:"Total",storageUsageErrors:"Errors",storageUsageOtherBreakdown:"Other (includes static assets, scripts, and configuration files)",storageUsageSystem:"System",storageUsageData:"Data",storageUsageUnavailable:"Storage usage information unavailable",clearNotificationLogsDescription:"Delete notification logs older than 30 days",resetUiPreferencesDescription:"Reset sidebar order, theme, view modes, and layout preferences. Printers, archives, and settings are not affected.",enableHomeAssistant:"Enable Home Assistant",enableMqtt:"Enable MQTT",useTls:"Use TLS",enableMetricsEndpoint:"Enable Metrics Endpoint",availableMetrics:"Available Metrics",editUser:"Edit User",deleteUserTitle:"Delete User",groupName:"Group Name",leaveEmptyForAnonymous:"Leave empty for anonymous",leaveEmptyForNoAuth:"Leave empty for no authentication",enterNewPassword:"Enter new password",confirmNewPassword:"Confirm new password",enterGroupName:"Enter group name",enterDescriptionOptional:"Enter description (optional)",enterCurrentPassword:"Enter current password",enterNewPasswordMin6:"Enter new password (min 6 characters)",toast:{keyCopied:"Key copied to clipboard",copyFailed:"Failed to copy key",keyAddedToBrowser:"Key added to API Browser",clearLogsFailed:"Failed to clear logs",uiPreferencesReset:"UI preferences reset. Refreshing...",authDisabled:"Authentication disabled successfully",authDisableFailed:"Failed to disable authentication",apiKeyCreated:"API key created",apiKeyDeleted:"API key deleted",userCreated:"User created successfully",userUpdated:"User updated successfully",userDeleted:"User deleted successfully",groupCreated:"Group created successfully",groupUpdated:"Group updated successfully",groupDeleted:"Group deleted successfully",fillRequiredFields:"Please fill in all required fields",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters",enterGroupName:"Please enter a group name",settingsSaved:"Settings saved",cameraSettingsSaved:"Camera settings saved",enterCameraUrl:"Please enter a camera URL",passwordChanged:"Password changed successfully",connectionFailed:"Connection failed",testFailed:"Test failed",cameraConnected:"Camera connected{{resolution}}"},testConnection:"Test Connection",catalog:{spoolCatalog:"Spool Catalog",spoolCatalogDescription:"Empty spool weights by brand/type. Used for automatic weight lookup when adding spools.",searchCatalog:"Search catalog...",addNewEntry:"Add New Entry",namePlaceholder:"Name (e.g., Bambu Lab - Plastic)",weight:"Weight",type:"Type",default:"Default",custom:"Custom",noMatch:"No entries match your search",empty:"No entries in catalog",deleteEntry:"Delete Entry",deleteConfirm:'Are you sure you want to delete "{{name}}"?',resetCatalog:"Reset Catalog",resetConfirm:"Reset catalog to defaults? This will remove all custom entries.",loadFailed:"Failed to load spool catalog",nameWeightRequired:"Name and weight are required",entryAdded:"Entry added",addFailed:"Failed to add entry",entryUpdated:"Entry updated",updateFailed:"Failed to update entry",entryDeleted:"Entry deleted",deleteFailed:"Failed to delete entry",resetSuccess:"Catalog reset to defaults",resetFailed:"Failed to reset catalog",exported:"Exported {{count}} entries",imported:"Imported {{added}} entries ({{skipped}} skipped)",importFailed:"Failed to import: invalid JSON format",exportTooltip:"Export catalog to JSON",importTooltip:"Import catalog from JSON",resetTooltip:"Reset to defaults"},colorCatalog:{title:"Color Catalog",description:"Filament colors by manufacturer/material. Used for automatic color lookup when adding spools.",searchColors:"Search colors...",allManufacturers:"All manufacturers",addNewColor:"Add New Color",manufacturer:"Manufacturer",colorName:"Color Name",hex:"Hex",materialOptional:"Material (optional)",showing:"Showing {{filtered}} of {{total}} colors",noMatch:"No colors match your search",empty:"No colors in catalog",deleteColor:"Delete Color",deleteConfirm:'Are you sure you want to delete "{{name}}"?',resetCatalog:"Reset Color Catalog",resetConfirm:"Reset catalog to defaults? This will remove all custom colors.",sync:"Sync",starting:"Starting...",syncTooltip:"Sync from FilamentColors.xyz (2000+ colors, may take a minute)",loadFailed:"Failed to load color catalog",fieldsRequired:"Manufacturer, color name, and hex color are required",colorAdded:"Color added",addFailed:"Failed to add color",colorUpdated:"Color updated",updateFailed:"Failed to update color",colorDeleted:"Color deleted",deleteFailed:"Failed to delete color",resetSuccess:"Color catalog reset to defaults",resetFailed:"Failed to reset catalog",syncUpToDate:"Already up to date ({{count}} colors checked)",syncComplete:"Added {{added}} new colors ({{skipped}} already existed)",syncError:"Sync error",syncFailed:"Failed to sync from FilamentColors.xyz",exported:"Exported {{count}} colors",imported:"Imported {{added}} colors ({{skipped}} skipped)",importFailed:"Failed to import: invalid JSON format"}},notification:{printStarted:{title:"Print Started",body:"{{printer}}: {{filename}} has started printing"},printCompleted:{title:"Print Completed",body:"{{printer}}: {{filename}} completed successfully"},printFailed:{title:"Print Failed",body:"{{printer}}: {{filename}} has failed"},printStopped:{title:"Print Stopped",body:"{{printer}}: {{filename}} was stopped"},printProgress:{title:"Print Progress",body:"{{printer}}: {{filename}} is {{percent}}% complete"},printerOffline:{title:"Printer Offline",body:"{{printer}} is offline"},printerError:{title:"Printer Error",body:"{{printer}}: {{error}}"},filamentLow:{title:"Low Filament",body:"{{printer}}: Filament is running low"},maintenanceDue:{title:"Maintenance Due",body:"{{printer}}: {{items}} need attention"}},errors:{generic:"Something went wrong",networkError:"Network error. Please check your connection.",notFound:"Not found",unauthorized:"Unauthorized",serverError:"Server error",validationError:"Please check your input",printerConnectionFailed:"Failed to connect to printer",saveFailed:"Failed to save changes",deleteFailed:"Failed to delete",loadFailed:"Failed to load data"},hmsErrors:{title:"Errors - {{name}}",noErrors:"No errors",viewOnWiki:"View on Bambu Lab Wiki",clearInstructions:"Clear errors on the printer to dismiss them here.",clearErrors:"Clear Errors",clearSuccess:"HMS errors cleared",clearFailed:"Failed to clear HMS errors"},mqttDebug:{title:"MQTT Debug Log",searchPlaceholder:"Search topic or payload...",noMessages:"No messages logged yet",startLoggingHint:'Click "Start Logging" to begin capturing MQTT messages',noMessagesMatch:"No messages match your filter",adjustFilterHint:"Try adjusting your search or filter criteria",incoming:"Incoming",outgoing:"Outgoing",loggingStopped:"Logging stopped",loggingActive:"Logging active - messages will auto-refresh",startLogging:"Start Logging",stopLogging:"Stop Logging",clearLog:"Clear Log",topic:"Topic",timestamp:"Timestamp",direction:"Direction",all:"All"},printerFiles:{title:"File Manager",storageUsed:"Used:",storageFree:"Free:",filterPlaceholder:"Filter files...",deleteButton:"Delete",deleteFiles:"Delete {{count}} Files",deleteFileConfirm:'Delete "{{name}}"? This cannot be undone.',deleteFilesConfirm:"Delete {{count}} selected files? This cannot be undone.",noFiles:"No files on printer",loadingFiles:"Loading files...",failedToLoad:"Failed to load files",toast:{filesDeleted:"Deleted {{count}} file(s)",deleteFailed:"Delete failed: {{error}}"}},confirm:{delete:"Are you sure you want to delete this?",unsavedChanges:"You have unsaved changes. Are you sure you want to leave?",clearQueue:"Are you sure you want to clear the queue?"},login:{title:"Bambuddy Login",subtitle:"Sign in to your account",username:"Username",usernamePlaceholder:"Enter your username",usernameOrEmail:"Username or Email",usernameOrEmailPlaceholder:"Username or @ Email",password:"Password",passwordPlaceholder:"Enter your password",signIn:"Sign in",signingIn:"Logging in...",forgotPassword:"Forgot your password?",loginSuccess:"Logged in successfully",loginFailed:"Login failed",enterCredentials:"Please enter username and password",forgotPasswordTitle:"Forgot Password",forgotPasswordMessage:"If you've forgotten your password, please contact your system administrator to reset it.",forgotPasswordEmailMessage:"Enter your email address and we'll send you a new password.",emailAddress:"Email Address",emailPlaceholder:"your.email@example.com",cancel:"Cancel",sending:"Sending...",sendResetEmail:"Send Reset Email",howToReset:"How to reset your password:",resetStep1:"Contact your Bambuddy administrator",resetStep2:"Ask them to reset your password in User Management",resetStep3:"They can set a new temporary password for you",resetStep4:"Log in with the new password and change it in Settings",gotIt:"Got it"},setup:{title:"Bambuddy Setup",subtitle:"Configure authentication for your Bambuddy instance",enableAuth:"Enable Authentication",adminAccount:"Admin Account",adminAccountDesc:"If admin users already exist, authentication will be enabled using the existing admin accounts. Leave the fields below empty to use existing admins, or enter new credentials to create a new admin user.",adminUsername:"Admin Username",adminPassword:"Admin Password",optionalIfAdminExists:"(optional if admin users exist)",adminUsernamePlaceholder:"Enter admin username (optional)",adminPasswordPlaceholder:"Enter admin password (optional)",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm admin password",settingUp:"Setting up...",completeSetup:"Complete Setup",toast:{authEnabledAdminCreated:"Authentication enabled and admin user created",authEnabledExistingAdmins:"Authentication enabled using existing admin users",setupCompleted:"Setup completed",enterBothCredentials:"Please enter both admin username and password, or leave both empty to use existing admin users",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters"}},changePassword:{title:"Change Password",currentPassword:"Current Password",currentPasswordPlaceholder:"Enter current password",newPassword:"New Password",newPasswordPlaceholder:"Enter new password (min 6 characters)",confirmPassword:"Confirm New Password",confirmPasswordPlaceholder:"Confirm new password",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters",changing:"Changing...",success:"Password changed successfully",failed:"Failed to change password"},plateAlert:{title:"Print Paused!",message:"Objects detected on build plate. The print has been automatically paused. Please clear the plate and resume the print.",understand:"I Understand"},camera:{title:"Camera View",invalidPrinterId:"Invalid printer ID",live:"Live",snapshot:"Snapshot",restartStream:"Restart stream",refreshSnapshot:"Refresh snapshot",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",connectingToCamera:"Connecting to camera...",capturingSnapshot:"Capturing snapshot...",connectionLost:"Connection lost",connectionFailed:"Camera connection failed",reconnecting:"Reconnecting in {{countdown}}s... (attempt {{attempt}}/{{max}})",reconnectNow:"Reconnect now",cameraUnavailable:"Camera unavailable",cameraUnavailableDesc:"Make sure the printer is powered on and connected.",noCamera:"No camera available",retry:"Retry",cameraStream:"Camera stream",zoomOut:"Zoom out",zoomIn:"Zoom in",resetZoom:"Reset zoom",recording:"Recording",startRecording:"Start Recording",stopRecording:"Stop Recording",chamberLight:"Toggle chamber light"},groups:{title:"Group Management",subtitle:"Manage permission groups for access control",backToSettings:"Back to Settings",createGroup:"Create Group",noPermission:"You do not have permission to access this page.",system:"System",noDescription:"No description",usersCount:"{{count}} users",permissionsCount:"{{count}} permissions",edit:"Edit",delete:"Delete",toast:{created:"Group created successfully",updated:"Group updated successfully",deleted:"Group deleted successfully",enterGroupName:"Please enter a group name"},modal:{editGroup:"Edit Group",createGroup:"Create Group",cancel:"Cancel",saving:"Saving...",creating:"Creating...",saveChanges:"Save Changes"},form:{groupName:"Group Name",groupNamePlaceholder:"Enter group name",systemGroupWarning:"System group names cannot be changed",description:"Description",descriptionPlaceholder:"Enter description (optional)",permissions:"Permissions ({{count}} selected)"},deleteModal:{title:"Delete Group",message:"Are you sure you want to delete this group? Users in this group will lose these permissions.",confirm:"Delete Group"},editor:{title:"Edit Group",createTitle:"Create Group",search:"Search permissions...",selectAll:"Select All",clearAll:"Clear All",permissionsSelected:"{{count}} selected",noResults:"No permissions match your search"}},users:{title:"User Management",subtitle:"Manage users and their access to your Bambuddy instance",backToSettings:"Back to Settings",createUser:"Create User",noPermission:"You do not have permission to access this page.",admin:"Admin",noGroups:"No groups",active:"Active",inactive:"Inactive",edit:"Edit",delete:"Delete",system:"System",noGroupsAvailable:"No groups available",table:{username:"Username",groups:"Groups",status:"Status",actions:"Actions"},toast:{created:"User created successfully",updated:"User updated successfully",deleted:"User deleted successfully",fillRequired:"Please fill in all required fields",passwordsDoNotMatch:"Passwords do not match",passwordTooShort:"Password must be at least 6 characters"},modal:{createUser:"Create User",editUser:"Edit User",cancel:"Cancel",creating:"Creating...",saving:"Saving...",saveChanges:"Save Changes",advancedAuthSubtitle:"with Advanced Authentication"},form:{username:"Username",usernamePlaceholder:"Enter username",email:"Email",emailPlaceholder:"user@example.com",password:"Password",passwordPlaceholder:"Enter password",confirmPassword:"Confirm Password",confirmPasswordPlaceholder:"Confirm password",newPasswordPlaceholder:"Enter new password",confirmNewPasswordPlaceholder:"Confirm new password",leaveBlankToKeep:"leave blank to keep current",groups:"Groups",optional:"optional",autoGeneratedPassword:"A secure password will be automatically generated and emailed to the user.",passwordManagedByAdvancedAuth:'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.',resetPassword:"Reset Password",resettingPassword:"Resetting Password..."},deleteModal:{title:"Delete User",message:"Are you sure you want to delete this user? This action cannot be undone.",confirm:"Delete User"}},streamOverlay:{title:"Stream Overlay",invalidPrinterId:"Invalid printer ID",cameraStream:"Camera stream",progress:"Progress",eta:"ETA",printerIdle:"Printer is idle",printerOffline:"Printer offline",status:{printing:"Printing",paused:"Paused",finished:"Finished",failed:"Failed",idle:"Idle",unknown:"Unknown"}},profiles:{title:"Profiles",subtitle:"Manage your slicer presets and pressure advance calibrations",tabs:{cloud:"Cloud Profiles",local:"Local Profiles",kprofiles:"K-Profiles"},localProfiles:{title:"Local Profiles",subtitle:"Import and manage slicer presets from OrcaSlicer",import:"Import Profiles",importDesc:"Drop .bbscfg, .bbsflmt, .orca_filament, .zip, or .json files here",importing:"Importing...",search:"Search local presets...",noPresets:"No local presets yet",badge:"Local",edit:"Edit",delete:"Delete",cancel:"Cancel",deleteConfirmTitle:"Delete Preset",deleteConfirm:"Are you sure you want to delete this preset? This cannot be undone.",source:"Source",inheritsFrom:"Inherits",filamentType:"Type",vendor:"Vendor",compatiblePrinters:"Printers",nozzleTemp:"Nozzle Temp",cost:"Cost",density:"Density",pressureAdvance:"Pressure Advance",filament:"Filament",process:"Process",printer:"Printer",toast:{importSuccess:"{{count}} preset(s) imported",importSkipped:"{{count}} preset(s) skipped (duplicates)",importError:"{{count}} error(s) during import",deleted:"Preset deleted",updated:"Preset updated"}},connectedAs:"Connected as",logout:"Logout",noLogoutPermission:"You do not have permission to logout",failedToLoad:"Failed to load profiles",retry:"Retry",time:{justNow:"Just now",minsAgo:"{{count}}m ago",hoursAgo:"{{count}}h ago",daysAgo:"{{count}}d ago"},toast:{loggedOut:"Logged out"},login:{title:"Connect to Bambu Cloud",subtitle:"Sync your slicer presets across devices",email:"Email",password:"Password",region:"Region",regionGlobal:"Global",regionChina:"China",verificationCode:"Verification Code",totpCode:"Authenticator Code",checkEmail:"Check your email ({{email}}) for a 6-digit code",enterTotpHint:"Enter the 6-digit code from your authenticator app",accessToken:"Access Token",accessTokenHint:"Paste your Bambu Lab access token (from Bambu Studio)",back:"Back",loginButton:"Login",verifyButton:"Verify",setTokenButton:"Set Token",useToken:"Use access token instead",useEmail:"Login with email instead",toast:{loggedIn:"Logged in successfully",codeSent:"Verification code sent to your email",enterTotp:"Enter code from your authenticator app",tokenSet:"Token set successfully"}},presets:{myPreset:"My preset (editable)",duplicate:"Duplicate",editable:"Editable",failedToLoadDetails:"Failed to load preset details",deleteConfirm:"Delete this preset?",deleteWarning:'This will permanently delete "{{name}}" from Bambu Cloud. This cannot be undone.',noDuplicatePermission:"You do not have permission to duplicate presets",noEditPermission:"You do not have permission to edit presets",noDeletePermission:"You do not have permission to delete presets",types:{filament:"Filament preset",printer:"Printer preset",process:"Process preset"},toast:{deleted:"Preset deleted",created:"Preset created",updated:"Preset updated",duplicated:"Preset duplicated",fieldAdded:'Field "{{key}}" added',exported:"Preset exported"},baseLabel:"Base: {{name}}",currentLabel:"Current: {{name}}",newPreset:"New Preset",editPreset:"Edit Preset",duplicatePreset:"Duplicate Preset",createNewPreset:"Create New Preset",customizeSettings:"Customize settings for your new preset",compareWithBase:"Compare with base preset",compare:"Compare",basePreset:"Base Preset",selectBasePreset:"Select base preset...",presetName:"Preset Name",myCustomPreset:"My custom preset",inheritsFrom:"Inherits from",dropJsonToImport:"Drop JSON to import",tabs:{common:"Common",allFields:"All Fields"},availableFields:"Available Fields",searchFieldsPlaceholder:"Search fields...",noMatchingFields:"No matching fields",allFieldsAdded:"All fields added",addCustomField:"Add custom field",yourOverrides:"Your Overrides",noOverridesYet:"No overrides yet",clickFieldsToAdd:"Click fields on the left to add them",saveAsTemplate:"Save as template",jsonTip:"Tip: Drag & drop a .json file anywhere on this modal to import settings"},cloudView:{searchPlaceholder:"Search presets...",templates:"Templates",refresh:"Refresh",newPreset:"New Preset",clearFilters:"Clear filters",compareMode:"Compare Mode",selectAnotherPreset:"Select another {{type}} preset",clickTwoPresets:"Click two presets of the same type to compare",selectFirst:"1. Select first",selectSecond:"2. Select second",compareNow:"Compare Now",lastSynced:"Last synced:",showingCount:"Showing {{showing}} of {{total}} presets",noPresetsFound:"No presets found",columns:{filament:"Filament",process:"Process",printer:"Printer"},noFilamentPresets:"No filament presets",noProcessPresets:"No process presets",noPrinterPresets:"No printer presets",filters:{type:"Type",owner:"Owner",printer:"Printer",nozzle:"Nozzle",filament:"Filament",layer:"Layer",all:"All",myPresets:"My Presets",builtIn:"Built-in",process:"Process"},noTemplatesPermission:"You do not have permission to manage templates",noRefreshPermission:"You do not have permission to refresh profiles",noCreatePermission:"You do not have permission to create presets"},templates:{title:"Quick Templates",noTemplates:"No templates yet",createFirst:"Create templates from the preset editor",typeFilter:"Type:",deleteTitle:"Delete Template",deleteWarning:"This action cannot be undone",deleteConfirm:'Are you sure you want to delete "{{name}}"?',namePlaceholder:"Template name",descriptionPlaceholder:"Description",settingsJson:"Settings (JSON)",fieldsCount:"{{count}} fields",shownInModals:"Shown in modals",hiddenInModals:"Hidden in modals",apply:"Apply",toast:{deleted:"Template deleted",updated:"Template updated",created:"Template created",applied:"Template applied"}}},support:{debugLoggingActive:"Debug logging is active",manageLogs:"Manage",collectItem7:"Printer connectivity and firmware versions",collectItem8:"Integration status (Spoolman, MQTT, HA)",collectItem9:"Network interfaces (subnets only)",collectItem10:"Python package versions",collectItem11:"Database health checks",collectItem12:"Docker environment details"},fileManager:{title:"File Manager",subtitle:"Organize and manage your print files",uploadFiles:"Upload Files",newFolder:"New Folder",folderName:"Folder Name",folderNamePlaceholder:"e.g., Functional Parts",renameFile:"Rename File",renameFolder:"Rename Folder",moveFiles:"Move {{count}} File(s)",rootNoFolder:"Root (No Folder)",current:"current",linkFolder:"Link Folder",linkFolderDescription:'Link "{{name}}" to a project or archive for quick access.',project:"Project",archive:"Archive",noProjectsFound:"No projects found",noArchivesFound:"No archives found",unlink:"Unlink",link:"Link",dragDropFiles:"Drag & drop files here",dropFilesHere:"Drop files here",orClickToBrowse:"or click to browse",allFileTypesSupported:"All file types supported. ZIP files will be extracted.",zipFilesDetected:"ZIP files detected",zipExtractOptions:"ZIP files will be extracted. Choose how to handle folder structure:",preserveZipStructure:"Preserve folder structure from ZIP",createFolderFromZip:"Create folder from ZIP filename",stlThumbnailGeneration:"STL thumbnail generation",zipMayContainStl:"ZIP files may contain STL files. Thumbnails can be generated during extraction.",thumbnailsCanBeGenerated:"Thumbnails can be generated for STL files. Large models may take longer to process.",generateThumbnailsForStl:"Generate thumbnails for STL files",threemfDetected:"3MF files detected",threemfExtractionInfo:"Printer model, material, color, and print settings will be automatically extracted from 3MF files.",willBeExtracted:"Will be extracted",filesExtracted:"{{count}} files extracted",uploadComplete:"Upload complete: {{succeeded}} succeeded",uploadFailed:"{{count}} failed",uploading:"Uploading...",changeLink:"Change Link...",linkTo:"Link to...",linkToProjectOrArchive:"Link to project or archive",addToQueue:"Add to Queue",schedulePrint:"Schedule",generateThumbnail:"Generate Thumbnail",generateThumbnails:"Generate Thumbnails",generateThumbnailsForMissing:"Generate thumbnails for STL files missing them",gridView:"Grid view",listView:"List view",lowDiskSpaceWarning:"Low disk space warning",lowDiskSpaceDetails:"Only {{free}} free of {{total}} total. Threshold is set to {{threshold}} GB in settings.",files:"Files",folders:"Folders",size:"Size",free:"Free",allFiles:"All Files",wrap:"Wrap",enableTextWrapping:"Enable text wrapping",disableTextWrapping:"Disable text wrapping",dragToResizeTooltip:"Drag to resize, double-click to reset",searchFiles:"Search files...",allTypes:"All types",prints:"Prints",ascending:"Ascending",descending:"Descending",resultsCount:"{{showing}} of {{total}} files",selectAll:"Select All",deselectAll:"Deselect All",selected:"{{count}} selected",adding:"Adding...",loadingFiles:"Loading files...",folderIsEmpty:"Folder is empty",noFilesYet:"No files yet",folderEmptyDescription:"Upload files or move files into this folder to get started.",noFilesDescription:"Upload files to start organizing your print-related files.",noMatchingFiles:"No matching files",noMatchingFilesDescription:"No files match your current search or filter criteria.",clearFilters:"Clear filters",printedCount:"Printed {{count}}x",uploadedBy:"Uploaded By",deleteFolder:"Delete Folder",deleteFile:"Delete File",deleteFilesCount:"Delete {{count}} Files",deleteFolderConfirm:"Are you sure you want to delete this folder? All files inside will also be deleted.",deleteFileConfirm:"Are you sure you want to delete this file?",deleteFilesConfirm:"Are you sure you want to delete {{count}} selected files? This action cannot be undone.",deleting:"Deleting...",noPermissionRenameFolder:"You do not have permission to rename folders",noPermissionLinkFolder:"You do not have permission to link folders",noPermissionDeleteFolder:"You do not have permission to delete folders",noPermissionPrint:"You do not have permission to print",noPermissionAddToQueue:"You do not have permission to add to queue",noPermissionDownload:"You do not have permission to download files",noPermissionRenameFile:"You do not have permission to rename this file",noPermissionGenerateThumbnail:"You do not have permission to generate thumbnails",noPermissionDeleteFile:"You do not have permission to delete this file",noPermissionCreateFolder:"You do not have permission to create folders",noPermissionUpload:"You do not have permission to upload files",noPermissionMoveFiles:"You do not have permission to move files",noPermissionDeleteFiles:"You do not have permission to delete files",toast:{folderCreated:"Folder created",folderDeleted:"Folder deleted",fileDeleted:"File deleted",filesDeleted:"Deleted {{count}} files",filesMoved:"Files moved",folderLinked:"Folder linked",folderUnlinked:"Folder unlinked",addedToQueue:"Added {{count}} file(s) to queue",addedToQueuePartial:"Added {{added}} file(s), {{failed}} failed",failedToAddToQueue:"Failed to add files: {{error}}",fileRenamed:"File renamed",folderRenamed:"Folder renamed",thumbnailsGenerated:"Generated {{count}} thumbnail(s)",thumbnailsGeneratedPartial:"Generated {{succeeded}} thumbnail(s), {{failed}} failed",noStlMissingThumbnails:"No STL files missing thumbnails",failedToGenerateThumbnails:"Failed to generate thumbnails: {{error}}",thumbnailGenerated:"Thumbnail generated",failedToGenerateThumbnail:"Failed to generate thumbnail: {{error}}"}},projects:{title:"Projects",subtitle:"Organize and track your 3D printing projects",newProject:"New Project",editProject:"Edit Project",deleteProject:"Delete Project",projectName:"Project Name",description:"Description",noProjects:"No projects yet",noProjectsFiltered:"No {{status}} projects",noProjectsFilteredHelp:"You don't have any {{status}} projects. Projects will appear here when their status changes.",createFirst:"Create your first project to start organizing related prints, tracking progress, and managing your builds.",createFirstButton:"Create Your First Project",create:"Create",files:"Files",prints:"Prints",plates:"plates",parts:"parts",lastModified:"Last Modified",deleteConfirm:"Are you sure you want to delete this project? Archives and queue items will be unlinked but not deleted.",addFiles:"Add Files",removeFile:"Remove File",viewDetails:"View Details",namePlaceholder:"e.g., Voron 2.4 Build",descriptionPlaceholder:"Optional description...",color:"Color",targetPlates:"Target Plates",targetPlatesPlaceholder:"e.g., 25",targetPlatesHelp:"Number of print jobs",targetParts:"Target Parts",targetPartsPlaceholder:"e.g., 150",targetPartsHelp:"Total objects needed",tagsLabel:"Tags (comma-separated)",tagsPlaceholder:"e.g., voron, functional, gift",dueDate:"Due Date",priority:"Priority",priorityLow:"Low",priorityNormal:"Normal",priorityHigh:"High",priorityUrgent:"Urgent",statusActive:"Active",statusCompleted:"Completed",statusArchived:"Archived",done:"Done",completed:"completed",failed:"failed",inQueue:"in queue",noPrintsYet:"No prints yet",printJobs:"Print jobs (plates)",partsPrinted:"Parts printed",failedParts:"Failed parts",import:"Import",export:"Export",importProject:"Import project",exportAll:"Export all projects",loading:"Loading projects...",noEditPermission:"You do not have permission to edit projects",noDeletePermission:"You do not have permission to delete projects",noCreatePermission:"You do not have permission to create projects",noImportPermission:"You do not have permission to import projects",noExportPermission:"You do not have permission to export projects",toast:{created:"Project created",updated:"Project updated",deleted:"Project deleted",imported:"Project imported",multipleImported:"{{count}} projects imported",importFailed:"Import failed",exported:"Projects exported (metadata only)"}},projectDetail:{notFound:"Project not found",backToProjects:"Back to Projects",export:"Export",exportProject:"Export project",noExportPermission:"You do not have permission to export projects",noEditPermission:"You do not have permission to edit projects",partOf:"Part of:",priorityLabel:"Priority:",noPrints:"No prints in this project yet",status:{active:"Active",completed:"Completed",archived:"Archived"},priority:{low:"Low",normal:"Normal",high:"High",urgent:"Urgent"},dueDate:{overdue:"Overdue",today:"Due today",daysLeft:"{{count}} days left"},progress:{platesProgress:"Plates Progress",partsProgress:"Parts Progress",printJobs:"print jobs",parts:"parts",percentComplete:"{{percent}}% complete",remaining:"{{count}} remaining"},stats:{printJobs:"Print Jobs",total:"total",failed:"{{count}} failed",partsPrinted:"{{count}} parts printed",printTime:"Print Time",filamentUsed:"Filament Used"},cost:{title:"Cost Tracking",filamentCost:"Filament Cost",energy:"Energy",budget:"Budget",remaining:"Remaining"},subProjects:{title:"Sub-projects ({{count}})"},notes:{title:"Notes",noEditPermission:"You do not have permission to edit notes",placeholder:"Add notes about this project...",empty:"No notes yet. Click Edit to add notes."},files:{title:"Files",linkFolders:"Link folders from the File Manager",forQuickAccess:"to this project for quick access.",fileCount:"{{count}} file(s)",empty:"No folders linked. Go to File Manager and link a folder to this project."},bom:{title:"Bill of Materials",acquired:"{{completed}}/{{total}} acquired",showAll:"Show all",hideDone:"Hide done",addPart:"Add Part",noAddPermission:"You do not have permission to add parts",partNamePlaceholder:"Part name (e.g., M3x8 screws)",partName:"Part name",qty:"Qty",price:"Price ({{currency}})",sourcingUrlPlaceholder:"Sourcing URL (optional)",remarksPlaceholder:"Remarks (optional)",deletePart:"Delete Part",deleteConfirm:'Are you sure you want to delete "{{name}}"?',noUpdatePermission:"You do not have permission to update parts",noEditPermission:"You do not have permission to edit parts",noDeletePermission:"You do not have permission to delete parts",totalCost:"Total cost:",empty:"No parts in the bill of materials. Add hardware, electronics, or other components to track what needs to be sourced."},timeline:{title:"Activity Timeline",empty:"No activity yet."},template:{saveAsTemplate:"Save as Template",noCreatePermission:"You do not have permission to create templates"},queue:{title:"Queue",viewAll:"View all",printing:"{{count}} printing",queued:"{{count}} queued"},prints:{title:"Prints ({{count}})"},toast:{projectUpdated:"Project updated",partAdded:"Part added",partRemoved:"Part removed",exportFailed:"Export failed",projectExported:"Project exported",templateCreated:"Template created"}},system:{title:"System Information",version:"Version",uptime:"Uptime",cpuUsage:"CPU Usage",memoryUsage:"Memory Usage",diskUsage:"Disk Usage",networkInfo:"Network Info",logs:"Logs",debugMode:"Debug Mode",enableDebug:"Enable Debug Logging",disableDebug:"Disable Debug Logging",downloadLogs:"Download Logs",clearLogs:"Clear Logs",dockerInfo:"Docker Info",containerName:"Container Name",imageName:"Image Name",platform:"Platform",architecture:"Architecture"},library:{title:"Filament Library",addFilament:"Add Filament",editFilament:"Edit Filament",deleteFilament:"Delete Filament",vendor:"Vendor",material:"Material",color:"Color",kFactor:"K Factor",temperature:"Temperature",noFilaments:"No filaments in library",deleteConfirm:"Are you sure you want to delete this filament?",importFromPrinter:"Import from Printer",exportToFile:"Export to File"},spoolman:{title:"Spoolman Integration",enabled:"Spoolman Enabled",url:"Spoolman URL",connected:"Connected",disconnected:"Not Connected",testConnection:"Test Connection",sync:"Sync",syncing:"Syncing...",lastSync:"Last Sync",linkToSpoolman:"Link to Spoolman",openInSpoolman:"Open in Spoolman",unlinkSpool:"Unlink Spool",selectSpool:"Select Spool",noUnlinkedSpools:"No unlinked spools available",linkSuccess:"Spool linked to Spoolman successfully",linkFailed:"Failed to link spool",spoolId:"Spool ID",fillSourceLabel:"(Spoolman)",weight:"Weight",remaining:"Remaining",disableWeightSync:"Disable AMS Estimated Weight Sync",disableWeightSyncDesc:"Don't update remaining capacity from AMS estimates. Use this if you prefer Spoolman's usage tracking over AMS percentage-based estimates. New spools will still use the AMS estimate as their initial weight.",reportPartialUsage:"Report Partial Usage for Failed Prints",reportPartialUsageDesc:"When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress."},inventory:{title:"Spool Inventory",addSpool:"Add Spool",editSpool:"Edit Spool",material:"Material",selectMaterial:"Select material...",subtype:"Subtype",brand:"Brand",searchBrand:"Search brand...",useCustomBrand:'Use "{{brand}}"',useCustomMaterial:"Use custom material: {{material}}",colorName:"Color Name",colorNamePlaceholder:"Jade White, Fire Red...",color:"Color",hexColor:"Hex Color",pickColor:"Pick custom color",labelWeight:"Label Weight",coreWeight:"Empty Spool Weight",searchSpoolWeight:"Search spool weight...",weightUsed:"Used",currentWeight:"Remaining Weight",measuredWeight:"Measured Weight",costPerKg:"Cost per kg",measuredWeightError:"Measured weight must be between {{min}}g and {{max}}g.",slicerFilament:"Slicer Filament",slicerFilamentName:"Slicer Preset Name",slicerPreset:"Slicer Preset",searchPresets:"Search filament presets...",selectedPreset:"Selected",noPresetsFound:"No presets found",tempOverrides:"Temperature Overrides",note:"Note",notePlaceholder:"Any additional notes about this spool...",archive:"Archive",restore:"Restore",noSpools:"No spools yet. Add your first spool to get started.",noManualSpools:"No manually added spools available. Add a spool to your inventory first.",kProfiles:"K-Profiles",addKProfile:"Add K-Profile",assignSpool:"Assign Spool",unassignSpool:"Unassign",assignSuccess:"Spool assigned and AMS slot configured",assignFailed:"Failed to assign spool",selectSpool:"Select a spool to assign to this slot",assigned:"Assigned",assigning:"Assigning...",searchSpools:"Search spools...",allMaterials:"All Materials",filterByBrand:"Filter by brand...",showArchived:"Show archived",quickAdd:"Quick Add (Stock)",quantity:"Quantity",stock:"Stock",configured:"Configured",spoolsCreated:"{{count}} spools created",spoolCreated:"Spool created",spoolUpdated:"Spool updated",spoolDeleted:"Spool deleted",spoolArchived:"Spool archived",spoolRestored:"Spool restored",deleteConfirm:"Are you sure you want to delete this spool? This cannot be undone.",archiveConfirm:"Are you sure you want to archive this spool?",advancedSettings:"Advanced Settings",filamentInfoTab:"Filament Info",paProfileTab:"PA Profile",filamentInfo:"Filament",additional:"Additional",loadingPresets:"Loading cloud presets...",cloudConnected:"Cloud connected",cloudNotConnected:"Cloud not connected (using defaults)",recentColors:"Recent",searchColors:"Search colors...",searchResults:"Search results",allColors:"All colors",commonColors:"Common colors",showLess:"Show less",showAll:"Show all",noColorsFound:"No colors match your search",noResults:"No matches found",selectMaterialFirst:"Please select a material first in the Filament Info tab.",noPrintersConfigured:"No printers configured. Add printers to use PA profiles.",matchingFilter:"Matching",anyBrand:"Any brand",anyVariant:"Any variant",autoSelect:"Auto-select",matches:"matches",match:"match",noMatches:"No matches",connected:"Connected",offline:"Offline",printerOffline:"Printer is offline. Connect to view calibration profiles.",noKProfilesMatch:"No K-profiles match the selected filament.",leftNozzle:"Left Nozzle",rightNozzle:"Right Nozzle",profilesSelected:"calibration profile(s) selected",totalInventory:"Total Inventory",totalConsumed:"Total Consumed",byMaterial:"By Material",inPrinter:"In Printer",lowStock:"Low Stock",sinceTracking:"Since tracking started",loadedInAms:"Loaded in AMS/Ext",remaining:"Remaining",lowStockThreshold:"<20% remaining",search:"Search spools...",showing:"Showing",to:"to",of:"of",show:"Show",spools:"spools",spool:"spool",page:"Page",noSpoolsMatch:"No results found",noSpoolsMatchDesc:"Try adjusting your search or filters to find what you're looking for.",active:"Active",archived:"Archived",all:"All",used:"Used",new:"New",clearFilters:"Clear filters",table:"Table",cards:"Cards",net:"Net",groupSimilar:"Group",groupedSpools:"{{count}} identical spools",groupedRows:"rows",columns:"Columns",configureColumns:"Configure Columns",configureColumnsDesc:"Drag to reorder columns or use arrows. Toggle visibility with the eye icon.",visible:"visible",reset:"Reset",cancel:"Cancel",applyChanges:"Apply Changes",moveUp:"Move up",moveDown:"Move down",hideColumn:"Hide column",showColumn:"Show column",linkToSpool:"Link to Spool",tagLinked:"Tag linked to spool",tagLinkFailed:"Failed to link tag",tagAlreadyLinked:"Tag already linked to another spool",unknownTag:"Unknown RFID tag detected",usageHistory:"Usage History",noUsageHistory:"No usage recorded yet",printName:"Print Name",weightConsumed:"Weight Consumed",clearHistory:"Clear",historyCleared:"Usage history cleared",fillSourceLabel:"(Inv)"},timelapse:{title:"Timelapse",create:"Create Timelapse",download:"Download",delete:"Delete",preview:"Preview",frameRate:"Frame Rate",quality:"Quality",processing:"Processing...",noTimelapses:"No timelapses available"},ams:{title:"AMS",slot:"Slot",empty:"Empty",emptySlot:"Empty slot",unknown:"Unknown",humidity:"Humidity",temperature:"Temperature",filamentType:"Filament Type",filamentColor:"Color",remaining:"Remaining",history:"AMS History",noHistory:"No history available",configureSlot:"Configure Slot",externalSpool:"External Spool",profile:"Profile",kFactor:"K Factor",fill:"Fill",configure:"Configure",used:"used",remainingUnit:"remaining"},printModal:{title:"Start Print",selectPrinter:"Select Printer",selectPlate:"Select Plate",filamentMapping:"Filament Mapping",totalCost:"Total cost:",printSettings:"Print Settings",bedLeveling:"Bed Leveling",flowCalibration:"Flow Calibration",vibrationCalibration:"Vibration Calibration",layerInspection:"First Layer Inspection",timelapse:"Timelapse",startPrint:"Start Print",addToQueue:"Add to Queue",cancel:"Cancel",noPrintersAvailable:"No printers available",printerBusy:"Printer is busy",printerOffline:"Printer is offline",sameTypeDifferentColor:"Same type, different color",filamentTypeNotLoaded:"Filament type not loaded",openCalendar:"Open calendar",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Left nozzle",rightNozzleTooltip:"Right nozzle",filamentOverride:"Filament Override",filamentOverrideHint:"Optionally override filaments for model-based assignment. The scheduler will match against your selected filaments instead of the original 3MF values.",originalFilament:"Original",overrideWith:"Override with",resetToOriginal:"Reset to original"},backup:{title:"Backup & Restore",createBackup:"Create Backup",restoreBackup:"Restore Backup",restoreDescription:"Replace all data from a backup file",downloadBackup:"Download Backup",uploadBackup:"Upload Backup",lastBackup:"Last Backup",autoBackup:"Auto Backup",backupNow:"Backup Now",restoreWarning:"Warning: Restoring a backup will overwrite all current data.",includeArchives:"Include Archives",includeSettings:"Include Settings",includeProfiles:"Include Profiles",backupSuccess:"Backup created successfully",restoreSuccess:"Backup restored successfully",backupFailed:"Backup failed",restoreFailed:"Restore failed",restoreNote:"Virtual Printer will be stopped during restore"},tags:{title:"Tags",addTag:"Add Tag",editTag:"Edit Tag",deleteTag:"Delete Tag",tagName:"Tag Name",tagColor:"Tag Color",noTags:"No tags",deleteConfirm:"Are you sure you want to delete this tag?",manageTags:"Manage Tags"},uploadModal:{title:"Upload 3MF Files",dragDrop:"Drag & drop .3mf files here",or:"or",browseFiles:"Browse Files",extractionInfo:"The printer model will be automatically extracted from the 3MF file metadata.",uploaded:"uploaded",failed:"failed",uploading:"Uploading...",upload:"Upload",uploadFailed:"Upload failed"},editArchive:{title:"Edit Archive",name:"Name",namePlaceholder:"Print name",printer:"Printer",noPrinter:"No printer",project:"Project",noProject:"No project",itemsPrinted:"Items Printed",itemsPrintedHelp:"Number of items produced in this print job",notes:"Notes",notesPlaceholder:"Add notes about this print...",externalLink:"External Link",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link to Printables, Thingiverse, or other source",tags:"Tags",tagsPlaceholder:"Add tags...",addMoreTags:"Add more tags...",matchingTags:'Matching "{{query}}"',existingTags:"Existing tags",clickToAdd:"(click to add)",status:"Status",failureReason:"Failure Reason",selectReason:"Select reason...",photos:"Photos of Printed Result",photosHelp:"Click + to add photos of your printed result",printResult:"Print result",saving:"Saving...",failureReasons:{adhesionFailure:"Adhesion failure",spaghettiDetached:"Spaghetti / Detached",layerShift:"Layer shift",cloggedNozzle:"Clogged nozzle",filamentRunout:"Filament runout",warping:"Warping",stringing:"Stringing",underExtrusion:"Under-extrusion",powerFailure:"Power failure",userCancelled:"User cancelled",other:"Other"},statuses:{completed:"Completed",failed:"Failed",aborted:"Cancelled",printing:"Printing"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"No Printers Configured",addPrinterInSettings:"Add a printer in Settings to manage K-profiles",noActivePrinters:"No Active Printers",enablePrinterConnection:"Enable a printer connection to view its K-profiles",loadingProfiles:"Loading K-Profiles...",printerOffline:"Printer Offline",printerOfflineDesc:"The selected printer is not connected. Power it on to view K-profiles.",noMatchingProfiles:"No Matching Profiles",noMatchingProfilesDesc:"No profiles match your search criteria",noKProfiles:"No K-Profiles",noKProfilesDesc:"No pressure advance profiles found for {{diameter}}mm nozzle",createFirstProfile:"Create First Profile",printer:"Printer",nozzle:"Nozzle",refresh:"Refresh",addProfile:"Add Profile",export:"Export",import:"Import",select:"Select",selectAll:"Select All",delete:"Delete",searchPlaceholder:"Search by name or filament...",allExtruders:"All Extruders",leftOnly:"Left Only",rightOnly:"Right Only",allFlow:"All Flow",hfOnly:"HF Only",sOnly:"S Only",sortName:"Sort: Name",sortKValue:"Sort: K-Value",sortFilament:"Sort: Filament",leftExtruder:"Left Extruder",rightExtruder:"Right Extruder",modal:{addTitle:"Add K-Profile",editTitle:"Edit K-Profile",profileName:"Profile Name",profileNamePlaceholder:"My PLA Profile",kValue:"K-Value",kValuePlaceholder:"0.020",kValueHelp:"Typical range: 0.01 - 0.06 for PLA, 0.02 - 0.10 for PETG",filament:"Filament",selectFilament:"Select filament...",noFilamentsHelp:"No filaments found. Create a K-profile in Bambu Studio first.",flowType:"Flow Type",highFlow:"High Flow",standard:"Standard",nozzleSize:"Nozzle Size",extruder:"Extruder",extruders:"Extruders",left:"Left",right:"Right",notes:"Notes (stored locally)",notesPlaceholder:"Add notes about this profile...",notesHelp:"Notes are saved in Bambuddy, not on the printer",syncing:"Syncing with printer...",savingExtruder:"Saving to extruder {{current}}/{{total}}...",pleaseWait:"Please wait"},deleteConfirm:{title:"Delete Profile",cannotUndo:"This cannot be undone",message:'Are you sure you want to delete "{{name}}" from the printer?'},bulkDelete:{title:"Delete Profiles",cannotUndo:"This cannot be undone",message:"Are you sure you want to delete {{count}} selected profiles from the printer?"},toast:{profileSaved:"K-profile saved",profilesSaved:"K-profile saved to {{count}} extruders",selectAtLeastOneExtruder:"Please select at least one extruder",profileDeleted:"K-profile deleted",profilesDeleted:"Deleted {{count}} profiles",exportedProfiles:"Exported {{count}} profiles",importedProfiles:"Imported {{count}} of {{total}} profiles",noProfilesToExport:"No profiles to export",invalidFileFormat:"Invalid file format",failedToParseImport:"Failed to parse import file",failedToSaveBatch:"Failed to save K-profiles",noteSaved:"Note saved",failedToSaveNote:"Failed to save note"},permission:{noRead:"You do not have permission to refresh profiles",noCreate:"You do not have permission to add profiles",noUpdate:"You do not have permission to update K-profiles",noDelete:"You do not have permission to delete K-profiles",noExport:"You do not have permission to export profiles",noImport:"You do not have permission to import profiles"}},virtualPrinter:{title:"Virtual Printer",running:"Running",stopped:"Stopped",description:{default:"Enable a virtual printer that appears in Bambu Studio and OrcaSlicer. Files sent to this printer will be archived directly without printing.",proxy:"Enable a proxy that relays slicer traffic to a real printer, allowing remote printing over any network."},enable:{title:"Enable Virtual Printer",visibleInSlicer:'Visible as "Bambuddy" in slicer discovery',proxyingTo:"Proxying to {{name}}",notActive:"Not active"},model:{title:"Printer Model",description:"Select which printer model to emulate.",restartWarning:"Changing the model will restart the virtual printer"},accessCode:{title:"Access Code",isSet:"Access code is set",notSet:"No access code set - required to enable",placeholder:"Enter 8-char code",placeholderChange:"Enter new code to change",hint:"Must be exactly 8 characters. Used by slicers to authenticate.",charCount:"({{count}}/8)"},targetPrinter:{title:"Target Printer",configured:"Proxy target configured",notConfigured:"No target printer selected - required for proxy mode",placeholder:"Select a printer...",hint:"Select the printer to proxy slicer traffic to. The printer must be in LAN mode.",noPrinters:"No printers configured. Add a printer first to use proxy mode."},remoteInterface:{title:"Network Interface Override",configured:"Interface override active",optional:"Optional - use if auto-detected IP is wrong (e.g. multiple NICs, Docker, VPN)",placeholder:"Auto-detect (default)...",hint:"Override the IP address advertised via SSDP and used in the TLS certificate. Useful when Bambuddy has multiple network interfaces."},mode:{title:"Mode",archive:"Archive",archiveDesc:"Archive files immediately",review:"Review",reviewDesc:"Review before archiving",queue:"Queue",queueDesc:"Archive and add to queue",proxy:"Proxy",proxyDesc:"Relay to real printer"},setupRequired:{title:"Setup Required",description:"The virtual printer feature requires additional system configuration before it will work. This includes port forwarding, firewall rules, and platform-specific settings.",readGuide:"Read the setup guide before enabling"},howItWorks:{title:"How it works",step1:"On the same LAN, virtual printers appear in your slicer (Bambu Studio / OrcaSlicer) automatically via discovery. From other networks, add them manually by IP address and access code.",step2:'In Archive, Review, and Queue modes, use the "Send" button in your slicer to upload 3MF files to Bambuddy. The slicer will show "Print success" — the file is stored, not printed.',step3:"In Proxy mode, the virtual printer relays all traffic to a real printer — prints start immediately as if connected directly."},status:{title:"Status Details",printerName:"Printer Name",model:"Model",serialNumber:"Serial Number",mode:"Mode",pendingFiles:"Pending Files",targetPrinter:"Target Printer",ftpPort:"FTP Port",mqttPort:"MQTT Port",ftpConnections:"FTP Connections",mqttConnections:"MQTT Connections"},toast:{updated:"Virtual printer settings updated",failedToUpdate:"Failed to update settings",accessCodeRequired:"Please set an access code first",targetPrinterRequired:"Please select a target printer first",bindIpRequired:"Please set a bind IP first",accessCodeEmpty:"Access code cannot be empty",accessCodeLength:"Access code must be exactly 8 characters",created:"Virtual printer created",failedToCreate:"Failed to create virtual printer",deleted:"Virtual printer deleted",failedToDelete:"Failed to delete virtual printer"},list:{title:"Virtual Printers",add:"Add",addFirst:"Add Virtual Printer",empty:"No virtual printers configured. Add one to get started."},bindIp:{title:"Bind Interface",placeholder:"Select interface...",hint:"Network interface for this virtual printer to bind to. Must be unique per printer."},proxy:{accessCodeHint:"In proxy mode, use your target printer's access code in the slicer. The connection is forwarded transparently to the real printer."},addDialog:{title:"Add Virtual Printer",name:"Name",hint:"You can configure access code, target printer, and other settings after creating.",create:"Create"},deleteConfirm:{title:"Delete Virtual Printer",message:'Are you sure you want to delete "{{name}}"? This will stop all services for this printer.'}},modelViewer:{openInSlicer:"Open in Slicer",tabs:{model:"3D Model",gcode:"G-code Preview"},notAvailable:"not available",notSliced:"not sliced",plates:"Plates",allPlates:"All Plates",plateNumber:"Plate {{number}}",plateCount:"{{count}} plate",plateCount_other:"{{count}} plates",objectCount:"{{count}} object",objectCount_other:"{{count}} objects",filamentCount:"{{count}} filament",filamentCount_other:"{{count}} filaments",eta:"ETA {{minutes}} min",noPreview:"No preview available for this file",pagination:{pageOf:"Page {{current}} of {{total}}",prev:"Prev",next:"Next"},errors:{failedToLoad:"Failed to load file",noMeshes:"No meshes found in 3MF file",unsupportedFormat:"Unsupported file format"}},maintenanceDescriptions:{lubricateCarbonRods:"Apply lubricant to carbon rods for smooth motion",lubricateRails:"Apply lubricant to linear rails for smooth motion",cleanNozzle:"Clean hotend and nozzle to prevent clogs",checkBelts:"Verify belt tension for accurate prints",cleanBuildPlate:"Clean build plate for better adhesion",checkExtruder:"Inspect extruder gears for wear",checkCooling:"Ensure cooling fans are working properly",generalInspection:"General printer inspection",cleanCarbonRods:"Clean carbon rods to reduce friction",cleanLinearRails:"Wipe linear rails to remove dust and debris",checkPtfeTube:"Inspect PTFE tube for wear or damage",replaceHepaFilter:"Replace HEPA filter for air quality",replaceCarbonFilter:"Replace activated carbon filter",lubricateLeftNozzleRail:"Lubricate left nozzle rail (H2 series)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Open plug admin page",deleteSmartPlug:"Delete Smart Plug",turnOnSmartPlug:"Turn On Smart Plug",turnOffSmartPlug:"Turn Off Smart Plug",turnOn:"Turn On",turnOff:"Turn Off",addSmartPlug:{scanningNetwork:"Scanning network...",chooseEntity:"Choose an entity...",connectionFailed:"Connection failed",searchEntities:"Search entities...",searchPowerSensors:"Search power sensors...",searchEnergySensors:"Search energy sensors...",placeholders:{plugName:"Living Room Plug",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Same as power topic, or different"}}},richTextEditor:{bold:"Bold",italic:"Italic",underline:"Underline",bulletList:"Bullet List",numberedList:"Numbered List",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",addLink:"Add Link",removeLink:"Remove Link"},externalLinks:{noLinksConfigured:"No external links configured",deleteLink:"Delete Link",removeCustomIcon:"Remove custom icon",openInNewTab:"Open in new tab",placeholders:{linkName:"My Link"}},keyboardShortcuts:{title:"Keyboard Shortcuts",navigation:"Navigation",archivesSection:"Archives",kProfilesSection:"K-Profiles",generalSection:"General",shortcuts:{goToPrinters:"Go to Printers",goToArchives:"Go to Archives",goToQueue:"Go to Queue",goToStats:"Go to Statistics",goToProfiles:"Go to Cloud Profiles",goToSettings:"Go to Settings",focusSearch:"Focus search",openUploadModal:"Open upload modal",clearSelection:"Clear selection / blur input",contextMenu:"Context menu on cards",refreshProfiles:"Refresh profiles",newProfile:"New profile",exitSelectionMode:"Exit selection mode",showHelp:"Show this help"},footer:"Press Esc or click outside to close"},notificationLog:{title:"Notification Log",events:{printStarted:"Print Started",printComplete:"Print Complete",printFailed:"Print Failed",printStopped:"Print Stopped",progress:"Progress",printerOffline:"Printer Offline",printerError:"Printer Error",lowFilament:"Low Filament",maintenanceDue:"Maintenance Due",test:"Test"},timeAgo:{justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago"}},restoreBackup:{title:"Restore Backup",restoring:"Restoring...",restoreComplete:"Restore Complete",restoreFailed:"Restore Failed",importSettings:"Import settings from a backup file",pleaseWait:"Please wait while your data is being restored",clickToSelect:"Click to select backup file (.json or .zip)",howDuplicateHandling:"How duplicate handling works:",categories:{printers:"Printers",smartPlugs:"Smart Plugs",notificationProviders:"Notification Providers",filaments:"Filaments",archives:"Archives",pendingUploads:"Pending Uploads",settingsTemplates:"Settings & Templates"},matchingInfo:{printers:"matched by serial number",smartPlugs:"matched by IP address",notificationProviders:"matched by name",filaments:"matched by name + type + brand",archives:"matched by content hash",pendingUploads:"matched by filename",settingsTemplates:"always overwritten"},replaceExisting:"Replace existing data",keepExisting:"Keep existing data",replaceDescription:"Overwrite items that already exist with backup data",keepDescription:"Only restore items that don't already exist",caution:"Caution:",cautionText:"Overwriting will replace your current configurations with backup data. Printer access codes are never overwritten for security.",itemsRestored:"Items Restored",itemsSkipped:"Items Skipped",restored:"Restored",skipped:"Skipped (already exist)",filesLabel:"Files (3MF, thumbnails, etc.)",newApiKeysGenerated:"New API Keys Generated",newApiKeysWarning:"These keys are only shown once. Copy them now!",processingBackup:"Processing backup file...",noDataFound:"No data was found to restore in the backup file.",failedToRestore:"Failed to restore backup. Please check the file format."},backupExport:{title:"Export Backup",selectData:"Select data to include",selectAll:"Select All",selectNone:"Select None",categoryDescriptions:{settings:"Language, theme, update preferences",notifications:"ntfy, Pushover, Discord, etc.",templates:"Custom message templates",smartPlugs:"Tasmota plug configurations",externalLinks:"Sidebar links to external services",printers:"Printer info (access codes excluded)",plateDetection:"Empty plate reference images",filaments:"Filament types and costs",maintenance:"Custom maintenance schedules",archives:"All print data + files (3MF, thumbnails, photos)",projects:"Projects, BOM items, and attachments",pendingUploads:"Virtual printer uploads awaiting review",apiKeys:"Webhook API keys (new keys generated on import)"},requiresPrinters:"Requires Printers to be selected",zipFileWarning:"ZIP file will be created.",zipFileDescription:"Includes all 3MF files, thumbnails, timelapses, and photos. This may take a while and result in a large file.",includeAccessCodes:"Include Access Codes",includeAccessCodesDescription:"For transferring to another machine",includeAccessCodesWarning:"Access codes will be included in plain text. Keep this backup file secure!",categoriesSelected:"{{selectedCount}} categories selected"},pendingUploads:{placeholders:{notes:"Add notes about this print..."},discardUpload:"Discard Upload",archiveAllUploads:"Archive All Uploads",discardAllUploads:"Discard All Uploads",archive:"Archive",timeAgo:{justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago",daysAgo:"{{days}}d ago"}},apiBrowser:{placeholders:{requestBody:"JSON request body...",searchEndpoints:"Search endpoints..."}},configureAmsSlot:{title:"Configure AMS Slot",slotConfigured:"Slot Configured!",configuringSlot:"Configuring slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Search presets...",colorPlaceholder:"Color name or hex (e.g., brown, FF8800)",clearCustomColor:"Clear custom color",noCloudPresets:"No cloud presets. Login to Bambu Cloud to sync.",noPresetsAvailable:"No presets available. Login to Bambu Cloud or import local profiles.",noMatchingPresets:"No matching presets found.",custom:"Custom",builtin:"Built-in",settingsSentToPrinter:"Settings sent to printer",filamentProfile:"Filament Profile",kProfileLabel:"K Profile (Pressure Advance)",filteringFor:"Filtering for: {{material}}",noKProfile:"No K profile (use default 0.020)",noMatchingKProfiles:"No matching K profiles found. Default K=0.020 will be used.",selectFilamentFirst:"Select a filament profile first",kFromCalibration:"K={{value}} from printer calibration",customColorLabel:"Custom Color (optional)",presetColors:"{{name}} colors:",showLessColors:"Show less colors",showMoreColors:"Show more colors",clear:"Clear",hexLabel:"Hex: #{{hex}}",resetting:"Resetting...",resetSlot:"Reset Slot",cancel:"Cancel",configuring:"Configuring...",configureSlot:"Configure Slot"},githubBackup:{title:"GitHub Backup",history:"History",downloadBackup:"Download Backup",restoreBackup:"Restore Backup",noBackupsYet:"No backups yet"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Search tags...",renameTag:"Rename tag",deleteTag:"Delete tag"},notificationTemplates:{placeholders:{title:"Notification title...",body:"Notification body..."}},batchTag:{placeholders:{newTag:"Enter new tag..."}},photoGallery:{deletePhoto:"Delete Photo"},filamentHoverCard:{copySpoolUuid:"Copy spool UUID"},kProfilesView:{hasNote:"Has note",copyProfile:"Copy profile"},layout:{openMenu:"Open menu",noPermissionSystemInfo:"You do not have permission to view system information"},dashboard:{dragToReorder:"Drag to reorder",hideWidget:"Hide widget"},notificationProviderCard:{deleteNotificationProvider:"Delete Notification Provider"},fileManagerModal:{closeFileManager:"Close file manager",sortFiles:"Sort files",goToParentFolder:"Go to parent folder",threeView:"3D View"},embeddedCameraViewer:{refreshStream:"Refresh stream",close:"Close",zoomOut:"Zoom out",resetZoom:"Reset zoom",zoomIn:"Zoom in",dragToResize:"Drag to resize"},timelapseViewer:{skipBack5s:"Skip back 5s",skipForward5s:"Skip forward 5s"},notificationProviders:{descriptions:{email:"SMTP email notifications",telegram:"Notifications via Telegram bot",discord:"Send to Discord channel via webhook",ntfy:"Free, self-hostable push notifications",pushover:"Simple, reliable push notifications",callmebot:"Free WhatsApp notifications via CallMeBot",webhook:"Generic HTTP POST to any URL"}},logViewer:{searchPlaceholder:"Search message or logger name...",noLogEntries:"No log entries found"},switchbarPopover:{noSwitchesInSwitchbar:"No switches in switchbar"},projectPageModal:{placeholders:{title:"Title",designer:"Designer",license:"License",description:"Enter description...",profileTitle:"Profile Title",profileDescription:"Profile description..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"Waiting",justNow:"Just now",now:"Now",minsAgo:"{{count}}m ago",inMins:"in {{count}}m",hoursAgo:"{{count}}h ago",inHours:"in {{count}}h",daysAgo:"{{count}}d ago",inDays:"in {{count}}d"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventory",printers:"Printers",settings:"Settings"},status:{nfcReady:"Ready",nfcOff:"Off",offline:"Device Offline"},dashboard:{idleMessage:"Place spool on scale and scan NFC tag"},weight:{noReading:"No reading",stable:"Stable",measuring:"Measuring",tare:"Tare",calibrate:"Calibrate",tareQueued:"Tare command sent"},spool:{remaining:"Remaining"},tag:{unknownTitle:"Unknown Tag",linkExisting:"Link to Existing Spool",createNew:"Create New Spool"},actions:{assignAms:"Assign AMS",updateWeight:"Update Weight",editSpool:"Edit Spool",viewHistory:"View History",weightUpdated:"Spool weight updated"},ams:{noData:"No AMS data available"},inventory:{search:"Search spools...",empty:"No spools found"},printers:{noPrinters:"No printers configured"},settings:{scaleCalibration:"Scale Calibration",currentWeight:"Current weight",tareOffset:"Tare offset",knownWeight:"Known weight",calibrated:"Calibration updated",tareQueued:"Tare command queued",nfcReader:"NFC Reader",nfcConnected:"Connected",nfcDisconnected:"Disconnected",deviceInfo:"Device Info",deviceId:"Device ID",uptime:"Uptime",firmware:"Firmware"}}},cce={nav:{printers:"Drucker",archives:"Archiv",queue:"Warteschlange",stats:"Statistiken",profiles:"Profile",maintenance:"Wartung",projects:"Projekte",inventory:"Filament",files:"Dateimanager",settings:"Einstellungen",system:"System",collapseSidebar:"Seitenleiste einklappen",expandSidebar:"Seitenleiste ausklappen",update:"Update",updateAvailable:"Update verfügbar: v{{version}}",updateAvailableBanner:"Version {{version}} ist verfügbar!",viewUpdate:"Update anzeigen",viewOnGithub:"Auf GitHub ansehen",keyboardShortcuts:"Tastaturkürzel (?)",switchToLight:"Zum hellen Modus wechseln",switchToDark:"Zum dunklen Modus wechseln",smartSwitches:"Smart Switches",logout:"Abmelden"},common:{save:"Speichern",saving:"Speichern...",cancel:"Abbrechen",delete:"Löschen",edit:"Bearbeiten",add:"Hinzufügen",close:"Schließen",confirm:"Bestätigen",loading:"Lädt...",error:"Fehler",success:"Erfolg",warning:"Warnung",enabled:"Aktiviert",disabled:"Deaktiviert",yes:"Ja",no:"Nein",on:"An",off:"Aus",all:"Alle",none:"Keine",search:"Suchen",filter:"Filtern",sort:"Sortieren",refresh:"Aktualisieren",download:"Herunterladen",upload:"Hochladen",actions:"Aktionen",status:"Status",name:"Name",description:"Beschreibung",date:"Datum",time:"Zeit",hours:"Stunden",minutes:"Minuten",seconds:"Sekunden",days:"Tage",enable:"Aktivieren",disable:"Deaktivieren",permissions:"Berechtigungen",noPrinters:"Keine Drucker konfiguriert",noData:"Keine Daten verfügbar",linkNotFound:"Link nicht gefunden",required:"Erforderlich",optional:"Optional",dismiss:"Schließen",apply:"Anwenden",reset:"Zurücksetzen",export:"Exportieren",import:"Importieren",clear:"Leeren",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",noChange:"— Keine Änderung —",unchanged:"Unverändert",unassigned:"Nicht zugewiesen",unknown:"Unbekannt",unknownError:"Unbekannter Fehler",today:"Heute",tomorrow:"Morgen",asap:"Sofort",overdue:"Überfällig",now:"Jetzt",collapse:"Einklappen",expand:"Ausklappen",viewArchive:"Archiv anzeigen",viewInFileManager:"Im Dateimanager anzeigen",addedBy:"Hinzugefügt von {{username}}",prints:"Drucke",more:"+{{count}} weitere",ascending:"Aufsteigend",descending:"Absteigend",printer:"Drucker",remove:"Entfernen",type:"Typ",print:"Drucken",rename:"Umbenennen",move:"Verschieben",create:"Erstellen",duplicate:"Duplizieren",left:"Links",right:"Rechts"},printers:{title:"Drucker",addPrinter:"Drucker hinzufügen",editPrinter:"Drucker bearbeiten",deletePrinter:"Drucker löschen",printerName:"Druckername",serialNumber:"Seriennummer",ipAddress:"IP-Adresse / Hostname",accessCode:"Zugangscode",model:"Modell",nozzleCount:"Düsenanzahl",autoArchive:"Automatische Archivierung",status:{available:"Verfügbar",idle:"Bereit",printing:"Druckt",paused:"Pausiert",offline:"Offline",error:"Fehler",finished:"Fertig",unknown:"Unbekannt"},temperatures:{nozzle:"Düse",bed:"Druckbett",chamber:"Kammer"},progress:"{{percent}}% abgeschlossen",timeRemaining:"Noch {{time}}",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',maintenanceOk:"Wartung OK",maintenanceWarning:"{{count}} Warnung",maintenanceWarning_plural:"{{count}} Warnungen",maintenanceDue:"{{count}} fällig",maintenanceDue_plural:"{{count}} fällig",sort:{name:"Name",status:"Status",model:"Modell",location:"Standort",ascending:"Aufsteigend sortieren",descending:"Absteigend sortieren"},cardSize:{small:"Kleine Karten",medium:"Mittlere Karten",large:"Große Karten",extraLarge:"Extra große Karten"},hideOffline:"Offline ausblenden",nextAvailable:"Nächster verfügbar",powerOn:"Einschalten",offlinePrintersWithPlugs:"Offline-Drucker mit Smart-Plugs",noPrintersConfigured:"Noch keine Drucker konfiguriert",readyToPrint:"Druckbereit",external:"Extern",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Druckarchive löschen",noLabel:"Keine Bezeichnung",printPreview:"Druckvorschau",width:"Breite",height:"Höhe",noObjectsFound:"Keine Objekte gefunden",objectsLoadedOnPrintStart:"Objekte werden beim Druckstart geladen",willBeSkipped:"Wird übersprungen",name:"Name",serialCannotBeChanged:"Seriennummer kann nicht geändert werden",locationHelp:"Dient zur Gruppierung von Druckern und zum Filtern von Warteschlangenaufträgen",wifiSignal:{veryWeak:"Sehr schwach",weak:"Schwach",fair:"Ausreichend",good:"Gut",excellent:"Ausgezeichnet"},maintenanceUpToDate:"Alle Wartungen aktuell - Klicken zum Anzeigen",chamberLightOn:"Kammerbeleuchtung einschalten",chamberLightOff:"Kammerbeleuchtung ausschalten",browseFiles:"Druckerdateien durchsuchen",autoOffAfterPrint:"Automatisches Ausschalten nach Druck",autoOffExecuted:"Auto-off wurde ausgeführt - Drucker einschalten zum Zurücksetzen",hmsErrors:"HMS-Fehler",viewHmsErrors:"{{count}} HMS-Fehler anzeigen",resume:"Fortsetzen",pause:"Pausieren",stop:"Stoppen",camera:"Kamera",skipObject:"Objekt überspringen",reconnect:"Neu verbinden",mqttDebug:"MQTT-Debug",activeNozzle:"Aktiv: {{nozzle}} Düse",nozzleRack:"Düsenhalter",nozzleDocked:"Angedockt",nozzleMounted:"Montiert",nozzleActive:"Aktiv",nozzleIdle:"Inaktiv",nozzleDiameter:"Durchmesser",nozzleType:"Typ",nozzleStatus:"Status",nozzleFilament:"Filament",nozzleWear:"Verschleiß",nozzleMaxTemp:"Max Temp",nozzleSerial:"Seriennr.",nozzleHardenedSteel:"Gehärteter Stahl",nozzleStainlessSteel:"Edelstahl",nozzleTungstenCarbide:"Wolframkarbid",nozzleFlow:"Durchfluss",nozzleHighFlow:"High Flow",nozzleStandardFlow:"Standard",firmwareUpdate:"Firmware-Update",firmwareInstructions:"Gehen Sie auf dem Touchscreen des Druckers zu",firmwareNav:"Navigieren Sie zu",settings:"Einstellungen",firmware:"Firmware",discoverPrinters:"Drucker entdecken",searching:"Suche...",manualEntry:"Manuelle Eingabe",addFromCloud:"Aus Cloud hinzufügen",toast:{printerDeleted:"Drucker gelöscht",printerAdded:"Drucker hinzugefügt",printerUpdated:"Drucker aktualisiert",failedToDelete:"Drucker konnte nicht gelöscht werden",failedToAdd:"Drucker konnte nicht hinzugefügt werden",failedToUpdate:"Drucker konnte nicht aktualisiert werden",commandSent:"Befehl gesendet",failedToSendCommand:"Befehl konnte nicht gesendet werden",turnedOn:"{{name}} eingeschaltet",failedToPowerOn:"{{name}} konnte nicht eingeschaltet werden",scriptTriggered:"Skript ausgelöst",printStopped:"Druck gestoppt",printPaused:"Druck pausiert",printResumed:"Druck fortgesetzt",referenceDeleted:"Referenz gelöscht",detectionAreaSaved:"Erkennungsbereich gespeichert",failedToRunScript:"Skript konnte nicht ausgeführt werden",failedToStopPrint:"Druck konnte nicht gestoppt werden",failedToPausePrint:"Druck konnte nicht pausiert werden",failedToResumePrint:"Druck konnte nicht fortgesetzt werden",failedToControlChamberLight:"Kammerbeleuchtung konnte nicht gesteuert werden",failedToUpdateSetting:"Einstellung konnte nicht aktualisiert werden",failedToSkipObjects:"Objekte konnten nicht übersprungen werden",failedToRereadRfid:"RFID konnte nicht erneut gelesen werden",failedToCheckPlate:"Platte konnte nicht überprüft werden",failedToUpdateLabel:"Bezeichnung konnte nicht aktualisiert werden",failedToDeleteReference:"Referenz konnte nicht gelöscht werden",failedToSaveDetectionArea:"Erkennungsbereich konnte nicht gespeichert werden",plateCheckEnabled:"Plattenprüfung aktiviert",plateCheckDisabled:"Plattenprüfung deaktiviert",calibrationSaved:"Kalibrierung gespeichert!",calibrationFailed:"Kalibrierung fehlgeschlagen",rfidRereadInitiated:"RFID-Neueinlesen gestartet"},connection:{connected:"Verbunden",offline:"Offline"},queue:{inQueue:"{{count}} Druck in Warteschlange",inQueue_plural:"{{count}} Drucke in Warteschlange"},controls:"Steuerung",rfid:{reread:"RFID neu lesen"},permission:{noAdd:"Sie haben keine Berechtigung, Drucker hinzuzufügen",noEdit:"Sie haben keine Berechtigung, Drucker zu bearbeiten",noDelete:"Sie haben keine Berechtigung, Drucker zu löschen",noControl:"Sie haben keine Berechtigung, Drucker zu steuern",noFiles:"Sie haben keine Berechtigung, auf Druckerdateien zuzugreifen",noAmsRfid:"Sie haben keine Berechtigung, AMS-RFID erneut zu lesen",noSmartPlugControl:"Sie haben keine Berechtigung, Smart Plugs zu steuern"},modal:{addTitle:"Drucker hinzufügen",editTitle:"Drucker bearbeiten",myPrinter:"Mein Drucker",selectModel:"Modell auswählen...",locationGroup:"Standort / Gruppe (optional)",locationPlaceholder:"z.B. Werkstatt, Büro, Keller",autoArchiveLabel:"Abgeschlossene Drucke automatisch archivieren",fromPrinterSettings:"Aus Druckereinstellungen",modelOptional:"Modell (optional)",saveChanges:"Änderungen speichern"},skipObjects:{tooltip:"Objekte überspringen",onlyWhilePrinting:"Objekte überspringen (nur während des Drucks)",requiresMultiple:"Objekte überspringen (erfordert 2+ Objekte)",title:"Objekte überspringen",matchIdsInfo:"IDs mit Drucker-Display abgleichen",printerShowsIds:"Der Druckerbildschirm zeigt Objekt-IDs auf der Bauplatte",skipSelected:"Ausgewählte überspringen",skipping:"Überspringe...",noObjectsSelected:"Keine Objekte ausgewählt",selectObjectsToSkip:"Wählen Sie Objekte aus, die Sie vom aktuellen Druck überspringen möchten",skipped:"übersprungen",objectsSkipped:"Objekte übersprungen",activeCount:"{{count}} aktiv",waitForLayer:"Warten Sie auf Schicht 2+ zum Überspringen von Objekten (aktuell Schicht {{layer}})",skip:"Überspringen",confirmTitle:"Objekt überspringen?",confirmMessage:'Möchten Sie "{{name}}" wirklich überspringen? Dies kann nicht rückgängig gemacht werden.'},confirm:{deleteTitle:"Drucker löschen",deleteMessage:'Möchten Sie "{{name}}" wirklich löschen? Alle Verbindungseinstellungen werden entfernt.',deleteArchivesNote:"Der gesamte Druckverlauf für diesen Drucker wird dauerhaft gelöscht.",keepArchivesNote:"Der Druckverlauf wird beibehalten, aber nicht mehr mit diesem Drucker verknüpft.",stopTitle:"Druck stoppen",stopMessage:'Möchten Sie den aktuellen Druck auf "{{name}}" wirklich stoppen? Der Druckauftrag wird abgebrochen.',stopButton:"Druck stoppen",pauseTitle:"Druck pausieren",pauseMessage:'Möchten Sie den aktuellen Druck auf "{{name}}" wirklich pausieren?',pauseButton:"Druck pausieren",resumeTitle:"Druck fortsetzen",resumeMessage:'Möchten Sie den Druck auf "{{name}}" fortsetzen?',resumeButton:"Druck fortsetzen",powerOnTitle:"Drucker einschalten",powerOnMessage:'Möchten Sie die Stromversorgung für "{{name}}" wirklich EINSCHALTEN?',powerOnButton:"Einschalten",powerOffTitle:"Drucker ausschalten",powerOffMessage:'Möchten Sie die Stromversorgung für "{{name}}" wirklich AUSSCHALTEN?',powerOffWarning:'WARNUNG: "{{name}}" druckt gerade! Möchten Sie die Stromversorgung wirklich AUSSCHALTEN? Dies unterbricht den Druck und kann den Drucker beschädigen.',powerOffButton:"Ausschalten"},discovery:{title:"Drucker entdecken",searching:"Suche...",scanning:"Scanne...",scanProgress:"Scanne... {{scanned}}/{{total}}",foundPrinters:"{{count}} Drucker gefunden",noPrintersFound:"Keine Drucker gefunden",noPrintersFoundSubnet:"Keine Drucker im angegebenen Subnetz gefunden.",noPrintersFoundNetwork:"Keine Drucker im Netzwerk gefunden.",allConfigured:"Alle erkannten Drucker sind bereits konfiguriert.",alreadyAdded:"Bereits hinzugefügt",select:"Auswählen",manualEntry:"Manuelle Eingabe",addFromCloud:"Aus Cloud hinzufügen",subnetToScan:"Zu scannendes Subnetz",dockerNote:"Docker erkannt. Geben Sie das Subnetz Ihres Druckers in CIDR-Notation ein. Erfordert network_mode: host in docker-compose.yml.",scanSubnet:"Subnetz nach Druckern scannen",discoverNetwork:"Drucker im Netzwerk suchen",scanningSubnet:"Subnetz wird nach Bambu-Druckern gescannt...",scanningNetwork:"Netzwerk wird gescannt...",serialRequired:"Seriennummer erforderlich",unknown:"Unbekannt",failedToStart:"Erkennung konnte nicht gestartet werden"},filaments:"Filamente",openCameraOverlay:"Kamera-Overlay öffnen",openCameraWindow:"Kamera in neuem Fenster öffnen",firmwareUpdateAvailable:"Firmware-Update verfügbar: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Aktuell",firmwareUpdateButton:"Update",plateDetection:{noPermission:"Sie haben keine Berechtigung, Drucker zu aktualisieren",enabledClick:"Plattenprüfung aktiviert - Klicken zum Deaktivieren",disabledClick:"Plattenprüfung deaktiviert - Klicken zum Aktivieren",manageCalibration:"Platten-Erkennungskalibrierung verwalten",calibrationRequired:"Kalibrierung erforderlich",calibrationInstructions:"Bitte stellen Sie sicher, dass die Druckplatte <strong>vollständig leer</strong> ist, und klicken Sie dann auf Kalibrieren.",calibrationDescription:"Die Kalibrierung erfasst ein Referenzbild der leeren Platte. Zukünftige Prüfungen vergleichen mit dieser Referenz, um Objekte zu erkennen.",calibrationTip:"<strong>Tipp:</strong> Sie können bis zu 5 Kalibrierungen für verschiedene Platten speichern. Das System verwendet automatisch die beste Übereinstimmung bei der Prüfung.",plateEmpty:"Platte erscheint leer",objectsDetected:"Objekte auf Platte erkannt",confidence:"Konfidenz",difference:"Differenz",analysisPreview:"Analysevorschau:",analysisLegend:"Grüner Rahmen = Erkennungsbereich, Rote Überlagerung = Unterschiede zur Kalibrierung",savedReferences:"Gespeicherte Referenzen ({{count}}/{{max}})",deleteReference:"Referenz löschen",labelPlaceholder:"Bezeichnung...",clickToEdit:"{{label}} - Zum Bearbeiten klicken",clickToAddLabel:"Zum Hinzufügen einer Bezeichnung klicken"},fans:{partCooling:"Bauteilkühlung",auxiliary:"Hilfsventilator",chamber:"Kammerventilator"},clickToViewHmsErrors:"Klicken, um HMS-Fehler anzuzeigen",estimatedCompletion:"Geschätzte Fertigstellungszeit",slotOptions:"Slot-Optionen",firmwareModal:{title:"Firmware-Update",titleUpToDate:"Firmware-Info",currentVersion:"Aktuell:",latestVersion:"Neueste:",releaseNotes:"Versionshinweise",checkingPrereqs:"Prüfe Voraussetzungen...",sdCardReady:"SD-Karte bereit. Klicken Sie unten, um die Firmware hochzuladen.",uploadedSuccess:"Firmware auf SD-Karte hochgeladen!",applyInstructions:"So wenden Sie das Update auf Ihrem Drucker an:",step1:"Gehen Sie auf dem Touchscreen des Druckers zu <strong>Einstellungen</strong>",step2:"Navigieren Sie zu <strong>Firmware</strong>",step3:"Wählen Sie <strong>Update von SD-Karte</strong>",step4:"Das Update dauert 10-20 Minuten",done:"Fertig",starting:"Starte...",uploadFirmware:"Firmware hochladen",uploadFailed:"Upload fehlgeschlagen: {{error}}",uploadedToast:"Firmware hochgeladen! Starten Sie das Update vom Druckerbildschirm."},accessCodePlaceholder:"Leer lassen, um den aktuellen zu behalten",roi:{title:"Erkennungsbereich (ROI)",xStart:"X-Start",yStart:"Y-Start",width:"Breite",height:"Höhe",instruction:"Passen Sie den Erkennungsbereich an, um sich auf die Druckplatte zu konzentrieren. Der grüne Rahmen in der Vorschau zeigt den aktuellen Bereich."},developerModeWarning:"Der Entwickler-LAN-Modus ist nicht aktiviert auf: {{names}}. Einige Funktionen funktionieren möglicherweise nicht.",howToEnable:"Aktivieren"},archives:{title:"Druckarchiv",searchPlaceholder:"Archiv durchsuchen...",filterByPrinter:"Nach Drucker filtern",filterByStatus:"Nach Status filtern",sortBy:"Sortieren nach",sortNewest:"Neueste zuerst",sortOldest:"Älteste zuerst",sortName:"Name",sortDuration:"Dauer",sortLargest:"Größte zuerst",sortSmallest:"Kleinste zuerst",sortSize:"Größe",noArchives:"Keine Archive gefunden",noArchivesSearch:"Keine Archive entsprechen Ihrer Suche",noArchivesYet:"Noch keine Archive",loadingArchives:"Lade Archive...",releaseToUpload:"Loslassen zum Hochladen",showAll:"Alle anzeigen",showFavoritesOnly:"Nur Favoriten anzeigen",gridView:"Rasteransicht",listView:"Listenansicht",calendarView:"Kalenderansicht",logView:"Druckprotokoll",manageTags:"Tags verwalten",showFailedPrints:"Fehlgeschlagene Drucke anzeigen",hideFailedPrints:"Fehlgeschlagene Drucke ausblenden",printTime:"Druckzeit",filamentUsed:"Verbrauchtes Filament",cost:"Kosten",reprint:"Drucken",preview:"Vorschau",deleteArchive:"Archiv löschen",deleteConfirm:"Möchten Sie dieses Archiv wirklich löschen?",favorite:"Favorit",unfavorite:"Aus Favoriten entfernen",viewDetails:"Details anzeigen",status:{completed:"Abgeschlossen",failed:"Fehlgeschlagen",stopped:"Gestoppt"},toast:{source3mfAttached:"Quell-3MF angehängt: {{filename}}",failedUploadSource3mf:"Fehler beim Hochladen der Quell-3MF",source3mfRemoved:"Quell-3MF entfernt",failedRemoveSource3mf:"Fehler beim Entfernen der Quell-3MF",f3dAttached:"F3D angehängt: {{filename}}",failedUploadF3d:"Fehler beim Hochladen der F3D",f3dRemoved:"F3D entfernt",failedRemoveF3d:"Fehler beim Entfernen der F3D",timelapseAttached:"Zeitraffer angehängt: {{filename}}",timelapseAlreadyAttached:"Zeitraffer bereits angehängt",noMatchingTimelapse:"Kein passender Zeitraffer gefunden",failedScanTimelapse:"Fehler beim Suchen nach Zeitraffer",failedAttachTimelapse:"Fehler beim Anhängen des Zeitraffers",timelapseRemoved:"Zeitraffer entfernt",failedRemoveTimelapse:"Fehler beim Entfernen des Zeitraffers",timelapseUploaded:"Zeitraffer hochgeladen: {{filename}}",failedUploadTimelapse:"Fehler beim Hochladen des Zeitraffers",archiveDeleted:"Archiv gelöscht",failedDeleteArchive:"Fehler beim Löschen des Archivs",addedToFavorites:"Zu Favoriten hinzugefügt",removedFromFavorites:"Aus Favoriten entfernt",projectUpdated:"Projekt aktualisiert",failedUpdateProject:"Fehler beim Aktualisieren des Projekts",linkCopied:"Link in die Zwischenablage kopiert",failedCopyLink:"Fehler beim Kopieren des Links",photoDeleted:"Foto gelöscht",failedDeletePhoto:"Fehler beim Löschen des Fotos",failedDeleteArchives:"Fehler beim Löschen der Archive",failedUpdateFavorites:"Fehler beim Aktualisieren der Favoriten",exportDownloaded:"Export heruntergeladen",exportFailed:"Export fehlgeschlagen"},menu:{print:"Drucken",schedule:"Planen",openInBambuStudio:"Im Slicer öffnen",slice:"Slicen",externalLink:"Externer Link",viewOnMakerWorld:"Auf MakerWorld ansehen",preview3d:"3D-Vorschau",viewTimelapse:"Zeitraffer ansehen",scanForTimelapse:"Nach Zeitraffer suchen",uploadTimelapse:"Zeitraffer hochladen",removeTimelapse:"Zeitraffer entfernen",downloadSource3mf:"Quell-3MF herunterladen",uploadSource3mf:"Quell-3MF hochladen",replaceSource3mf:"Quell-3MF ersetzen",removeSource3mf:"Quell-3MF entfernen",uploadF3d:"F3D hochladen",replaceF3d:"F3D ersetzen",downloadF3d:"F3D herunterladen",removeF3d:"F3D entfernen",download:"Herunterladen",copyDownloadLink:"Download-Link kopieren",qrCode:"QR-Code",viewPhotos:"Fotos ansehen",viewPhotosCount:"Fotos ansehen ({{count}})",projectPage:"Projektseite",addToFavorites:"Zu Favoriten hinzufügen",removeFromFavorites:"Aus Favoriten entfernen",edit:"Bearbeiten",goToProject:"Zum Projekt: {{name}}",addToProject:"Zu Projekt hinzufügen",removeFromProject:"Aus Projekt entfernen",loading:"Laden...",noProjectsAvailable:"Keine Projekte verfügbar",select:"Auswählen",deselect:"Abwählen",delete:"Löschen"},permission:{noReprint:"Sie haben keine Berechtigung, dieses Archiv erneut zu drucken",noAddToQueue:"Sie haben keine Berechtigung, zur Warteschlange hinzuzufügen",noUpdateArchives:"Sie haben keine Berechtigung, Archive zu aktualisieren",noUploadFiles:"Sie haben keine Berechtigung, Dateien hochzuladen",noDownload:"Sie haben keine Berechtigung, Archive herunterzuladen",noCopyLink:"Sie haben keine Berechtigung, Download-Links zu kopieren",noDelete:"Sie haben keine Berechtigung, dieses Archiv zu löschen",noCreate:"Sie haben keine Berechtigung, Archive zu erstellen"},card:{previousPlate:"Vorherige Platte",nextPlate:"Nächste Platte",plateNumber:"Platte {{index}}",moreOptions:"Rechtsklick für mehr Optionen",addToFavorites:"Zu Favoriten hinzufügen",removeFromFavorites:"Aus Favoriten entfernen",cancelled:"abgebrochen",failed:"fehlgeschlagen",duplicate:"Duplikat",duplicateTitle:"Dieses Modell wurde bereits zuvor gedruckt",openSource3mf:"Quell-3MF in Bambu Studio öffnen (Rechtsklick für mehr Optionen)",downloadF3d:"Fusion 360 Designdatei herunterladen",viewTimelapse:"Zeitraffer ansehen",viewPhoto:"1 Foto ansehen",viewPhotos:"{{count}} Fotos ansehen",openFolder:"Ordner öffnen: {{name}}",slicedFile:"Geslicte Datei - druckbereit",sourceFile:"Nur Quelldatei - keine AMS-Zuordnung verfügbar",gcode:"GCODE",source:"QUELLE",project:"Projekt: {{name}}",estimated:"Geschätzt: {{time}}",actual:"Tatsächlich: {{time}}",accuracy:"Genauigkeit: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} Schicht",layers:"{{count}} Schichten",object:"{{count}} Objekt",objects:"{{count}} Objekte",slicedFor:"Geslict für {{model}}",uploadedBy:"Hochgeladen von",noPermissionReprint:"Sie haben keine Berechtigung, erneut zu drucken",noFileForReprint:"Keine 3MF-Datei verfügbar — die Datei konnte beim Aufzeichnen des Drucks nicht vom Drucker heruntergeladen werden",noPermissionEdit:"Sie haben keine Berechtigung, Archive zu bearbeiten",noPermissionDelete:"Sie haben keine Berechtigung, Archive zu löschen",reprint:"Drucken",schedulePrint:"Druck planen",schedule:"Planen",openInBambuStudio:"Im Slicer öffnen",openInBambuStudioToSlice:"Im Slicer öffnen zum Slicen",slice:"Slicen",externalLink:"Externer Link",makerWorld:"MakerWorld: {{designer}}",viewProject:"Projekt ansehen",noExternalLink:"Kein externer Link",preview3d:"3D-Vorschau",download:"Herunterladen",edit:"Bearbeiten",delete:"Löschen"},modal:{deleteArchive:"Archiv löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.',deleteButton:"Löschen",removeSource3mf:"Quell-3MF entfernen",removeSource3mfConfirm:'Möchten Sie die Quell-3MF-Datei wirklich von "{{name}}" entfernen? Die ursprüngliche Slicer-Projektdatei wird gelöscht.',removeButton:"Entfernen",removeF3d:"F3D entfernen",removeF3dConfirm:'Möchten Sie die Fusion 360 Designdatei wirklich von "{{name}}" entfernen?',removeTimelapse:"Zeitraffer entfernen",removeTimelapseConfirm:'Möchten Sie das Zeitraffervideo wirklich von "{{name}}" entfernen?',timelapse:"{{name}} - Zeitraffer",selectTimelapse:"Zeitraffer auswählen",selectTimelapseDesc:"Keine automatische Übereinstimmung gefunden. Wählen Sie den Zeitraffer für diesen Druck:",deleteArchives:"Archive löschen",deleteArchivesConfirm:"Möchten Sie wirklich {{count}} Archiv(e) löschen? Diese Aktion kann nicht rückgängig gemacht werden.",deleteCount:"{{count}} löschen"},page:{title:"Archive",printsCount:"{{filtered}} von {{total}} Drucken",dropFilesHere:".3mf-Dateien hier ablegen",releaseToUpload:"Loslassen zum Hochladen",only3mfSupported:"Nur .3mf-Dateien werden unterstützt",close:"Schließen",selected:"{{count}} ausgewählt",selectAll:"Alle auswählen",tags:"Tags",project:"Projekt",favorite:"Favorit",delete:"Löschen",toggledFavorites:"Favoriten für {{count}} Archiv(e) umgeschaltet",failedUpdateFavorites:"Fehler beim Aktualisieren der Favoriten",archivesDeleted:"{{count}} Archiv(e) gelöscht",failedDeleteArchives:"Fehler beim Löschen der Archive",photoDeleted:"Foto gelöscht",failedDeletePhoto:"Fehler beim Löschen des Fotos"},list:{name:"Name",printer:"Drucker",date:"Datum",size:"Größe",actions:"Aktionen",hasTimelapse:"Hat Zeitraffer"},log:{date:"Datum",printName:"Druckname",printer:"Drucker",user:"Benutzer",status:"Status",duration:"Dauer",filament:"Filament",allPrinters:"Alle Drucker",allUsers:"Alle Benutzer",allStatuses:"Alle Status",cancelled:"Abgebrochen",skipped:"Übersprungen",dateFrom:"Von",dateTo:"Bis",noEntries:"Keine Druckprotokolleinträge gefunden",showing:"{{count}} von {{total}} Einträgen",rowsPerPage:"Zeilen",page:"Seite",prev:"Zurück",next:"Weiter",clearLog:"Protokoll löschen",clearLogTitle:"Druckprotokoll löschen",clearLogConfirm:"Alle Druckprotokolleinträge werden dauerhaft gelöscht. Archive und Warteschlangeneinträge sind nicht betroffen. Diese Aktion kann nicht rückgängig gemacht werden. Sind Sie sicher?",clearLogButton:"Alle löschen",cleared:"{{count}} Protokolleinträge gelöscht",clearFailed:"Druckprotokoll konnte nicht gelöscht werden"}},queue:{title:"Druckwarteschlange",subtitle:"Planen und verwalten Sie Ihre Druckaufträge",addToQueue:"Zur Warteschlange hinzufügen",print:"Drucken",reprint:"Erneut drucken",schedulePrint:"Druck planen",editQueueItem:"Warteschlangeneintrag bearbeiten",printToPrinters:"Auf {{count}} Druckern drucken",queueToPrinters:"Zu {{count}} Druckern hinzufügen",sending:"Wird gesendet...",sendingProgress:"Sende {{current}}/{{total}}...",adding:"Wird hinzugefügt...",addingProgress:"Füge hinzu {{current}}/{{total}}...",savingProgress:"Speichere {{current}}/{{total}}...",clearQueue:"Warteschlange leeren",clearHistory:"Verlauf löschen",emptyQueue:"Warteschlange ist leer",position:"Position",scheduledTime:"Geplante Zeit",moveUp:"Nach oben",moveDown:"Nach unten",startNow:"Jetzt starten",printingInProgress:"Druck läuft...",viewArchive:"Archiv anzeigen",viewInFileManager:"Im Dateimanager anzeigen",itemCount:"{{count}} Element",itemCount_plural:"{{count}} Elemente",dragToReorder:"Ziehen zum Neuordnen (nur Sofort)",reorderHint:"Position betrifft nur Sofort-Elemente. Geplante Elemente werden zur festgelegten Zeit ausgeführt.",addedBy:"Hinzugefügt von {{name}}",nextInQueue:"Nächster in der Warteschlange",clearPlate:"Druckplatte freigeben & Nächsten starten",clearPlateSuccess:"Druckplatte freigegeben — bereit für nächsten Druck",plateReady:"Druckplatte freigegeben — bereit für nächsten Druck",plateNumber:"Platte {{index}}",sections:{currentlyPrinting:"Aktuell druckend",queued:"In Warteschlange",history:"Verlauf"},status:{pending:"Ausstehend",waiting:"Wartend",printing:"Druckt",paused:"Pausiert",completed:"Abgeschlossen",failed:"Fehlgeschlagen",skipped:"Übersprungen",cancelled:"Abgebrochen"},summary:{printing:"Druckt",queued:"In Warteschlange",totalTime:"Gesamte Wartezeit",totalWeight:"Gesamtgewicht der Warteschlange",history:"Verlauf"},filter:{allPrinters:"Alle Drucker",unassigned:"Nicht zugewiesen",allStatus:"Alle Status",allLocations:"Alle Standorte",any:"Beliebig"},sort:{byPosition:"Nach Position sortieren",byName:"Nach Name sortieren",byPrinter:"Nach Drucker sortieren",bySchedule:"Nach Zeitplan sortieren",byDate:"Nach Datum sortieren",ascendingOldest:"Aufsteigend (älteste zuerst)",descendingNewest:"Absteigend (neueste zuerst)"},badges:{staged:"Bereitgestellt",requiresPrevious:"Erfordert vorherigen Erfolg",autoPowerOff:"Automatisch ausschalten"},empty:{title:"Keine Drucke geplant",description:'Planen Sie einen Druck von der Archivseite über die Option "Planen" im Kontextmenü oder ziehen Sie Dateien hierher.'},time:{asap:"Sofort",overdue:"Überfällig",now:"Jetzt",lessThanMinute:"In weniger als einer Minute",inMinutes:"In {{count}} Min",inHours:"In {{count}} Stunden"},actions:{stopPrint:"Druck stoppen",startPrint:"Druck starten",requeue:"Erneut einreihen"},bulkEdit:{title:"{{count}} Element bearbeiten",title_plural:"{{count}} Elemente bearbeiten",description:"Nur geänderte Einstellungen werden auf ausgewählte Elemente angewendet.",printer:"Drucker",noChange:"— Keine Änderung —",queueOptions:"Warteschlangenoptionen",staged:"Bereitgestellt (manueller Start)",autoPowerOff:"Nach Druck automatisch ausschalten",requirePrevious:"Vorherigen Erfolg erfordern",printOptions:"Druckoptionen",bedLevelling:"Bett-Nivellierung",flowCalibration:"Fluss-Kalibrierung",vibrationCalibration:"Vibrations-Kalibrierung",layerInspection:"Erste-Schicht-Prüfung",timelapse:"Zeitraffer",useAms:"AMS verwenden",applyChanges:"Änderungen übernehmen",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",selected:"{{count}} ausgewählt",editSelected:"Ausgewählte bearbeiten",cancelSelected:"Ausgewählte abbrechen"},confirm:{cancelTitle:"Geplanten Druck abbrechen",cancelMessage:'Möchten Sie "{{name}}" wirklich abbrechen?',stopTitle:"Druck stoppen",stopMessage:'Möchten Sie den aktuellen Druck "{{name}}" wirklich stoppen? Der Druckauftrag wird am Drucker abgebrochen.',removeTitle:"Aus Verlauf entfernen",removeMessage:'Möchten Sie "{{name}}" wirklich aus dem Warteschlangenverlauf entfernen?',clearHistoryTitle:"Verlauf löschen",clearHistoryMessage:"Möchten Sie alle {{count}} Element(e) aus dem Verlauf entfernen?",cancelButton:"Druck abbrechen",stopButton:"Druck stoppen",thisPrint:"diesen Druck",thisItem:"dieses Element"},toast:{cancelled:"Warteschlangenelement abgebrochen",cancelFailed:"Element konnte nicht abgebrochen werden",removed:"Warteschlangenelement entfernt",removeFailed:"Element konnte nicht entfernt werden",stopped:"Druck gestoppt",stopFailed:"Druck konnte nicht gestoppt werden",released:"Druck in Warteschlange freigegeben",startFailed:"Druck konnte nicht gestartet werden",reorderFailed:"Warteschlange konnte nicht neu geordnet werden",historyCleared:"{{count}} Verlaufselement(e) gelöscht",clearHistoryFailed:"Verlauf konnte nicht gelöscht werden",updateFailed:"Elemente konnten nicht aktualisiert werden",bulkCancelled:"{{count}} Element(e) abgebrochen",bulkCancelFailed:"Elemente konnten nicht abgebrochen werden"},permissions:{noStopPrint:"Sie haben keine Berechtigung, Drucke zu stoppen",noStartPrint:"Sie haben keine Berechtigung, Drucke zu starten",noEdit:"Sie haben keine Berechtigung, dieses Warteschlangenelement zu bearbeiten",noCancel:"Sie haben keine Berechtigung, dieses Warteschlangenelement abzubrechen",noRequeue:"Sie haben keine Berechtigung, Elemente erneut einzureihen",noRemove:"Sie haben keine Berechtigung, dieses Warteschlangenelement zu entfernen",noClearHistory:"Sie haben keine Berechtigung, den gesamten Verlauf zu löschen",noEditItems:"Sie haben keine Berechtigung, Warteschlangenelemente zu bearbeiten",noCancelItems:"Sie haben keine Berechtigung, Warteschlangenelemente abzubrechen"}},backgroundDispatch:{unknownFile:"Unbekannte Datei",unknownPrinter:"Unbekannter Drucker",startingPrints:"Starte Drucke",progressSummary:"{{complete}}/{{total}} abgeschlossen • Geplant: {{dispatched}} • In Bearbeitung: {{processing}}",expandDetails:"Dispatch-Details ausklappen",collapseDetails:"Dispatch-Details einklappen",dismissToast:"Dispatch-Hinweis schließen",cancelDispatchJob:"Dispatch-Job abbrechen",cancel:"Abbrechen",cancelling:"Wird abgebrochen…",status:{dispatched:"Geplant",processing:"In Bearbeitung",completed:"Abgeschlossen",failed:"Fehlgeschlagen",cancelled:"Abgebrochen"},toast:{cancellingUpload:"Upload wird abgebrochen...",cancelled:"Dispatch abgebrochen",cancelFailed:"Dispatch konnte nicht abgebrochen werden",completeWithFailures:"Background Dispatch abgeschlossen: {{completed}} erfolgreich, {{failed}} fehlgeschlagen",completeSuccess:"Background Dispatch abgeschlossen: {{completed}} erfolgreich"}},stats:{title:"Dashboard",subtitle:"Widgets zum Neuanordnen ziehen. Auf das Augensymbol klicken zum Ausblenden.",overview:"Übersicht",totalPrints:"Gesamtdrucke",successRate:"Erfolgsrate",totalPrintTime:"Gesamtdruckzeit",printTime:"Druckzeit",totalFilament:"Gesamtverbrauch Filament",filamentUsed:"Filamentverbrauch",filamentCost:"Filamentkosten",totalCost:"Gesamtkosten",energyUsed:"Energieverbrauch",energyCost:"Energiekosten",averagePrintTime:"Durchschnittliche Druckzeit",printsPerDay:"Drucke pro Tag",byPrinter:"Nach Drucker",printsByPrinter:"Drucke nach Drucker",byMaterial:"Nach Material",byMonth:"Nach Monat",last7Days:"Letzte 7 Tage",last30Days:"Letzte 30 Tage",last90Days:"Letzte 90 Tage",allTime:"Gesamt",quickStats:"Schnellstatistiken",printActivity:"Druckaktivität",filamentTypes:"Filamenttypen",filamentTrends:"Filamenttrends",failureAnalysis:"Fehleranalyse",timeAccuracy:"Zeitgenauigkeit",successful:"Erfolgreich:",failed:"Fehlgeschlagen:",perfectEstimate:"100% = perfekte Schätzung",noTimeAccuracyData:"Noch keine Zeitgenauigkeitsdaten",noFilamentData:"Keine Filamentdaten verfügbar",noPrinterData:"Keine Druckerdaten verfügbar",noPrintData:"Keine Druckdaten verfügbar",noPrintDataLast30Days:"Keine Druckdaten in den letzten 30 Tagen",failureReasons:"Fehlerursachen",topFailureReasons:"Häufigste Fehlerursachen",failedPrintsCount:"{{failed}} / {{total}} Drucke fehlgeschlagen",lastWeekRate:"Letzte Woche: {{rate}}%",resetLayout:"Layout zurücksetzen",recalculateCosts:"Kosten neu berechnen",recalculateCostsHint:"Alle Archivkosten mit aktuellen Filamentpreisen neu berechnen",exportStats:"Statistiken exportieren",exportAsCsv:"Als CSV exportieren",exportAsExcel:"Als Excel exportieren",hiddenCount:"{{count}} ausgeblendet",exportDownloaded:"Export heruntergeladen",exportFailed:"Export fehlgeschlagen",layoutReset:"Layout zurückgesetzt",recalculatedCosts:"Kosten für {{count}} Archive neu berechnet",recalculateFailed:"Kosten konnten nicht neu berechnet werden",loadingStats:"Statistiken werden geladen...",noPermissionResetLayout:"Sie haben keine Berechtigung, das Layout zurückzusetzen",noPermissionRecalculate:"Sie haben keine Berechtigung, Kosten neu zu berechnen"},maintenance:{title:"Wartung",overview:"Übersicht",allOk:"Alle Wartungen aktuell",dueCount:"{{count}} Aufgabe fällig",dueCount_plural:"{{count}} Aufgaben fällig",warningCount:"{{count}} Warnung",warningCount_plural:"{{count}} Warnungen",totalPrintTime:"Gesamtdruckzeit",nextMaintenance:"Nächste Wartung",nothingDue:"Nichts fällig",tasks:"Aufgaben",lastPerformed:"Zuletzt durchgeführt",interval:"Intervall",hoursRemaining:"{{hours}}h verbleibend",hoursOverdue:"{{hours}}h überfällig",markDone:"Als erledigt markieren",performMaintenance:"Wartung durchführen",history:"Verlauf",noHistory:"Kein Wartungsverlauf",editPrintHours:"Druckstunden bearbeiten",currentHours:"Aktuelle Stunden",statusTab:"Status",settingsTab:"Einstellungen",overdueCount:"{{count}} überfällig",dueSoonCount:"{{count}} bald fällig",dueSoon:"Bald fällig",allGood:"Alles in Ordnung",overdueBy:"Überfällig um {{duration}}",dueIn:"Fällig in {{duration}}",timeLeft:"{{duration}} verbleibend",day:"1 Tag",days:"{{count}} Tage",week:"1 Woche",weeks:"{{count}} Wochen",month:"1 Monat",months:"{{count}} Monate",year:"1 Jahr",maintenanceTypes:"Wartungstypen",maintenanceTypesDescription:"Systemtypen und Ihre benutzerdefinierten Wartungsaufgaben",addCustomType:"Benutzerdefinierten Typ hinzufügen",restoreDefaults:"Standardaufgaben wiederherstellen",intervalType:"Intervalltyp",intervalValue:"Intervall ({{type}})",icon:"Symbol",documentationLink:"Dokumentationslink (optional)",assignToPrinters:"Druckern zuweisen",selectAtLeastOnePrinter:"Wählen Sie mindestens einen Drucker",addType:"Typ hinzufügen",custom:"Benutzerdefiniert",printHours:"Druckstunden",calendarDays:"Kalendertage",exampleName:"z.B. HEPA-Filter ersetzen",viewDocumentation:"Dokumentation anzeigen",timeBasedInterval:"Zeitbasiertes Intervall",intervalOverrides:"Intervall-Überschreibungen",intervalOverridesDescription:"Intervalle für bestimmte Drucker anpassen",assignedToPrinters:"Druckern zugewiesen:",noPrintersAssigned:"Keine Drucker zugewiesen",addPrinterShort:"Hinzufügen:",printersAssignedClick:"{{count}} Drucker zugewiesen - klicken zum Verwalten",removeFromPrinter:"Von diesem Drucker entfernen",types:{lubricateCarbonRods:"Karbonstäbe schmieren",lubricateRails:"Linearschienen schmieren",cleanNozzle:"Düse/Hotend reinigen",checkBelts:"Riemenspannung prüfen",cleanBuildPlate:"Druckbett reinigen",checkExtruder:"Extruderzahnräder prüfen",checkCooling:"Kühlungslüfter prüfen",generalInspection:"Allgemeine Inspektion",cleanCarbonRods:"Kohlenstoffstangen reinigen",cleanLinearRails:"Linearschienen reinigen",checkPtfeTube:"PTFE-Schlauch prüfen",replaceHepaFilter:"HEPA-Filter ersetzen",replaceCarbonFilter:"Aktivkohlefilter ersetzen",lubricateLeftNozzleRail:"Linke Düsenschiene schmieren"},maintenanceComplete:"Wartung als abgeschlossen markiert",typeUpdated:"Wartungstyp aktualisiert",typeDeleted:"Wartungstyp gelöscht",defaultsRestored:"{{count}} Standardaufgabe(n) wiederhergestellt",printHoursUpdated:"Druckstunden aktualisiert",printerAssigned:"Drucker zugewiesen",printerRemoved:"Drucker entfernt",deleteTypeConfirm:'"{{name}}" löschen?',deleteSystemTypeTitle:"Standard-Wartungsaufgabe löschen?",deleteSystemTypeMessage:'Möchten Sie die Standard-Wartungsaufgabe "{{name}}" wirklich löschen?',noPermissionUpdate:"Sie haben keine Berechtigung, Wartungselemente zu aktualisieren",noPermissionPerform:"Sie haben keine Berechtigung, Wartungen durchzuführen",noPermissionEditTypes:"Sie haben keine Berechtigung, Wartungstypen zu bearbeiten",noPermissionDeleteTypes:"Sie haben keine Berechtigung, Wartungstypen zu löschen",noPermissionEditHours:"Sie haben keine Berechtigung, Druckstunden zu bearbeiten",noPermissionRemovePrinter:"Sie haben keine Berechtigung, Druckerzuweisungen zu entfernen",noPermissionAssignPrinter:"Sie haben keine Berechtigung, Drucker zuzuweisen",noPermissionEditIntervals:"Sie haben keine Berechtigung, Intervalle zu bearbeiten",configureSettings:"Wartungstypen und Intervalle konfigurieren"},settings:{title:"Einstellungen",general:"Allgemein",tabs:{general:"Allgemein",smartPlugs:"Smart Plugs",notifications:"Benachrichtigungen",filament:"Filament",network:"Netzwerk",apiKeys:"API-Schlüssel",virtualPrinter:"Virtueller Drucker",users:"Authentifizierung",backup:"Sicherung",emailAuth:"E-Mail-Authentifizierung"},email:{smtpSettings:"SMTP-Konfiguration",smtpHost:"SMTP-Server",smtpPort:"SMTP-Port",security:"Sicherheit",authentication:"Authentifizierung",username:"Benutzername",password:"Passwort",fromEmail:"Absender-E-Mail",fromName:"Absendername",testConnection:"SMTP-Verbindung testen",testRecipient:"Test-Empfänger-E-Mail",sendTest:"Test-E-Mail senden",sending:"Wird gesendet...",save:"Einstellungen speichern",saving:"Wird gespeichert...",advancedAuth:"Erweiterte Authentifizierung",advancedAuthEnabled:"Erweiterte Authentifizierung ist aktiviert",advancedAuthEnabledDesc:"E-Mail-basierte Benutzerverwaltungsfunktionen sind aktiv. Neue Benutzer erhalten automatisch generierte Passwörter per E-Mail und können ihr Passwort über die Passwort vergessen Funktion zurücksetzen.",advancedAuthDisabled:"Erweiterte Authentifizierung ist deaktiviert",advancedAuthDisabledDesc:"Aktivieren Sie die erweiterte Authentifizierung, um E-Mail-basierte Funktionen für die Benutzerverwaltung zu aktivieren.",enable:"Aktivieren",disable:"Deaktivieren",feature1:"Passwörter werden automatisch generiert und an neue Benutzer gesendet",feature2:"Benutzer können sich mit Benutzername oder E-Mail anmelden",feature3:"Passwort vergessen Funktion ist verfügbar",feature4:"Administratoren können Benutzerpasswörter per E-Mail zurücksetzen",errors:{requiredFields:"Bitte füllen Sie alle Pflichtfelder aus",usernameRequired:"Benutzername ist erforderlich, wenn Authentifizierung aktiviert ist",enterTestEmail:"Bitte geben Sie eine Test-E-Mail-Adresse ein",smtpServerAndEmail:"Bitte füllen Sie SMTP-Server und Absender-E-Mail aus, bevor Sie testen",usernamePasswordRequired:"Benutzername und Passwort sind erforderlich, wenn Authentifizierung aktiviert ist",configureSmtpFirst:"Bitte konfigurieren und testen Sie zuerst die SMTP-Einstellungen"},success:{settingsSaved:"SMTP-Einstellungen erfolgreich gespeichert"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"Keine (Port 25)"},authOptions:{enabled:"Aktiviert",disabled:"Deaktiviert"}},appearance:"Erscheinungsbild",notifications:"Benachrichtigungen",smartPlugs:"Smart Plugs",spoolman:"Spoolman",updates:"Updates",language:"Sprache",languageDescription:"Wählen Sie Ihre bevorzugte Sprache",theme:"Design",themeLight:"Hell",themeDark:"Dunkel",themeSystem:"System",defaultView:"Standardansicht",defaultViewDescription:"Seite, die beim Öffnen der App angezeigt wird",checkForUpdates:"Nach Updates suchen",autoUpdate:"Automatische Updates",currentVersion:"Aktuelle Version",latestVersion:"Neueste Version",upToDate:"Sie sind auf dem neuesten Stand",updateAvailable:"Update verfügbar",notificationLanguage:"Benachrichtigungssprache",notificationLanguageDescription:"Sprache für Push-Benachrichtigungen",bedCooledThreshold:"Bett-Abkühlung Schwellenwert",bedCooledThresholdDescription:"Temperatur, unter der das Bett nach einem Druck als abgekühlt gilt",notificationProviders:"Benachrichtigungsanbieter",addProvider:"Anbieter hinzufügen",editProvider:"Anbieter bearbeiten",providerType:"Anbietertyp",testNotification:"Testbenachrichtigung",testSuccess:"Testbenachrichtigung erfolgreich gesendet",testFailed:"Testbenachrichtigung konnte nicht gesendet werden",quietHours:"Ruhezeiten",quietHoursDescription:"Keine Störungen während dieser Zeiten",quietHoursStart:"Beginn",quietHoursEnd:"Ende",events:{title:"Benachrichtigungsereignisse",printStart:"Druck gestartet",printComplete:"Druck abgeschlossen",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",printProgress:"Fortschrittsmeldungen",printProgressDescription:"Bei 25%, 50%, 75% benachrichtigen",printerOffline:"Drucker offline",printerError:"Druckerfehler",filamentLow:"Filament niedrig",maintenanceDue:"Wartung fällig",maintenanceDueDescription:"Benachrichtigen, wenn Wartung erforderlich"},smartPlug:{title:"Smart Plugs",add:"Smart Plug hinzufügen",edit:"Smart Plug bearbeiten",name:"Name",ipAddress:"IP-Adresse",linkedPrinter:"Verknüpfter Drucker",autoOn:"Automatisch einschalten",autoOnDescription:"Einschalten beim Druckstart",autoOff:"Automatisch ausschalten",autoOffDescription:"Ausschalten nach Druckende",offDelay:"Ausschaltverzögerung",offDelayMinutes:"Minuten nach Druck",offDelayTemp:"Wenn Düse unter Temperatur",currentState:"Aktueller Status",turnOn:"Einschalten",turnOff:"Ausschalten"},filamentTracking:"Filament-Verfolgung",filamentTrackingDesc:"Wählen Sie, wie Sie Ihre Filamentspulen verfolgen möchten. Sie können das integrierte Inventar oder einen externen Spoolman-Server verwenden.",trackingModeBuiltIn:"Integriertes Inventar",trackingModeBuiltInDesc:"RFID-Erkennung und Verbrauchserfassung inklusive",trackingModeSpoolmanDesc:"Externer Filament-Management-Server",builtInFeatureRfid:"Erkennt automatisch Bambu Lab RFID-Spulen im AMS",builtInFeatureUsage:"Erfasst den Filamentverbrauch pro Druck",builtInFeatureCatalog:"Spulen, Farben und K-Faktor-Profile verwalten",builtInFeatureThirdParty:"Drittanbieter-Spulen können Inventarspulen zugewiesen werden",amsSyncButton:"Gewichte vom AMS synchronisieren",amsSyncTitle:"Spulengewichte vom AMS synchronisieren",amsSyncMessage:"Alle Inventar-Spulengewichte werden mit den aktuellen AMS-Restwerten der verbundenen Drucker überschrieben. Verwenden Sie dies zur Wiederherstellung beschädigter Gewichtsdaten. Drucker müssen online sein.",amsSyncing:"Synchronisiere...",amsSyncSuccess:"{{synced}} Spule(n) synchronisiert, {{skipped}} übersprungen",amsSyncError:"Synchronisierung der Gewichte vom AMS fehlgeschlagen",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL Ihres Spoolman-Servers (z.B. http://localhost:7912)",spoolmanConnected:"Verbunden",spoolmanDisconnected:"Nicht verbunden",status:"Status",connect:"Verbinden",disconnect:"Trennen",howSyncWorks:"So funktioniert die Synchronisierung",syncInfoRfidOnly:"Nur offizielle Bambu Lab Spulen mit RFID werden synchronisiert",syncInfoAutoCreate:"Neue Spulen werden bei der ersten Synchronisierung automatisch in Spoolman erstellt",syncInfoThirdPartySkipped:"Nicht-Bambu-Lab-Spulen (Drittanbieter, nachgefüllt) werden übersprungen",linkingExistingSpools:"Vorhandene Spulen verknüpfen",linkingExistingSpoolsDesc:'Um vorhandene Spoolman-Spulen mit Ihrem AMS zu verknüpfen, fahren Sie über einen AMS-Slot und klicken Sie auf "Mit Spoolman verknüpfen".',syncMode:"Synchronisierungsmodus",syncModeAuto:"Automatisch",syncModeManual:"Nur manuell",syncModeAutoDesc:"AMS-Daten werden automatisch synchronisiert, wenn Änderungen erkannt werden",syncModeManualDesc:"Nur bei manueller Auslösung synchronisieren",syncAmsData:"AMS-Daten synchronisieren",syncAmsDataDesc:"AMS-Daten des Druckers manuell mit Spoolman synchronisieren",allPrinters:"Alle Drucker",noDefaultPrinter:"Kein Standard (jedes Mal fragen)",sidebarOrder:"Seitenleisten-Reihenfolge",saveThumbnails:"Vorschaubilder speichern",captureFinishPhoto:"Abschlussfoto aufnehmen",noPrintersConfigured:"Keine Drucker konfiguriert",archiveMode:{always:"Immer Archiveintrag erstellen",never:"Nie Archiveintrag erstellen",ask:"Jedes Mal fragen"},checkForUpdatesLabel:"Nach Updates suchen",checkPrinterFirmware:"Drucker-Firmware prüfen",includeBetaUpdates:"Beta-Versionen einschließen",includeBetaUpdatesDesc:"Über Beta- und Vorabversionen bei der Updateprüfung benachrichtigen",enableRetry:"Wiederholung aktivieren",homeAssistantDescription:"Smart Plugs über Home Assistant steuern",environmentManagedLabel:"(Umgebungsvariable)",autoEnabledViaEnv:"Automatisch über Umgebungsvariablen aktiviert",urlFromEnvReadOnly:"Wert wird über HA_URL Umgebungsvariable gesetzt (schreibgeschützt)",tokenFromEnvReadOnly:"Wert wird über HA_TOKEN Umgebungsvariable gesetzt (schreibgeschützt)",mqttConnectedTo:"Verbunden mit",prometheusDescription:"Druckerdaten im Prometheus-Format bereitstellen",noSmartPlugsTitle:"Keine Smart Plugs konfiguriert",noSmartPlugsDescription:"Fügen Sie einen Tasmota-basierten Smart Plug hinzu, um den Energieverbrauch zu verfolgen und die Stromsteuerung zu automatisieren.",noProvidersTitle:"Keine Anbieter konfiguriert",noProvidersDescription:"Fügen Sie einen Anbieter hinzu, um Benachrichtigungen zu erhalten.",noTemplatesAvailable:"Keine Vorlagen verfügbar. Starten Sie das Backend neu, um Standardvorlagen zu laden.",apiPermissionView:"Druckerstatus und Warteschlange anzeigen",apiPermissionEdit:"Elemente zur Druckwarteschlange hinzufügen und entfernen",apiKeysEmptyTitle:"Keine API-Schlüssel",apiKeysEmptyDescription:"Erstellen Sie einen API-Schlüssel zur Integration mit externen Diensten.",noUsersFound:"Keine Benutzer gefunden",noGroupsFound:"Keine Gruppen gefunden",noGroupsAvailable:"Keine Gruppen verfügbar",passwordsDoNotMatch:"Passwörter stimmen nicht überein",systemGroupWarning:"System-Gruppennamen können nicht geändert werden",authDisabledTitle:"Authentifizierung ist deaktiviert",authDisabledFeature1:"Anmeldung zum Zugriff auf das System erforderlich",authDisabledFeature2:"Mehrere Benutzer mit gruppenbasierten Berechtigungen erstellen",authDisabledFeature3:"Zugriff mit über 50 granularen Berechtigungen steuern",userHasCreated:"Dieser Benutzer hat erstellt:",userItemsQuestion:"Was möchten Sie mit diesen Elementen tun?",deleteUserConfirm:"Möchten Sie diesen Benutzer wirklich löschen?",actionCannotBeUndone:"Diese Aktion kann nicht rückgängig gemacht werden.",addFirstSmartPlug:"Ersten Smart Plug hinzufügen",providers:"Anbieter",log:"Protokoll",testAll:"Alle testen",testResults:"Testergebnisse",testPassedCount:"{{count}} bestanden",testFailedCount:"{{count}} fehlgeschlagen",messageTemplates:"Nachrichtenvorlagen",messageTemplatesDescription:"Passen Sie Benachrichtigungen für jedes Ereignis an.",apiKeys:"API-Schlüssel",apiKeysDescription:"Erstellen Sie API-Schlüssel für externe Integrationen und Webhooks.",createKey:"Schlüssel erstellen",apiKeyCreated:"API-Schlüssel erfolgreich erstellt",apiKeyCopyWarning:"Kopieren Sie diesen Schlüssel jetzt - er wird nicht mehr angezeigt!",useInApiBrowser:"Im API-Browser verwenden",createNewApiKey:"Neuen API-Schlüssel erstellen",keyName:"Schlüsselname",keyNamePlaceholder:"z.B. Home Assistant, OctoPrint",readStatus:"Status lesen",readStatusDescription:"Druckerstatus und Warteschlange anzeigen",manageQueue:"Warteschlange verwalten",manageQueueDescription:"Elemente zur Druckwarteschlange hinzufügen und entfernen",controlPrinter:"Drucker steuern",controlPrinterDescription:"Drucke pausieren, fortsetzen und stoppen",unnamedKey:"Unbenannter Schlüssel",lastUsed:"Zuletzt verwendet",read:"Lesen",control:"Steuern",createFirstKey:"Ersten Schlüssel erstellen",webhookEndpoints:"Webhook-Endpunkte",webhookApiKeyHint:"Verwenden Sie Ihren API-Schlüssel im X-API-Key-Header.",webhook:{getAllStatus:"Alle Druckerstatus abrufen",getSpecificStatus:"Spezifischen Druckerstatus abrufen",addToQueue:"Zur Druckwarteschlange hinzufügen",pausePrint:"Druck pausieren",resumePrint:"Druck fortsetzen",stopPrint:"Druck stoppen"},apiBrowser:"API-Browser",apiBrowserDescription:"Erkunden und testen Sie alle verfügbaren API-Endpunkte.",apiKeyForTesting:"API-Schlüssel zum Testen",apiKeyPlaceholder:"Fügen Sie hier Ihren API-Schlüssel ein, um authentifizierte Endpunkte zu testen...",apiKeyHint:"Dieser Schlüssel wird als X-API-Key-Header mit Anfragen gesendet.",deleteApiKeyTitle:"API-Schlüssel löschen",deleteApiKeyMessage:"Möchten Sie diesen API-Schlüssel wirklich löschen? Alle Integrationen, die diesen Schlüssel verwenden, funktionieren nicht mehr.",deleteKey:"Schlüssel löschen",amsDisplayThresholds:"AMS-Anzeigeschwellenwerte",amsThresholdsDescription:"Konfigurieren Sie Farbschwellenwerte für AMS-Feuchtigkeits- und Temperaturanzeigen.",humidity:"Luftfeuchtigkeit",goodGreen:"Gut (grün)",fairOrange:"Mittel (orange)",aboveFairBad:"Über dem mittleren Schwellenwert wird rot angezeigt (schlecht)",temperature:"Temperatur",goodBlue:"Gut (blau)",aboveFairHot:"Über dem mittleren Schwellenwert wird rot angezeigt (heiß)",historyRetention:"Verlaufsaufbewahrung",keepSensorHistory:"Sensorverlauf behalten für",historyRetentionDescription:"Ältere Feuchtigkeits- und Temperaturdaten werden automatisch gelöscht",printModal:"Druckdialog",expandCustomMapping:"Benutzerdefinierte Zuordnung standardmäßig erweitern",expandCustomMappingDescription:"Bei Druck auf mehrere Drucker die AMS-Zuordnung pro Drucker erweitert anzeigen",authentication:"Authentifizierung",authEnabledDescription:"Ihre Instanz ist mit Benutzerauthentifizierung gesichert",authDisabledDescription:"Aktivieren Sie die Anmeldepflicht und verwalten Sie den Benutzerzugriff",authDisabledMessage:"Aktivieren Sie die Authentifizierung, um Benutzerkonten zu erstellen, Berechtigungen zu verwalten und Ihre Bambuddy-Instanz zu sichern.",enableAuthentication:"Authentifizierung aktivieren",currentUser:"Aktueller Benutzer",changePassword:"Passwort ändern",admin:"Admin",users:"Benutzer",addUser:"Benutzer hinzufügen",groups:"Gruppen",addGroup:"Gruppe hinzufügen",system:"System",noDescription:"Keine Beschreibung",userCount:"{{count}} Benutzer",permissionCount:"{{count}} Berechtigungen",createUser:"Benutzer erstellen",username:"Benutzername",enterUsername:"Benutzername eingeben",password:"Passwort",enterPassword:"Passwort eingeben (min. 6 Zeichen)",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Passwort bestätigen",viewReleaseOnGitHub:"Release auf GitHub anzeigen",turnAllPlugsOn:"Alle Stecker einschalten",turnAllPlugsOff:"Alle Stecker ausschalten",clearNotificationLogs:"Benachrichtigungsprotokolle löschen",clearLogsMessage:"Dadurch werden alle Benachrichtigungsprotokolle, die älter als 30 Tage sind, dauerhaft gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.",clearLogs:"Protokolle löschen",resetUiPreferences:"UI-Einstellungen zurücksetzen",resetUiPreferencesMessage:"Dadurch werden alle UI-Einstellungen auf Standardwerte zurückgesetzt: Seitenleisten-Reihenfolge, Theme, Dashboard-Layout, Ansichtsmodi und Sortiereinstellungen. Ihre Drucker, Archive und Servereinstellungen werden NICHT beeinträchtigt. Die Seite wird nach dem Löschen neu geladen.",resetPreferences:"Einstellungen zurücksetzen",deleteGroupTitle:"Gruppe löschen",deleteGroupMessage:"Möchten Sie diese Gruppe wirklich löschen? Benutzer in dieser Gruppe verlieren diese Berechtigungen.",deleteGroup:"Gruppe löschen",disableAuthenticationTitle:"Authentifizierung deaktivieren",disableAuthenticationMessage:"Möchten Sie die Authentifizierung wirklich deaktivieren? Dadurch wird Ihre Bambuddy-Instanz ohne Anmeldung zugänglich. Alle Benutzer bleiben in der Datenbank, aber die Authentifizierung wird deaktiviert.",disableAuthentication:"Authentifizierung deaktivieren",configureBambuddy:"Bambuddy konfigurieren",systemDefault:"Systemstandard",archiveSettings:"Archiv-Einstellungen",newWindow:"Neues Fenster",embeddedOverlay:"Eingebettetes Overlay",preferredSlicer:"Bevorzugter Slicer",preferredSlicerDescription:"Wähle die Slicer-Anwendung zum Öffnen von Dateien",externalCameras:"Externe Kameras",costTracking:"Kostenverfolgung",printsOnly:"Nur Drucke",totalConsumption:"Gesamtverbrauch",dataManagement:"Datenverwaltung",storageUsage:"Speichernutzung",storageUsageDescription:"Aufschlüsselung der Datennutzung nach Kategorie",storageUsageTotal:"Gesamt",storageUsageErrors:"Fehler",storageUsageOtherBreakdown:"Sonstiges (enthält statische Assets, Skripte und Konfigurationsdateien)",storageUsageSystem:"System",storageUsageData:"Daten",storageUsageUnavailable:"Speichernutzungsinformationen nicht verfügbar",clearNotificationLogsDescription:"Benachrichtigungsprotokolle älter als 30 Tage löschen",resetUiPreferencesDescription:"Seitenleisten-Reihenfolge, Theme, Ansichtsmodi und Layout-Einstellungen zurücksetzen. Drucker, Archive und Einstellungen werden nicht beeinflusst.",enableHomeAssistant:"Home Assistant aktivieren",enableMqtt:"MQTT aktivieren",useTls:"TLS verwenden",enableMetricsEndpoint:"Metrik-Endpunkt aktivieren",availableMetrics:"Verfügbare Metriken",editUser:"Benutzer bearbeiten",deleteUserTitle:"Benutzer löschen",groupName:"Gruppenname",leaveEmptyForAnonymous:"Leer lassen für anonym",leaveEmptyForNoAuth:"Leer lassen für keine Authentifizierung",enterNewPassword:"Neues Passwort eingeben",confirmNewPassword:"Neues Passwort bestätigen",enterGroupName:"Gruppenname eingeben",enterDescriptionOptional:"Beschreibung eingeben (optional)",enterCurrentPassword:"Aktuelles Passwort eingeben",enterNewPasswordMin6:"Neues Passwort eingeben (min. 6 Zeichen)",toast:{keyCopied:"Schlüssel in Zwischenablage kopiert",copyFailed:"Schlüssel konnte nicht kopiert werden",keyAddedToBrowser:"Schlüssel zum API-Browser hinzugefügt",clearLogsFailed:"Protokolle konnten nicht gelöscht werden",uiPreferencesReset:"UI-Einstellungen zurückgesetzt. Wird neu geladen...",authDisabled:"Authentifizierung erfolgreich deaktiviert",authDisableFailed:"Authentifizierung konnte nicht deaktiviert werden",apiKeyCreated:"API-Schlüssel erstellt",apiKeyDeleted:"API-Schlüssel gelöscht",userCreated:"Benutzer erfolgreich erstellt",userUpdated:"Benutzer erfolgreich aktualisiert",userDeleted:"Benutzer erfolgreich gelöscht",groupCreated:"Gruppe erfolgreich erstellt",groupUpdated:"Gruppe erfolgreich aktualisiert",groupDeleted:"Gruppe erfolgreich gelöscht",fillRequiredFields:"Bitte füllen Sie alle erforderlichen Felder aus",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein",enterGroupName:"Bitte geben Sie einen Gruppennamen ein",settingsSaved:"Einstellungen gespeichert",cameraSettingsSaved:"Kamera-Einstellungen gespeichert",enterCameraUrl:"Bitte geben Sie eine Kamera-URL ein",passwordChanged:"Passwort erfolgreich geändert",connectionFailed:"Verbindung fehlgeschlagen",testFailed:"Test fehlgeschlagen",cameraConnected:"Kamera verbunden{{resolution}}"},testConnection:"Verbindung testen",catalog:{spoolCatalog:"Spulenkatalog",spoolCatalogDescription:"Leerspulengewichte nach Marke/Typ. Wird für die automatische Gewichtssuche beim Hinzufügen von Spulen verwendet.",searchCatalog:"Katalog durchsuchen...",addNewEntry:"Neuen Eintrag hinzufügen",namePlaceholder:"Name (z.B. Bambu Lab - Plastik)",weight:"Gewicht",type:"Typ",default:"Standard",custom:"Benutzerdefiniert",noMatch:"Keine Einträge entsprechen Ihrer Suche",empty:"Keine Einträge im Katalog",deleteEntry:"Eintrag löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',resetCatalog:"Katalog zurücksetzen",resetConfirm:"Katalog auf Standardwerte zurücksetzen? Alle benutzerdefinierten Einträge werden entfernt.",loadFailed:"Spulenkatalog konnte nicht geladen werden",nameWeightRequired:"Name und Gewicht sind erforderlich",entryAdded:"Eintrag hinzugefügt",addFailed:"Eintrag konnte nicht hinzugefügt werden",entryUpdated:"Eintrag aktualisiert",updateFailed:"Eintrag konnte nicht aktualisiert werden",entryDeleted:"Eintrag gelöscht",deleteFailed:"Eintrag konnte nicht gelöscht werden",resetSuccess:"Katalog auf Standardwerte zurückgesetzt",resetFailed:"Katalog konnte nicht zurückgesetzt werden",exported:"{{count}} Einträge exportiert",imported:"{{added}} Einträge importiert ({{skipped}} übersprungen)",importFailed:"Import fehlgeschlagen: ungültiges JSON-Format",exportTooltip:"Katalog als JSON exportieren",importTooltip:"Katalog aus JSON importieren",resetTooltip:"Auf Standardwerte zurücksetzen"},colorCatalog:{title:"Farbkatalog",description:"Filamentfarben nach Hersteller/Material. Wird für die automatische Farbsuche beim Hinzufügen von Spulen verwendet.",searchColors:"Farben durchsuchen...",allManufacturers:"Alle Hersteller",addNewColor:"Neue Farbe hinzufügen",manufacturer:"Hersteller",colorName:"Farbname",hex:"Hex",materialOptional:"Material (optional)",showing:"{{filtered}} von {{total}} Farben angezeigt",noMatch:"Keine Farben entsprechen Ihrer Suche",empty:"Keine Farben im Katalog",deleteColor:"Farbe löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',resetCatalog:"Farbkatalog zurücksetzen",resetConfirm:"Katalog auf Standardwerte zurücksetzen? Alle benutzerdefinierten Farben werden entfernt.",sync:"Sync",starting:"Starten...",syncTooltip:"Von FilamentColors.xyz synchronisieren (2000+ Farben)",loadFailed:"Farbkatalog konnte nicht geladen werden",fieldsRequired:"Hersteller, Farbname und Hex-Farbe sind erforderlich",colorAdded:"Farbe hinzugefügt",addFailed:"Farbe konnte nicht hinzugefügt werden",colorUpdated:"Farbe aktualisiert",updateFailed:"Farbe konnte nicht aktualisiert werden",colorDeleted:"Farbe gelöscht",deleteFailed:"Farbe konnte nicht gelöscht werden",resetSuccess:"Farbkatalog auf Standardwerte zurückgesetzt",resetFailed:"Katalog konnte nicht zurückgesetzt werden",syncUpToDate:"Bereits aktuell ({{count}} Farben geprüft)",syncComplete:"{{added}} neue Farben hinzugefügt ({{skipped}} bereits vorhanden)",syncError:"Sync-Fehler",syncFailed:"Synchronisierung von FilamentColors.xyz fehlgeschlagen",exported:"{{count}} Farben exportiert",imported:"{{added}} Farben importiert ({{skipped}} übersprungen)",importFailed:"Import fehlgeschlagen: ungültiges JSON-Format"}},notification:{printStarted:{title:"Druck gestartet",body:"{{printer}}: {{filename}} wird gedruckt"},printCompleted:{title:"Druck abgeschlossen",body:"{{printer}}: {{filename}} erfolgreich abgeschlossen"},printFailed:{title:"Druck fehlgeschlagen",body:"{{printer}}: {{filename}} ist fehlgeschlagen"},printStopped:{title:"Druck gestoppt",body:"{{printer}}: {{filename}} wurde gestoppt"},printProgress:{title:"Druckfortschritt",body:"{{printer}}: {{filename}} ist zu {{percent}}% abgeschlossen"},printerOffline:{title:"Drucker offline",body:"{{printer}} ist offline"},printerError:{title:"Druckerfehler",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filament niedrig",body:"{{printer}}: Filament geht zur Neige"},maintenanceDue:{title:"Wartung fällig",body:"{{printer}}: {{items}} benötigen Aufmerksamkeit"}},errors:{generic:"Etwas ist schiefgelaufen",networkError:"Netzwerkfehler. Bitte überprüfen Sie Ihre Verbindung.",notFound:"Nicht gefunden",unauthorized:"Nicht autorisiert",serverError:"Serverfehler",validationError:"Bitte überprüfen Sie Ihre Eingabe",printerConnectionFailed:"Verbindung zum Drucker fehlgeschlagen",saveFailed:"Speichern fehlgeschlagen",deleteFailed:"Löschen fehlgeschlagen",loadFailed:"Laden der Daten fehlgeschlagen"},hmsErrors:{title:"Fehler - {{name}}",noErrors:"Keine Fehler",viewOnWiki:"Im Bambu Lab Wiki ansehen",clearInstructions:"Löschen Sie die Fehler am Drucker, um sie hier zu entfernen.",clearErrors:"Fehler löschen",clearSuccess:"HMS-Fehler gelöscht",clearFailed:"HMS-Fehler konnten nicht gelöscht werden"},mqttDebug:{title:"MQTT-Debug-Protokoll",searchPlaceholder:"Topic oder Payload suchen...",noMessages:"Noch keine Nachrichten protokolliert",startLoggingHint:'Klicken Sie auf "Protokollierung starten", um MQTT-Nachrichten aufzuzeichnen',noMessagesMatch:"Keine Nachrichten entsprechen Ihrem Filter",adjustFilterHint:"Versuchen Sie, Ihre Such- oder Filterkriterien anzupassen",incoming:"Eingehend",outgoing:"Ausgehend",loggingStopped:"Protokollierung gestoppt",loggingActive:"Protokollierung aktiv - Nachrichten werden automatisch aktualisiert",startLogging:"Protokollierung starten",stopLogging:"Protokollierung stoppen",clearLog:"Protokoll löschen",topic:"Topic",timestamp:"Zeitstempel",direction:"Richtung",all:"Alle"},printerFiles:{title:"Dateimanager",storageUsed:"Belegt:",storageFree:"Frei:",filterPlaceholder:"Dateien filtern...",deleteButton:"Löschen",deleteFiles:"{{count}} Dateien löschen",deleteFileConfirm:'"{{name}}" löschen? Dies kann nicht rückgängig gemacht werden.',deleteFilesConfirm:"{{count}} ausgewählte Dateien löschen? Dies kann nicht rückgängig gemacht werden.",noFiles:"Keine Dateien auf dem Drucker",loadingFiles:"Dateien werden geladen...",failedToLoad:"Dateien konnten nicht geladen werden",toast:{filesDeleted:"{{count}} Datei(en) gelöscht",deleteFailed:"Löschen fehlgeschlagen: {{error}}"}},confirm:{delete:"Möchten Sie dies wirklich löschen?",unsavedChanges:"Sie haben ungespeicherte Änderungen. Möchten Sie wirklich verlassen?",clearQueue:"Möchten Sie die Warteschlange wirklich leeren?"},login:{title:"Bambuddy Anmeldung",subtitle:"Melden Sie sich bei Ihrem Konto an",username:"Benutzername",usernamePlaceholder:"Benutzername eingeben",usernameOrEmail:"Benutzername oder E-Mail",usernameOrEmailPlaceholder:"Benutzername oder @ E-Mail",password:"Passwort",passwordPlaceholder:"Passwort eingeben",signIn:"Anmelden",signingIn:"Anmeldung läuft...",forgotPassword:"Passwort vergessen?",loginSuccess:"Erfolgreich angemeldet",loginFailed:"Anmeldung fehlgeschlagen",enterCredentials:"Bitte Benutzername und Passwort eingeben",forgotPasswordTitle:"Passwort vergessen",forgotPasswordMessage:"Wenn Sie Ihr Passwort vergessen haben, wenden Sie sich bitte an Ihren Systemadministrator.",forgotPasswordEmailMessage:"Geben Sie Ihre E-Mail-Adresse ein und wir senden Ihnen ein neues Passwort.",emailAddress:"E-Mail-Adresse",emailPlaceholder:"ihre.email@beispiel.de",cancel:"Abbrechen",sending:"Wird gesendet...",sendResetEmail:"Zurücksetzungs-E-Mail senden",howToReset:"So setzen Sie Ihr Passwort zurück:",resetStep1:"Kontaktieren Sie Ihren Bambuddy-Administrator",resetStep2:"Bitten Sie ihn, Ihr Passwort in der Benutzerverwaltung zurückzusetzen",resetStep3:"Er kann ein neues temporäres Passwort für Sie festlegen",resetStep4:"Melden Sie sich mit dem neuen Passwort an und ändern Sie es in den Einstellungen",gotIt:"Verstanden"},setup:{title:"Bambuddy Einrichtung",subtitle:"Konfigurieren Sie die Authentifizierung für Ihre Bambuddy-Instanz",enableAuth:"Authentifizierung aktivieren",adminAccount:"Admin-Konto",adminAccountDesc:"Wenn bereits Admin-Benutzer existieren, wird die Authentifizierung mit den vorhandenen Admin-Konten aktiviert. Lassen Sie die Felder unten leer, um vorhandene Admins zu verwenden, oder geben Sie neue Anmeldedaten ein, um einen neuen Admin-Benutzer zu erstellen.",adminUsername:"Admin-Benutzername",adminPassword:"Admin-Passwort",optionalIfAdminExists:"(optional, wenn Admin-Benutzer existieren)",adminUsernamePlaceholder:"Admin-Benutzernamen eingeben (optional)",adminPasswordPlaceholder:"Admin-Passwort eingeben (optional)",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Admin-Passwort bestätigen",settingUp:"Einrichtung läuft...",completeSetup:"Einrichtung abschließen",toast:{authEnabledAdminCreated:"Authentifizierung aktiviert und Admin-Benutzer erstellt",authEnabledExistingAdmins:"Authentifizierung mit vorhandenen Admin-Benutzern aktiviert",setupCompleted:"Einrichtung abgeschlossen",enterBothCredentials:"Bitte geben Sie sowohl Admin-Benutzernamen als auch Passwort ein, oder lassen Sie beide leer, um vorhandene Admin-Benutzer zu verwenden",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein"}},changePassword:{title:"Passwort ändern",currentPassword:"Aktuelles Passwort",currentPasswordPlaceholder:"Aktuelles Passwort eingeben",newPassword:"Neues Passwort",newPasswordPlaceholder:"Neues Passwort eingeben (min. 6 Zeichen)",confirmPassword:"Neues Passwort bestätigen",confirmPasswordPlaceholder:"Neues Passwort bestätigen",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein",changing:"Wird geändert...",success:"Passwort erfolgreich geändert",failed:"Passwortänderung fehlgeschlagen"},plateAlert:{title:"Druck pausiert!",message:"Objekte auf dem Druckbett erkannt. Der Druck wurde automatisch pausiert. Bitte räumen Sie das Druckbett und setzen Sie den Druck fort.",understand:"Verstanden"},camera:{title:"Kameraansicht",invalidPrinterId:"Ungültige Drucker-ID",live:"Live",snapshot:"Schnappschuss",restartStream:"Stream neu starten",refreshSnapshot:"Schnappschuss aktualisieren",fullscreen:"Vollbild",exitFullscreen:"Vollbild beenden",connectingToCamera:"Verbinde mit Kamera...",capturingSnapshot:"Schnappschuss wird aufgenommen...",connectionLost:"Verbindung verloren",connectionFailed:"Kameraverbindung fehlgeschlagen",reconnecting:"Neuverbindung in {{countdown}}s... (Versuch {{attempt}}/{{max}})",reconnectNow:"Jetzt verbinden",cameraUnavailable:"Kamera nicht verfügbar",cameraUnavailableDesc:"Stellen Sie sicher, dass der Drucker eingeschaltet und verbunden ist.",noCamera:"Keine Kamera verfügbar",retry:"Erneut versuchen",cameraStream:"Kamera-Stream",zoomOut:"Verkleinern",zoomIn:"Vergrößern",resetZoom:"Zoom zurücksetzen",recording:"Aufnahme",startRecording:"Aufnahme starten",stopRecording:"Aufnahme stoppen",chamberLight:"Kammerbeleuchtung umschalten"},groups:{title:"Gruppenverwaltung",subtitle:"Berechtigungsgruppen für Zugriffskontrolle verwalten",backToSettings:"Zurück zu Einstellungen",createGroup:"Gruppe erstellen",noPermission:"Sie haben keine Berechtigung, auf diese Seite zuzugreifen.",system:"System",noDescription:"Keine Beschreibung",usersCount:"{{count}} Benutzer",permissionsCount:"{{count}} Berechtigungen",edit:"Bearbeiten",delete:"Löschen",toast:{created:"Gruppe erfolgreich erstellt",updated:"Gruppe erfolgreich aktualisiert",deleted:"Gruppe erfolgreich gelöscht",enterGroupName:"Bitte geben Sie einen Gruppennamen ein"},modal:{editGroup:"Gruppe bearbeiten",createGroup:"Gruppe erstellen",cancel:"Abbrechen",saving:"Speichern...",creating:"Erstellen...",saveChanges:"Änderungen speichern"},form:{groupName:"Gruppenname",groupNamePlaceholder:"Gruppennamen eingeben",systemGroupWarning:"Systemgruppennamen können nicht geändert werden",description:"Beschreibung",descriptionPlaceholder:"Beschreibung eingeben (optional)",permissions:"Berechtigungen ({{count}} ausgewählt)"},deleteModal:{title:"Gruppe löschen",message:"Sind Sie sicher, dass Sie diese Gruppe löschen möchten? Benutzer in dieser Gruppe verlieren diese Berechtigungen.",confirm:"Gruppe löschen"},editor:{title:"Gruppe bearbeiten",createTitle:"Gruppe erstellen",search:"Berechtigungen suchen...",selectAll:"Alle auswählen",clearAll:"Alle abwählen",permissionsSelected:"{{count}} ausgewählt",noResults:"Keine Berechtigungen entsprechen Ihrer Suche"}},users:{title:"Benutzerverwaltung",subtitle:"Benutzer und deren Zugriff auf Ihre Bambuddy-Instanz verwalten",backToSettings:"Zurück zu Einstellungen",createUser:"Benutzer erstellen",noPermission:"Sie haben keine Berechtigung, auf diese Seite zuzugreifen.",admin:"Admin",noGroups:"Keine Gruppen",active:"Aktiv",inactive:"Inaktiv",edit:"Bearbeiten",delete:"Löschen",system:"System",noGroupsAvailable:"Keine Gruppen verfügbar",table:{username:"Benutzername",groups:"Gruppen",status:"Status",actions:"Aktionen"},toast:{created:"Benutzer erfolgreich erstellt",updated:"Benutzer erfolgreich aktualisiert",deleted:"Benutzer erfolgreich gelöscht",fillRequired:"Bitte füllen Sie alle Pflichtfelder aus",passwordsDoNotMatch:"Passwörter stimmen nicht überein",passwordTooShort:"Passwort muss mindestens 6 Zeichen lang sein"},modal:{createUser:"Benutzer erstellen",editUser:"Benutzer bearbeiten",cancel:"Abbrechen",creating:"Erstellen...",saving:"Speichern...",saveChanges:"Änderungen speichern",advancedAuthSubtitle:"mit erweiterter Authentifizierung"},form:{username:"Benutzername",usernamePlaceholder:"Benutzernamen eingeben",email:"E-Mail",emailPlaceholder:"benutzer@beispiel.de",password:"Passwort",passwordPlaceholder:"Passwort eingeben",confirmPassword:"Passwort bestätigen",confirmPasswordPlaceholder:"Passwort bestätigen",newPasswordPlaceholder:"Neues Passwort eingeben",confirmNewPasswordPlaceholder:"Neues Passwort bestätigen",leaveBlankToKeep:"leer lassen, um das aktuelle zu behalten",groups:"Gruppen",optional:"optional",autoGeneratedPassword:"Ein sicheres Passwort wird automatisch generiert und per E-Mail an den Benutzer gesendet.",passwordManagedByAdvancedAuth:'Das Passwort wird durch erweiterte Authentifizierung verwaltet. Verwenden Sie "Passwort zurücksetzen", um ein neues Passwort per E-Mail an den Benutzer zu senden.',resetPassword:"Passwort zurücksetzen",resettingPassword:"Passwort wird zurückgesetzt..."},deleteModal:{title:"Benutzer löschen",message:"Sind Sie sicher, dass Sie diesen Benutzer löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",confirm:"Benutzer löschen"}},streamOverlay:{title:"Stream-Overlay",invalidPrinterId:"Ungültige Drucker-ID",cameraStream:"Kamera-Stream",progress:"Fortschritt",eta:"ETA",printerIdle:"Drucker ist inaktiv",printerOffline:"Drucker offline",status:{printing:"Druckt",paused:"Pausiert",finished:"Fertig",failed:"Fehlgeschlagen",idle:"Inaktiv",unknown:"Unbekannt"}},profiles:{title:"Profile",subtitle:"Verwalten Sie Ihre Slicer-Voreinstellungen und Druckvorschub-Kalibrierungen",tabs:{cloud:"Cloud-Profile",local:"Lokale Profile",kprofiles:"K-Profile"},localProfiles:{title:"Lokale Profile",subtitle:"Slicer-Voreinstellungen aus OrcaSlicer importieren und verwalten",import:"Profile importieren",importDesc:".bbscfg-, .bbsflmt-, .orca_filament-, .zip- oder .json-Dateien hier ablegen",importing:"Importiere...",search:"Lokale Voreinstellungen durchsuchen...",noPresets:"Noch keine lokalen Voreinstellungen",badge:"Lokal",edit:"Bearbeiten",delete:"Löschen",cancel:"Abbrechen",deleteConfirmTitle:"Voreinstellung löschen",deleteConfirm:"Möchten Sie diese Voreinstellung wirklich löschen? Dies kann nicht rückgängig gemacht werden.",source:"Quelle",inheritsFrom:"Erbt von",filamentType:"Typ",vendor:"Hersteller",compatiblePrinters:"Drucker",nozzleTemp:"Düsentemperatur",cost:"Kosten",density:"Dichte",pressureAdvance:"Druckvorschub",filament:"Filament",process:"Prozess",printer:"Drucker",toast:{importSuccess:"{{count}} Voreinstellung(en) importiert",importSkipped:"{{count}} Voreinstellung(en) übersprungen (Duplikate)",importError:"{{count}} Fehler beim Import",deleted:"Voreinstellung gelöscht",updated:"Voreinstellung aktualisiert"}},connectedAs:"Verbunden als",logout:"Abmelden",noLogoutPermission:"Sie haben keine Berechtigung zum Abmelden",failedToLoad:"Profile konnten nicht geladen werden",retry:"Erneut versuchen",time:{justNow:"Gerade eben",minsAgo:"vor {{count}}m",hoursAgo:"vor {{count}}h",daysAgo:"vor {{count}}d"},toast:{loggedOut:"Abgemeldet"},login:{title:"Mit Bambu Cloud verbinden",subtitle:"Synchronisieren Sie Ihre Slicer-Voreinstellungen geräteübergreifend",email:"E-Mail",password:"Passwort",region:"Region",regionGlobal:"Global",regionChina:"China",verificationCode:"Bestätigungscode",totpCode:"Authenticator-Code",checkEmail:"Prüfen Sie Ihre E-Mail ({{email}}) für einen 6-stelligen Code",enterTotpHint:"Geben Sie den 6-stelligen Code aus Ihrer Authenticator-App ein",accessToken:"Zugriffstoken",accessTokenHint:"Fügen Sie Ihr Bambu Lab Zugriffstoken ein (aus Bambu Studio)",back:"Zurück",loginButton:"Anmelden",verifyButton:"Bestätigen",setTokenButton:"Token setzen",useToken:"Stattdessen Zugriffstoken verwenden",useEmail:"Stattdessen mit E-Mail anmelden",toast:{loggedIn:"Erfolgreich angemeldet",codeSent:"Bestätigungscode an Ihre E-Mail gesendet",enterTotp:"Geben Sie den Code aus Ihrer Authenticator-App ein",tokenSet:"Token erfolgreich gesetzt"}},presets:{myPreset:"Mein Profil (bearbeitbar)",duplicate:"Duplizieren",editable:"Bearbeitbar",failedToLoadDetails:"Profil-Details konnten nicht geladen werden",deleteConfirm:"Dieses Profil löschen?",deleteWarning:'"{{name}}" wird dauerhaft aus Bambu Cloud gelöscht. Dies kann nicht rückgängig gemacht werden.',noDuplicatePermission:"Sie haben keine Berechtigung zum Duplizieren von Profilen",noEditPermission:"Sie haben keine Berechtigung zum Bearbeiten von Profilen",noDeletePermission:"Sie haben keine Berechtigung zum Löschen von Profilen",types:{filament:"Filament-Profil",printer:"Drucker-Profil",process:"Prozess-Profil"},toast:{deleted:"Profil gelöscht",created:"Profil erstellt",updated:"Profil aktualisiert",duplicated:"Profil dupliziert",fieldAdded:'Feld "{{key}}" hinzugefügt',exported:"Profil exportiert"},baseLabel:"Basis: {{name}}",currentLabel:"Aktuell: {{name}}",newPreset:"Neues Profil",editPreset:"Profil bearbeiten",duplicatePreset:"Profil duplizieren",createNewPreset:"Neues Profil erstellen",customizeSettings:"Passen Sie die Einstellungen für Ihr neues Profil an",compareWithBase:"Mit Basis-Profil vergleichen",compare:"Vergleichen",basePreset:"Basis-Profil",selectBasePreset:"Basis-Profil auswählen...",presetName:"Profilname",myCustomPreset:"Mein eigenes Profil",inheritsFrom:"Erbt von",dropJsonToImport:"JSON zum Importieren ablegen",tabs:{common:"Allgemein",allFields:"Alle Felder"},availableFields:"Verfügbare Felder",searchFieldsPlaceholder:"Felder suchen...",noMatchingFields:"Keine passenden Felder",allFieldsAdded:"Alle Felder hinzugefügt",addCustomField:"Eigenes Feld hinzufügen",yourOverrides:"Ihre Überschreibungen",noOverridesYet:"Noch keine Überschreibungen",clickFieldsToAdd:"Klicken Sie links auf Felder, um sie hinzuzufügen",saveAsTemplate:"Als Vorlage speichern",jsonTip:"Tipp: Ziehen Sie eine .json-Datei auf dieses Fenster, um Einstellungen zu importieren"},cloudView:{searchPlaceholder:"Profile suchen...",templates:"Vorlagen",refresh:"Aktualisieren",newPreset:"Neues Profil",clearFilters:"Filter zurücksetzen",compareMode:"Vergleichsmodus",selectAnotherPreset:"Wählen Sie ein weiteres {{type}}-Profil",clickTwoPresets:"Klicken Sie auf zwei Profile des gleichen Typs zum Vergleichen",selectFirst:"1. Erstes auswählen",selectSecond:"2. Zweites auswählen",compareNow:"Jetzt vergleichen",lastSynced:"Zuletzt synchronisiert:",showingCount:"{{showing}} von {{total}} Profilen",noPresetsFound:"Keine Profile gefunden",columns:{filament:"Filament",process:"Prozess",printer:"Drucker"},noFilamentPresets:"Keine Filament-Profile",noProcessPresets:"Keine Prozess-Profile",noPrinterPresets:"Keine Drucker-Profile",filters:{type:"Typ",owner:"Besitzer",printer:"Drucker",nozzle:"Düse",filament:"Filament",layer:"Schicht",all:"Alle",myPresets:"Meine Profile",builtIn:"Voreingestellt",process:"Prozess"},noTemplatesPermission:"Sie haben keine Berechtigung, Vorlagen zu verwalten",noRefreshPermission:"Sie haben keine Berechtigung, Profile zu aktualisieren",noCreatePermission:"Sie haben keine Berechtigung, Profile zu erstellen"},templates:{title:"Schnellvorlagen",noTemplates:"Noch keine Vorlagen",createFirst:"Erstellen Sie Vorlagen aus dem Preset-Editor",typeFilter:"Typ:",deleteTitle:"Vorlage löschen",deleteWarning:"Diese Aktion kann nicht rückgängig gemacht werden",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',namePlaceholder:"Vorlagenname",descriptionPlaceholder:"Beschreibung",settingsJson:"Einstellungen (JSON)",fieldsCount:"{{count}} Felder",shownInModals:"In Dialogen angezeigt",hiddenInModals:"In Dialogen ausgeblendet",apply:"Anwenden",toast:{deleted:"Vorlage gelöscht",updated:"Vorlage aktualisiert",created:"Vorlage erstellt",applied:"Vorlage angewendet"}}},support:{debugLoggingActive:"Debug-Protokollierung ist aktiv",manageLogs:"Verwalten",collectItem7:"Drucker-Verbindungsstatus und Firmware-Versionen",collectItem8:"Integrationsstatus (Spoolman, MQTT, HA)",collectItem9:"Netzwerkschnittstellen (nur Subnetze)",collectItem10:"Python-Paketversionen",collectItem11:"Datenbankzustandsprüfungen",collectItem12:"Docker-Umgebungsdetails"},fileManager:{title:"Dateimanager",subtitle:"Organisieren und verwalten Sie Ihre Druckdateien",uploadFiles:"Dateien hochladen",newFolder:"Neuer Ordner",folderName:"Ordnername",folderNamePlaceholder:"z.B. Funktionsteile",renameFile:"Datei umbenennen",renameFolder:"Ordner umbenennen",moveFiles:"{{count}} Datei(en) verschieben",rootNoFolder:"Stammverzeichnis (Kein Ordner)",current:"aktuell",linkFolder:"Ordner verknüpfen",linkFolderDescription:'"{{name}}" mit einem Projekt oder Archiv verknüpfen für schnellen Zugriff.',project:"Projekt",archive:"Archiv",noProjectsFound:"Keine Projekte gefunden",noArchivesFound:"Keine Archive gefunden",unlink:"Verknüpfung aufheben",link:"Verknüpfen",dragDropFiles:"Dateien hierher ziehen",dropFilesHere:"Dateien hier ablegen",orClickToBrowse:"oder klicken zum Durchsuchen",allFileTypesSupported:"Alle Dateitypen werden unterstützt. ZIP-Dateien werden extrahiert.",zipFilesDetected:"ZIP-Dateien erkannt",zipExtractOptions:"ZIP-Dateien werden extrahiert. Wählen Sie, wie die Ordnerstruktur behandelt werden soll:",preserveZipStructure:"Ordnerstruktur aus ZIP beibehalten",createFolderFromZip:"Ordner aus ZIP-Dateiname erstellen",stlThumbnailGeneration:"STL-Vorschaubildgenerierung",zipMayContainStl:"ZIP-Dateien können STL-Dateien enthalten. Vorschaubilder können während der Extraktion generiert werden.",thumbnailsCanBeGenerated:"Vorschaubilder können für STL-Dateien generiert werden. Große Modelle benötigen möglicherweise mehr Zeit.",generateThumbnailsForStl:"Vorschaubilder für STL-Dateien generieren",threemfDetected:"3MF-Dateien erkannt",threemfExtractionInfo:"Druckermodell, Material, Farbe und Druckeinstellungen werden automatisch aus 3MF-Dateien extrahiert.",willBeExtracted:"Wird extrahiert",filesExtracted:"{{count}} Dateien extrahiert",uploadComplete:"Upload abgeschlossen: {{succeeded}} erfolgreich",uploadFailed:"{{count}} fehlgeschlagen",uploading:"Hochladen...",changeLink:"Verknüpfung ändern...",linkTo:"Verknüpfen mit...",linkToProjectOrArchive:"Mit Projekt oder Archiv verknüpfen",addToQueue:"Zur Warteschlange",schedulePrint:"Planen",generateThumbnail:"Vorschaubild generieren",generateThumbnails:"Vorschaubilder generieren",generateThumbnailsForMissing:"Vorschaubilder für STL-Dateien ohne Vorschau generieren",gridView:"Rasteransicht",listView:"Listenansicht",lowDiskSpaceWarning:"Warnung: Wenig Speicherplatz",lowDiskSpaceDetails:"Nur {{free}} frei von {{total}} gesamt. Schwellenwert ist auf {{threshold}} GB eingestellt.",files:"Dateien",folders:"Ordner",size:"Größe",free:"Frei",allFiles:"Alle Dateien",wrap:"Umbrechen",enableTextWrapping:"Textumbruch aktivieren",disableTextWrapping:"Textumbruch deaktivieren",dragToResizeTooltip:"Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen",searchFiles:"Dateien suchen...",allTypes:"Alle Typen",prints:"Drucke",ascending:"Aufsteigend",descending:"Absteigend",resultsCount:"{{showing}} von {{total}} Dateien",selectAll:"Alle auswählen",deselectAll:"Auswahl aufheben",selected:"{{count}} ausgewählt",adding:"Hinzufügen...",loadingFiles:"Dateien werden geladen...",folderIsEmpty:"Ordner ist leer",noFilesYet:"Noch keine Dateien",folderEmptyDescription:"Laden Sie Dateien hoch oder verschieben Sie Dateien in diesen Ordner.",noFilesDescription:"Laden Sie Dateien hoch, um Ihre Druckdateien zu organisieren.",noMatchingFiles:"Keine passenden Dateien",noMatchingFilesDescription:"Keine Dateien entsprechen Ihren aktuellen Such- oder Filterkriterien.",clearFilters:"Filter zurücksetzen",printedCount:"{{count}}x gedruckt",uploadedBy:"Hochgeladen von",deleteFolder:"Ordner löschen",deleteFile:"Datei löschen",deleteFilesCount:"{{count}} Dateien löschen",deleteFolderConfirm:"Möchten Sie diesen Ordner wirklich löschen? Alle Dateien darin werden ebenfalls gelöscht.",deleteFileConfirm:"Möchten Sie diese Datei wirklich löschen?",deleteFilesConfirm:"Möchten Sie {{count}} ausgewählte Dateien wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.",deleting:"Wird gelöscht...",noPermissionRenameFolder:"Sie haben keine Berechtigung, Ordner umzubenennen",noPermissionLinkFolder:"Sie haben keine Berechtigung, Ordner zu verknüpfen",noPermissionDeleteFolder:"Sie haben keine Berechtigung, Ordner zu löschen",noPermissionPrint:"Sie haben keine Berechtigung zum Drucken",noPermissionAddToQueue:"Sie haben keine Berechtigung, zur Warteschlange hinzuzufügen",noPermissionDownload:"Sie haben keine Berechtigung, Dateien herunterzuladen",noPermissionRenameFile:"Sie haben keine Berechtigung, diese Datei umzubenennen",noPermissionGenerateThumbnail:"Sie haben keine Berechtigung, Vorschaubilder zu generieren",noPermissionDeleteFile:"Sie haben keine Berechtigung, diese Datei zu löschen",noPermissionCreateFolder:"Sie haben keine Berechtigung, Ordner zu erstellen",noPermissionUpload:"Sie haben keine Berechtigung, Dateien hochzuladen",noPermissionMoveFiles:"Sie haben keine Berechtigung, Dateien zu verschieben",noPermissionDeleteFiles:"Sie haben keine Berechtigung, Dateien zu löschen",toast:{folderCreated:"Ordner erstellt",folderDeleted:"Ordner gelöscht",fileDeleted:"Datei gelöscht",filesDeleted:"{{count}} Dateien gelöscht",filesMoved:"Dateien verschoben",folderLinked:"Ordner verknüpft",folderUnlinked:"Ordnerverknüpfung aufgehoben",addedToQueue:"{{count}} Datei(en) zur Warteschlange hinzugefügt",addedToQueuePartial:"{{added}} Datei(en) hinzugefügt, {{failed}} fehlgeschlagen",failedToAddToQueue:"Fehler beim Hinzufügen: {{error}}",fileRenamed:"Datei umbenannt",folderRenamed:"Ordner umbenannt",thumbnailsGenerated:"{{count}} Vorschaubild(er) generiert",thumbnailsGeneratedPartial:"{{succeeded}} Vorschaubild(er) generiert, {{failed}} fehlgeschlagen",noStlMissingThumbnails:"Keine STL-Dateien ohne Vorschaubild",failedToGenerateThumbnails:"Fehler beim Generieren der Vorschaubilder: {{error}}",thumbnailGenerated:"Vorschaubild generiert",failedToGenerateThumbnail:"Fehler beim Generieren des Vorschaubildes: {{error}}"}},projects:{title:"Projekte",subtitle:"Organisieren und verfolgen Sie Ihre 3D-Druckprojekte",newProject:"Neues Projekt",editProject:"Projekt bearbeiten",deleteProject:"Projekt löschen",projectName:"Projektname",description:"Beschreibung",noProjects:"Noch keine Projekte",noProjectsFiltered:"Keine {{status}} Projekte",noProjectsFilteredHelp:"Sie haben keine {{status}} Projekte. Projekte werden hier angezeigt, wenn sich ihr Status ändert.",createFirst:"Erstellen Sie Ihr erstes Projekt, um verwandte Drucke zu organisieren, den Fortschritt zu verfolgen und Ihre Builds zu verwalten.",createFirstButton:"Erstes Projekt erstellen",create:"Erstellen",files:"Dateien",prints:"Drucke",plates:"Platten",parts:"Teile",lastModified:"Zuletzt geändert",deleteConfirm:"Möchten Sie dieses Projekt wirklich löschen? Archive und Warteschlangenelemente werden getrennt, aber nicht gelöscht.",addFiles:"Dateien hinzufügen",removeFile:"Datei entfernen",viewDetails:"Details anzeigen",namePlaceholder:"z.B. Voron 2.4 Build",descriptionPlaceholder:"Optionale Beschreibung...",color:"Farbe",targetPlates:"Ziel-Platten",targetPlatesPlaceholder:"z.B. 25",targetPlatesHelp:"Anzahl der Druckaufträge",targetParts:"Ziel-Teile",targetPartsPlaceholder:"z.B. 150",targetPartsHelp:"Benötigte Objekte insgesamt",tagsLabel:"Tags (kommagetrennt)",tagsPlaceholder:"z.B. voron, funktional, geschenk",dueDate:"Fälligkeitsdatum",priority:"Priorität",priorityLow:"Niedrig",priorityNormal:"Normal",priorityHigh:"Hoch",priorityUrgent:"Dringend",statusActive:"Aktiv",statusCompleted:"Abgeschlossen",statusArchived:"Archiviert",done:"Fertig",completed:"abgeschlossen",failed:"fehlgeschlagen",inQueue:"in Warteschlange",noPrintsYet:"Noch keine Drucke",printJobs:"Druckaufträge (Platten)",partsPrinted:"Gedruckte Teile",failedParts:"Fehlgeschlagene Teile",import:"Importieren",export:"Exportieren",importProject:"Projekt importieren",exportAll:"Alle Projekte exportieren",loading:"Projekte werden geladen...",noEditPermission:"Sie haben keine Berechtigung, Projekte zu bearbeiten",noDeletePermission:"Sie haben keine Berechtigung, Projekte zu löschen",noCreatePermission:"Sie haben keine Berechtigung, Projekte zu erstellen",noImportPermission:"Sie haben keine Berechtigung, Projekte zu importieren",noExportPermission:"Sie haben keine Berechtigung, Projekte zu exportieren",toast:{created:"Projekt erstellt",updated:"Projekt aktualisiert",deleted:"Projekt gelöscht",imported:"Projekt importiert",multipleImported:"{{count}} Projekte importiert",importFailed:"Import fehlgeschlagen",exported:"Projekte exportiert (nur Metadaten)"}},projectDetail:{notFound:"Projekt nicht gefunden",backToProjects:"Zurück zu Projekten",export:"Exportieren",exportProject:"Projekt exportieren",noExportPermission:"Sie haben keine Berechtigung, Projekte zu exportieren",noEditPermission:"Sie haben keine Berechtigung, Projekte zu bearbeiten",partOf:"Teil von:",priorityLabel:"Priorität:",noPrints:"Noch keine Drucke in diesem Projekt",status:{active:"Aktiv",completed:"Abgeschlossen",archived:"Archiviert"},priority:{low:"Niedrig",normal:"Normal",high:"Hoch",urgent:"Dringend"},dueDate:{overdue:"Überfällig",today:"Heute fällig",daysLeft:"{{count}} Tage übrig"},progress:{platesProgress:"Platten-Fortschritt",partsProgress:"Teile-Fortschritt",printJobs:"Druckaufträge",parts:"Teile",percentComplete:"{{percent}}% abgeschlossen",remaining:"{{count}} verbleibend"},stats:{printJobs:"Druckaufträge",total:"gesamt",failed:"{{count}} fehlgeschlagen",partsPrinted:"{{count}} Teile gedruckt",printTime:"Druckzeit",filamentUsed:"Filament verbraucht"},cost:{title:"Kostenverfolgung",filamentCost:"Filamentkosten",energy:"Energie",budget:"Budget",remaining:"Verbleibend"},subProjects:{title:"Unterprojekte ({{count}})"},notes:{title:"Notizen",noEditPermission:"Sie haben keine Berechtigung, Notizen zu bearbeiten",placeholder:"Notizen zu diesem Projekt hinzufügen...",empty:"Noch keine Notizen. Klicken Sie auf Bearbeiten, um Notizen hinzuzufügen."},files:{title:"Dateien",linkFolders:"Ordner aus dem Dateimanager verknüpfen",forQuickAccess:"für schnellen Zugriff auf dieses Projekt.",fileCount:"{{count}} Datei(en)",empty:"Keine Ordner verknüpft. Gehen Sie zum Dateimanager und verknüpfen Sie einen Ordner mit diesem Projekt."},bom:{title:"Stückliste",acquired:"{{completed}}/{{total}} beschafft",showAll:"Alle anzeigen",hideDone:"Erledigte ausblenden",addPart:"Teil hinzufügen",noAddPermission:"Sie haben keine Berechtigung, Teile hinzuzufügen",partNamePlaceholder:"Teilename (z.B. M3x8 Schrauben)",partName:"Teilename",qty:"Menge",price:"Preis ({{currency}})",sourcingUrlPlaceholder:"Bezugsquelle-URL (optional)",remarksPlaceholder:"Bemerkungen (optional)",deletePart:"Teil löschen",deleteConfirm:'Möchten Sie "{{name}}" wirklich löschen?',noUpdatePermission:"Sie haben keine Berechtigung, Teile zu aktualisieren",noEditPermission:"Sie haben keine Berechtigung, Teile zu bearbeiten",noDeletePermission:"Sie haben keine Berechtigung, Teile zu löschen",totalCost:"Gesamtkosten:",empty:"Keine Teile in der Stückliste. Fügen Sie Hardware, Elektronik oder andere Komponenten hinzu, um zu verfolgen, was beschafft werden muss."},timeline:{title:"Aktivitätsverlauf",empty:"Noch keine Aktivität."},template:{saveAsTemplate:"Als Vorlage speichern",noCreatePermission:"Sie haben keine Berechtigung, Vorlagen zu erstellen"},queue:{title:"Warteschlange",viewAll:"Alle anzeigen",printing:"{{count}} druckend",queued:"{{count}} in Warteschlange"},prints:{title:"Drucke ({{count}})"},toast:{projectUpdated:"Projekt aktualisiert",partAdded:"Teil hinzugefügt",partRemoved:"Teil entfernt",exportFailed:"Export fehlgeschlagen",projectExported:"Projekt exportiert",templateCreated:"Vorlage erstellt"}},system:{title:"Systeminformationen",version:"Version",uptime:"Laufzeit",cpuUsage:"CPU-Auslastung",memoryUsage:"Speicherauslastung",diskUsage:"Festplattenauslastung",networkInfo:"Netzwerkinformationen",logs:"Protokolle",debugMode:"Debug-Modus",enableDebug:"Debug-Protokollierung aktivieren",disableDebug:"Debug-Protokollierung deaktivieren",downloadLogs:"Protokolle herunterladen",clearLogs:"Protokolle löschen",dockerInfo:"Docker-Info",containerName:"Container-Name",imageName:"Image-Name",platform:"Plattform",architecture:"Architektur"},library:{title:"Filament-Bibliothek",addFilament:"Filament hinzufügen",editFilament:"Filament bearbeiten",deleteFilament:"Filament löschen",vendor:"Hersteller",material:"Material",color:"Farbe",kFactor:"K-Faktor",temperature:"Temperatur",noFilaments:"Keine Filamente in der Bibliothek",deleteConfirm:"Möchten Sie dieses Filament wirklich löschen?",importFromPrinter:"Vom Drucker importieren",exportToFile:"In Datei exportieren"},spoolman:{title:"Spoolman-Integration",enabled:"Spoolman aktiviert",url:"Spoolman URL",connected:"Verbunden",disconnected:"Nicht verbunden",testConnection:"Verbindung testen",sync:"Synchronisieren",syncing:"Synchronisiert...",lastSync:"Letzte Synchronisierung",linkToSpoolman:"Mit Spoolman verknüpfen",openInSpoolman:"In Spoolman öffnen",unlinkSpool:"Spule trennen",selectSpool:"Spule auswählen",noUnlinkedSpools:"Keine nicht verknüpften Spulen verfügbar",linkSuccess:"Spule erfolgreich mit Spoolman verknüpft",linkFailed:"Verknüpfung mit Spoolman fehlgeschlagen",spoolId:"Spulen-ID",fillSourceLabel:"(Spoolman)",weight:"Gewicht",remaining:"Verbleibend",disableWeightSync:"AMS-Gewichtsschätzung deaktivieren",disableWeightSyncDesc:"Verbleibende Kapazität nicht aus AMS-Schätzungen aktualisieren. Verwenden Sie dies, wenn Sie die Verbrauchserfassung von Spoolman gegenüber den prozentualen AMS-Schätzungen bevorzugen. Neue Spulen verwenden weiterhin die AMS-Schätzung als Anfangsgewicht.",reportPartialUsage:"Teilverbrauch bei fehlgeschlagenen Drucken melden",reportPartialUsageDesc:"Wenn ein Druck fehlschlägt oder abgebrochen wird, den geschätzten Filamentverbrauch bis zu diesem Zeitpunkt basierend auf dem Schichtfortschritt melden."},inventory:{title:"Spulen-Inventar",addSpool:"Spule hinzufügen",editSpool:"Spule bearbeiten",material:"Material",selectMaterial:"Material auswählen...",subtype:"Untertyp",brand:"Marke",searchBrand:"Marke suchen...",useCustomBrand:'"{{brand}}" verwenden',useCustomMaterial:"Benutzerdefiniertes Material verwenden: {{material}}",colorName:"Farbname",colorNamePlaceholder:"Jade White, Fire Red...",color:"Farbe",hexColor:"Hex-Farbe",pickColor:"Benutzerdefinierte Farbe wählen",labelWeight:"Nenngewicht",coreWeight:"Leergewicht der Spule",searchSpoolWeight:"Spulengewicht suchen...",weightUsed:"Verbraucht",currentWeight:"Restgewicht",measuredWeight:"Gemessenes Gewicht",costPerKg:"Kosten pro kg",measuredWeightError:"Das gemessene Gewicht muss zwischen {{min}}g und {{max}}g liegen.",slicerFilament:"Slicer-Filament",slicerFilamentName:"Slicer-Preset-Name",slicerPreset:"Slicer-Preset",searchPresets:"Filament-Presets suchen...",selectedPreset:"Ausgewählt",noPresetsFound:"Keine Presets gefunden",tempOverrides:"Temperatur-Überschreibungen",note:"Notiz",notePlaceholder:"Zusätzliche Notizen zu dieser Spule...",archive:"Archivieren",restore:"Wiederherstellen",noSpools:"Noch keine Spulen. Fügen Sie Ihre erste Spule hinzu.",noManualSpools:"Keine manuell hinzugefügten Spulen verfügbar. Fügen Sie zuerst eine Spule zum Inventar hinzu.",kProfiles:"K-Profile",addKProfile:"K-Profil hinzufügen",assignSpool:"Spule zuweisen",unassignSpool:"Zuweisung aufheben",assignSuccess:"Spule zugewiesen und AMS-Slot konfiguriert",assignFailed:"Spulenzuweisung fehlgeschlagen",selectSpool:"Wählen Sie eine Spule für diesen Slot",assigned:"Zugewiesen",assigning:"Wird zugewiesen...",searchSpools:"Spulen suchen...",allMaterials:"Alle Materialien",filterByBrand:"Nach Marke filtern...",showArchived:"Archivierte anzeigen",quickAdd:"Schnellerfassung (Lager)",quantity:"Menge",stock:"Lager",configured:"Konfiguriert",spoolsCreated:"{{count}} Spulen erstellt",spoolCreated:"Spule erstellt",spoolUpdated:"Spule aktualisiert",spoolDeleted:"Spule gelöscht",spoolArchived:"Spule archiviert",spoolRestored:"Spule wiederhergestellt",deleteConfirm:"Möchten Sie diese Spule wirklich löschen? Dies kann nicht rückgängig gemacht werden.",archiveConfirm:"Möchten Sie diese Spule wirklich archivieren?",advancedSettings:"Erweiterte Einstellungen",filamentInfoTab:"Filament-Info",paProfileTab:"PA-Profil",filamentInfo:"Filament",additional:"Zusätzlich",loadingPresets:"Cloud-Presets werden geladen...",cloudConnected:"Cloud verbunden",cloudNotConnected:"Cloud nicht verbunden (Standardwerte)",recentColors:"Zuletzt",searchColors:"Farben suchen...",searchResults:"Suchergebnisse",allColors:"Alle Farben",commonColors:"Häufige Farben",showLess:"Weniger",showAll:"Alle",noColorsFound:"Keine Farben gefunden",noResults:"Keine Ergebnisse",selectMaterialFirst:"Bitte zuerst ein Material im Filament-Info Tab auswählen.",noPrintersConfigured:"Keine Drucker konfiguriert. Fügen Sie Drucker hinzu.",matchingFilter:"Filter",anyBrand:"Jede Marke",anyVariant:"Jede Variante",autoSelect:"Auto-Auswahl",matches:"Treffer",match:"Treffer",noMatches:"Keine Treffer",connected:"Verbunden",offline:"Offline",printerOffline:"Drucker ist offline. Verbinden Sie ihn, um Kalibrierungsprofile anzuzeigen.",noKProfilesMatch:"Keine K-Profile stimmen mit dem gewählten Filament überein.",leftNozzle:"Linke Düse",rightNozzle:"Rechte Düse",profilesSelected:"Kalibrierungsprofil(e) ausgewählt",totalInventory:"Gesamtbestand",totalConsumed:"Gesamtverbrauch",byMaterial:"Nach Material",inPrinter:"Im Drucker",lowStock:"Niedriger Bestand",sinceTracking:"Seit Beginn der Erfassung",loadedInAms:"Im AMS/Ext geladen",remaining:"Verbleibend",lowStockThreshold:"<20% verbleibend",search:"Spulen suchen...",showing:"Zeige",to:"bis",of:"von",show:"Zeige",spools:"Spulen",spool:"Spule",page:"Seite",noSpoolsMatch:"Keine Ergebnisse",noSpoolsMatchDesc:"Versuchen Sie, Ihre Suche oder Filter anzupassen.",active:"Aktiv",archived:"Archiviert",all:"Alle",used:"Verwendet",new:"Neu",clearFilters:"Filter löschen",table:"Tabelle",cards:"Karten",net:"Netto",groupSimilar:"Gruppieren",groupedSpools:"{{count}} identische Spulen",groupedRows:"Zeilen",columns:"Spalten",configureColumns:"Spalten konfigurieren",configureColumnsDesc:"Ziehen zum Neuordnen oder Pfeile verwenden. Sichtbarkeit mit dem Augensymbol umschalten.",visible:"sichtbar",reset:"Zurücksetzen",cancel:"Abbrechen",applyChanges:"Änderungen anwenden",moveUp:"Nach oben",moveDown:"Nach unten",hideColumn:"Spalte ausblenden",showColumn:"Spalte einblenden",linkToSpool:"Mit Spule verknüpfen",tagLinked:"Tag mit Spule verknüpft",tagLinkFailed:"Tag-Verknüpfung fehlgeschlagen",tagAlreadyLinked:"Tag bereits mit anderer Spule verknüpft",unknownTag:"Unbekannter RFID-Tag erkannt",usageHistory:"Verbrauchshistorie",noUsageHistory:"Noch kein Verbrauch erfasst",printName:"Druckname",weightConsumed:"Verbrauchtes Gewicht",clearHistory:"Löschen",historyCleared:"Verbrauchshistorie gelöscht",fillSourceLabel:"(Inv)"},timelapse:{title:"Zeitraffer",create:"Zeitraffer erstellen",download:"Herunterladen",delete:"Löschen",preview:"Vorschau",frameRate:"Bildrate",quality:"Qualität",processing:"Wird verarbeitet...",noTimelapses:"Keine Zeitraffer verfügbar"},ams:{title:"AMS",slot:"Slot",empty:"Leer",emptySlot:"Leerer Slot",unknown:"Unbekannt",humidity:"Luftfeuchtigkeit",temperature:"Temperatur",filamentType:"Filamenttyp",filamentColor:"Farbe",remaining:"Verbleibend",history:"AMS-Verlauf",noHistory:"Kein Verlauf verfügbar",configureSlot:"Slot konfigurieren",externalSpool:"Externe Spule",profile:"Profil",kFactor:"K-Faktor",fill:"Füllstand",configure:"Konfigurieren",used:"verwendet",remainingUnit:"verbleibend"},printModal:{title:"Druck starten",selectPrinter:"Drucker auswählen",selectPlate:"Platte auswählen",filamentMapping:"Filamentzuordnung",totalCost:"Gesamtkosten:",printSettings:"Druckeinstellungen",bedLeveling:"Bett-Nivellierung",flowCalibration:"Fluss-Kalibrierung",vibrationCalibration:"Vibrations-Kalibrierung",layerInspection:"Erste-Schicht-Prüfung",timelapse:"Zeitraffer",startPrint:"Druck starten",addToQueue:"Zur Warteschlange hinzufügen",cancel:"Abbrechen",noPrintersAvailable:"Keine Drucker verfügbar",printerBusy:"Drucker ist beschäftigt",printerOffline:"Drucker ist offline",sameTypeDifferentColor:"Gleicher Typ, andere Farbe",filamentTypeNotLoaded:"Filamenttyp nicht geladen",openCalendar:"Kalender öffnen",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Linke Düse",rightNozzleTooltip:"Rechte Düse",filamentOverride:"Filament-Überschreibung",filamentOverrideHint:"Filamente für modellbasierte Zuweisung optional überschreiben. Der Planer wird gegen die ausgewählten Filamente statt der ursprünglichen 3MF-Werte abgleichen.",originalFilament:"Original",overrideWith:"Ersetzen mit",resetToOriginal:"Auf Original zurücksetzen"},backup:{title:"Sichern & Wiederherstellen",createBackup:"Sicherung erstellen",restoreBackup:"Sicherung wiederherstellen",restoreDescription:"Alle Daten aus einer Sicherungsdatei ersetzen",downloadBackup:"Sicherung herunterladen",uploadBackup:"Sicherung hochladen",lastBackup:"Letzte Sicherung",autoBackup:"Automatische Sicherung",backupNow:"Jetzt sichern",restoreWarning:"Warnung: Das Wiederherstellen einer Sicherung überschreibt alle aktuellen Daten.",includeArchives:"Archive einschließen",includeSettings:"Einstellungen einschließen",includeProfiles:"Profile einschließen",backupSuccess:"Sicherung erfolgreich erstellt",restoreSuccess:"Sicherung erfolgreich wiederhergestellt",backupFailed:"Sicherung fehlgeschlagen",restoreFailed:"Wiederherstellung fehlgeschlagen",restoreNote:"Virtueller Drucker wird während der Wiederherstellung gestoppt"},tags:{title:"Tags",addTag:"Tag hinzufügen",editTag:"Tag bearbeiten",deleteTag:"Tag löschen",tagName:"Tag-Name",tagColor:"Tag-Farbe",noTags:"Keine Tags",deleteConfirm:"Möchten Sie diesen Tag wirklich löschen?",manageTags:"Tags verwalten"},uploadModal:{title:"3MF-Dateien hochladen",dragDrop:"3MF-Dateien hierher ziehen",or:"oder",browseFiles:"Dateien durchsuchen",extractionInfo:"Das Druckermodell wird automatisch aus den 3MF-Datei-Metadaten extrahiert.",uploaded:"hochgeladen",failed:"fehlgeschlagen",uploading:"Wird hochgeladen...",upload:"Hochladen",uploadFailed:"Hochladen fehlgeschlagen"},editArchive:{title:"Archiv bearbeiten",name:"Name",namePlaceholder:"Druckname",printer:"Drucker",noPrinter:"Kein Drucker",project:"Projekt",noProject:"Kein Projekt",itemsPrinted:"Gedruckte Teile",itemsPrintedHelp:"Anzahl der in diesem Druckauftrag produzierten Teile",notes:"Notizen",notesPlaceholder:"Notizen zu diesem Druck hinzufügen...",externalLink:"Externer Link",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link zu Printables, Thingiverse oder anderer Quelle",tags:"Tags",tagsPlaceholder:"Tags hinzufügen...",addMoreTags:"Weitere Tags hinzufügen...",matchingTags:'Übereinstimmend mit "{{query}}"',existingTags:"Vorhandene Tags",clickToAdd:"(zum Hinzufügen klicken)",status:"Status",failureReason:"Fehlergrund",selectReason:"Grund auswählen...",photos:"Fotos des Druckergebnisses",photosHelp:"Klicken Sie auf + um Fotos Ihres Druckergebnisses hinzuzufügen",printResult:"Druckergebnis",saving:"Wird gespeichert...",failureReasons:{adhesionFailure:"Haftungsfehler",spaghettiDetached:"Spaghetti / Abgelöst",layerShift:"Schichtversatz",cloggedNozzle:"Verstopfte Düse",filamentRunout:"Filament aufgebraucht",warping:"Verformung",stringing:"Fadenziehen",underExtrusion:"Unterextrusion",powerFailure:"Stromausfall",userCancelled:"Vom Benutzer abgebrochen",other:"Sonstiges"},statuses:{completed:"Abgeschlossen",failed:"Fehlgeschlagen",aborted:"Abgebrochen",printing:"Druckt"}},kProfiles:{title:"K-Profile",noPrintersConfigured:"Keine Drucker konfiguriert",addPrinterInSettings:"Fügen Sie einen Drucker in den Einstellungen hinzu, um K-Profile zu verwalten",noActivePrinters:"Keine aktiven Drucker",enablePrinterConnection:"Aktivieren Sie eine Druckerverbindung, um K-Profile anzuzeigen",loadingProfiles:"Lade K-Profile...",printerOffline:"Drucker offline",printerOfflineDesc:"Der ausgewählte Drucker ist nicht verbunden. Schalten Sie ihn ein, um K-Profile anzuzeigen.",noMatchingProfiles:"Keine passenden Profile",noMatchingProfilesDesc:"Keine Profile entsprechen Ihren Suchkriterien",noKProfiles:"Keine K-Profile",noKProfilesDesc:"Keine Druckvorschub-Profile für {{diameter}}mm Düse gefunden",createFirstProfile:"Erstes Profil erstellen",printer:"Drucker",nozzle:"Düse",refresh:"Aktualisieren",addProfile:"Profil hinzufügen",export:"Exportieren",import:"Importieren",select:"Auswählen",selectAll:"Alle auswählen",delete:"Löschen",searchPlaceholder:"Nach Name oder Filament suchen...",allExtruders:"Alle Extruder",leftOnly:"Nur links",rightOnly:"Nur rechts",allFlow:"Alle Flusstypen",hfOnly:"Nur HF",sOnly:"Nur S",sortName:"Sortieren: Name",sortKValue:"Sortieren: K-Wert",sortFilament:"Sortieren: Filament",leftExtruder:"Linker Extruder",rightExtruder:"Rechter Extruder",modal:{addTitle:"K-Profil hinzufügen",editTitle:"K-Profil bearbeiten",profileName:"Profilname",profileNamePlaceholder:"Mein PLA-Profil",kValue:"K-Wert",kValuePlaceholder:"0,020",kValueHelp:"Typischer Bereich: 0,01 - 0,06 für PLA, 0,02 - 0,10 für PETG",filament:"Filament",selectFilament:"Filament auswählen...",noFilamentsHelp:"Keine Filamente gefunden. Erstellen Sie zuerst ein K-Profil in Bambu Studio.",flowType:"Flusstyp",highFlow:"High Flow",standard:"Standard",nozzleSize:"Düsengröße",extruder:"Extruder",extruders:"Extruder",left:"Links",right:"Rechts",notes:"Notizen (lokal gespeichert)",notesPlaceholder:"Notizen zu diesem Profil hinzufügen...",notesHelp:"Notizen werden in Bambuddy gespeichert, nicht auf dem Drucker",syncing:"Synchronisiert mit Drucker...",savingExtruder:"Speichern auf Extruder {{current}}/{{total}}...",pleaseWait:"Bitte warten"},deleteConfirm:{title:"Profil löschen",cannotUndo:"Dies kann nicht rückgängig gemacht werden",message:'Möchten Sie "{{name}}" wirklich vom Drucker löschen?'},bulkDelete:{title:"Profile löschen",cannotUndo:"Dies kann nicht rückgängig gemacht werden",message:"Möchten Sie wirklich {{count}} ausgewählte Profile vom Drucker löschen?"},toast:{profileSaved:"K-Profil gespeichert",profilesSaved:"K-Profil auf {{count}} Extrudern gespeichert",selectAtLeastOneExtruder:"Bitte wählen Sie mindestens einen Extruder aus",profileDeleted:"K-Profil gelöscht",profilesDeleted:"{{count}} Profile gelöscht",exportedProfiles:"{{count}} Profile exportiert",importedProfiles:"{{count}} von {{total}} Profilen importiert",noProfilesToExport:"Keine Profile zum Exportieren",invalidFileFormat:"Ungültiges Dateiformat",failedToParseImport:"Import-Datei konnte nicht gelesen werden",failedToSaveBatch:"K-Profile konnten nicht gespeichert werden",noteSaved:"Notiz gespeichert",failedToSaveNote:"Notiz konnte nicht gespeichert werden"},permission:{noRead:"Sie haben keine Berechtigung, Profile zu aktualisieren",noCreate:"Sie haben keine Berechtigung, Profile hinzuzufügen",noUpdate:"Sie haben keine Berechtigung, K-Profile zu aktualisieren",noDelete:"Sie haben keine Berechtigung, K-Profile zu löschen",noExport:"Sie haben keine Berechtigung, Profile zu exportieren",noImport:"Sie haben keine Berechtigung, Profile zu importieren"}},virtualPrinter:{title:"Virtueller Drucker",running:"Läuft",stopped:"Gestoppt",description:{default:"Aktiviere einen virtuellen Drucker, der in Bambu Studio und OrcaSlicer erscheint. Dateien, die an diesen Drucker gesendet werden, werden direkt archiviert ohne zu drucken.",proxy:"Aktiviere einen Proxy, der Slicer-Datenverkehr an einen echten Drucker weiterleitet, um Ferndruck über jedes Netzwerk zu ermöglichen."},enable:{title:"Virtuellen Drucker aktivieren",visibleInSlicer:'Sichtbar als "Bambuddy" in der Slicer-Erkennung',proxyingTo:"Proxy zu {{name}}",notActive:"Nicht aktiv"},model:{title:"Druckermodell",description:"Wähle welches Druckermodell emuliert werden soll.",restartWarning:"Das Ändern des Modells startet den virtuellen Drucker neu"},accessCode:{title:"Zugangscode",isSet:"Zugangscode ist gesetzt",notSet:"Kein Zugangscode gesetzt - erforderlich zum Aktivieren",placeholder:"8-Zeichen-Code eingeben",placeholderChange:"Neuen Code eingeben zum Ändern",hint:"Muss genau 8 Zeichen lang sein. Wird von Slicern zur Authentifizierung verwendet.",charCount:"({{count}}/8)"},targetPrinter:{title:"Zieldrucker",configured:"Proxy-Ziel konfiguriert",notConfigured:"Kein Zieldrucker ausgewählt - erforderlich für Proxy-Modus",placeholder:"Drucker auswählen...",hint:"Wähle den Drucker aus, an den der Slicer-Datenverkehr weitergeleitet werden soll. Der Drucker muss im LAN-Modus sein.",noPrinters:"Keine Drucker konfiguriert. Füge zuerst einen Drucker hinzu, um den Proxy-Modus zu verwenden."},remoteInterface:{title:"Netzwerkschnittstelle überschreiben",configured:"Schnittstellenüberschreibung aktiv",optional:"Optional - verwenden wenn die automatisch erkannte IP falsch ist (z.B. mehrere NICs, Docker, VPN)",placeholder:"Automatisch erkennen (Standard)...",hint:"Überschreibt die per SSDP beworbene und im TLS-Zertifikat verwendete IP-Adresse. Nützlich wenn Bambuddy mehrere Netzwerkschnittstellen hat."},mode:{title:"Modus",archive:"Archivieren",archiveDesc:"Dateien sofort archivieren",review:"Überprüfen",reviewDesc:"Vor dem Archivieren überprüfen",queue:"Warteschlange",queueDesc:"Archivieren und zur Warteschlange hinzufügen",proxy:"Proxy",proxyDesc:"An echten Drucker weiterleiten"},setupRequired:{title:"Einrichtung erforderlich",description:"Die virtuelle Druckerfunktion erfordert zusätzliche Systemkonfiguration, bevor sie funktioniert. Dies beinhaltet Portweiterleitung, Firewall-Regeln und plattformspezifische Einstellungen.",readGuide:"Lese die Einrichtungsanleitung vor dem Aktivieren"},howItWorks:{title:"So funktioniert es",step1:"Im selben LAN erscheinen virtuelle Drucker automatisch in deinem Slicer (Bambu Studio / OrcaSlicer). Aus anderen Netzwerken füge sie manuell per IP-Adresse und Zugangscode hinzu.",step2:'Im Archiv-, Überprüfungs- und Warteschlangen-Modus verwende die "Senden"-Funktion im Slicer, um 3MF-Dateien an Bambuddy zu senden. Der Slicer zeigt "Druck erfolgreich" — die Datei wird gespeichert, nicht gedruckt.',step3:"Im Proxy-Modus leitet der virtuelle Drucker den gesamten Datenverkehr an einen echten Drucker weiter — Drucke starten sofort wie bei einer direkten Verbindung."},status:{title:"Status-Details",printerName:"Druckername",model:"Modell",serialNumber:"Seriennummer",mode:"Modus",pendingFiles:"Ausstehende Dateien",targetPrinter:"Zieldrucker",ftpPort:"FTP-Port",mqttPort:"MQTT-Port",ftpConnections:"FTP-Verbindungen",mqttConnections:"MQTT-Verbindungen"},toast:{updated:"Virtuelle Druckereinstellungen aktualisiert",failedToUpdate:"Einstellungen konnten nicht aktualisiert werden",accessCodeRequired:"Bitte zuerst einen Zugangscode setzen",targetPrinterRequired:"Bitte zuerst einen Zieldrucker auswählen",bindIpRequired:"Bitte zuerst eine Bind-IP setzen",accessCodeEmpty:"Zugangscode darf nicht leer sein",accessCodeLength:"Zugangscode muss genau 8 Zeichen lang sein",created:"Virtueller Drucker erstellt",failedToCreate:"Virtueller Drucker konnte nicht erstellt werden",deleted:"Virtueller Drucker gelöscht",failedToDelete:"Virtueller Drucker konnte nicht gelöscht werden"},list:{title:"Virtuelle Drucker",add:"Hinzufügen",addFirst:"Virtuellen Drucker hinzufügen",empty:"Keine virtuellen Drucker konfiguriert. Fügen Sie einen hinzu, um zu beginnen."},bindIp:{title:"Bind-Interface",placeholder:"Interface auswählen...",hint:"Netzwerkinterface, an das dieser virtuelle Drucker gebunden wird. Muss pro Drucker eindeutig sein."},proxy:{accessCodeHint:"Im Proxy-Modus den Zugangscode des Zieldruckers im Slicer verwenden. Die Verbindung wird transparent zum echten Drucker weitergeleitet."},addDialog:{title:"Virtuellen Drucker hinzufügen",name:"Name",hint:"Sie können Zugangscode, Zieldrucker und andere Einstellungen nach dem Erstellen konfigurieren.",create:"Erstellen"},deleteConfirm:{title:"Virtuellen Drucker löschen",message:'Möchten Sie "{{name}}" wirklich löschen? Dies stoppt alle Dienste für diesen Drucker.'}},modelViewer:{openInSlicer:"Im Slicer öffnen",tabs:{model:"3D-Modell",gcode:"G-Code Vorschau"},notAvailable:"nicht verfügbar",notSliced:"nicht geslicet",plates:"Platten",allPlates:"Alle Platten",plateNumber:"Platte {{number}}",plateCount:"{{count}} Platte",plateCount_other:"{{count}} Platten",objectCount:"{{count}} Objekt",objectCount_other:"{{count}} Objekte",filamentCount:"{{count}} Filament",filamentCount_other:"{{count}} Filamente",eta:"ETA {{minutes}} Min",noPreview:"Keine Vorschau für diese Datei verfügbar",pagination:{pageOf:"Seite {{current}} von {{total}}",prev:"Zurück",next:"Weiter"},errors:{failedToLoad:"Datei konnte nicht geladen werden",noMeshes:"Keine Meshes in 3MF-Datei gefunden",unsupportedFormat:"Nicht unterstütztes Dateiformat"}},maintenanceDescriptions:{lubricateCarbonRods:"Schmiermittel auf Karbonstäbe für sanfte Bewegung auftragen",lubricateRails:"Schmiermittel auf Linearschienen für sanfte Bewegung auftragen",cleanNozzle:"Hotend und Düse reinigen, um Verstopfungen zu verhindern",checkBelts:"Riemenspannung für präzise Drucke überprüfen",cleanBuildPlate:"Druckplatte für bessere Haftung reinigen",checkExtruder:"Extruderzahnräder auf Verschleiß prüfen",checkCooling:"Sicherstellen, dass Lüfter ordnungsgemäß funktionieren",generalInspection:"Allgemeine Druckerinspektion",cleanCarbonRods:"Karbonstäbe reinigen, um Reibung zu reduzieren",cleanLinearRails:"Linearschienen abwischen, um Staub und Schmutz zu entfernen",checkPtfeTube:"PTFE-Schlauch auf Verschleiß oder Beschädigung prüfen",replaceHepaFilter:"HEPA-Filter für Luftqualität ersetzen",replaceCarbonFilter:"Aktivkohlefilter ersetzen",lubricateLeftNozzleRail:"Linke Düsenschiene schmieren (H2-Serie)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Plug-Admin-Seite öffnen",deleteSmartPlug:"Smart Plug löschen",turnOnSmartPlug:"Smart Plug einschalten",turnOffSmartPlug:"Smart Plug ausschalten",turnOn:"Einschalten",turnOff:"Ausschalten",addSmartPlug:{scanningNetwork:"Netzwerk wird durchsucht...",chooseEntity:"Entität auswählen...",connectionFailed:"Verbindung fehlgeschlagen",searchEntities:"Entitäten suchen...",searchPowerSensors:"Leistungssensoren suchen...",searchEnergySensors:"Energiesensoren suchen...",placeholders:{plugName:"Wohnzimmer Steckdose",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Gleich wie Leistungs-Topic oder anders"}}},richTextEditor:{bold:"Fett",italic:"Kursiv",underline:"Unterstrichen",bulletList:"Aufzählungsliste",numberedList:"Nummerierte Liste",alignLeft:"Linksbündig",alignCenter:"Zentriert",alignRight:"Rechtsbündig",addLink:"Link hinzufügen",removeLink:"Link entfernen"},externalLinks:{noLinksConfigured:"Keine externen Links konfiguriert",deleteLink:"Link löschen",removeCustomIcon:"Benutzerdefiniertes Symbol entfernen",openInNewTab:"In neuem Tab öffnen",placeholders:{linkName:"Mein Link"}},keyboardShortcuts:{title:"Tastaturkürzel",navigation:"Navigation",archivesSection:"Archive",kProfilesSection:"K-Profile",generalSection:"Allgemein",shortcuts:{goToPrinters:"Zu Drucker gehen",goToArchives:"Zu Archiv gehen",goToQueue:"Zur Warteschlange gehen",goToStats:"Zu Statistiken gehen",goToProfiles:"Zu Cloud-Profilen gehen",goToSettings:"Zu Einstellungen gehen",focusSearch:"Suche fokussieren",openUploadModal:"Upload-Modal öffnen",clearSelection:"Auswahl löschen / Eingabe aufheben",contextMenu:"Kontextmenü auf Karten",refreshProfiles:"Profile aktualisieren",newProfile:"Neues Profil",exitSelectionMode:"Auswahlmodus beenden",showHelp:"Diese Hilfe anzeigen"},footer:"Drücken Sie Esc oder klicken Sie außerhalb, um zu schließen"},notificationLog:{title:"Benachrichtigungsprotokoll",events:{printStarted:"Druck gestartet",printComplete:"Druck abgeschlossen",printFailed:"Druck fehlgeschlagen",printStopped:"Druck gestoppt",progress:"Fortschritt",printerOffline:"Drucker offline",printerError:"Druckerfehler",lowFilament:"Wenig Filament",maintenanceDue:"Wartung fällig",test:"Test"},timeAgo:{justNow:"Gerade eben",minutesAgo:"vor {{minutes}}m",hoursAgo:"vor {{hours}}h"}},restoreBackup:{title:"Backup wiederherstellen",restoring:"Wird wiederhergestellt...",restoreComplete:"Wiederherstellung abgeschlossen",restoreFailed:"Wiederherstellung fehlgeschlagen",importSettings:"Einstellungen aus Backup-Datei importieren",pleaseWait:"Bitte warten Sie, während Ihre Daten wiederhergestellt werden",clickToSelect:"Klicken Sie, um Backup-Datei auszuwählen (.json oder .zip)",howDuplicateHandling:"So funktioniert die Duplikatbehandlung:",categories:{printers:"Drucker",smartPlugs:"Smart Plugs",notificationProviders:"Benachrichtigungsanbieter",filaments:"Filamente",archives:"Archive",pendingUploads:"Ausstehende Uploads",settingsTemplates:"Einstellungen & Vorlagen"},matchingInfo:{printers:"abgeglichen nach Seriennummer",smartPlugs:"abgeglichen nach IP-Adresse",notificationProviders:"abgeglichen nach Name",filaments:"abgeglichen nach Name + Typ + Marke",archives:"abgeglichen nach Inhalts-Hash",pendingUploads:"abgeglichen nach Dateiname",settingsTemplates:"immer überschrieben"},replaceExisting:"Vorhandene Daten ersetzen",keepExisting:"Vorhandene Daten behalten",replaceDescription:"Bereits vorhandene Elemente mit Backup-Daten überschreiben",keepDescription:"Nur Elemente wiederherstellen, die noch nicht existieren",caution:"Vorsicht:",cautionText:"Das Überschreiben ersetzt Ihre aktuellen Konfigurationen durch Backup-Daten. Drucker-Zugangscodes werden aus Sicherheitsgründen niemals überschrieben.",itemsRestored:"Wiederhergestellte Elemente",itemsSkipped:"Übersprungene Elemente",restored:"Wiederhergestellt",skipped:"Übersprungen (existieren bereits)",filesLabel:"Dateien (3MF, Thumbnails, etc.)",newApiKeysGenerated:"Neue API-Schlüssel generiert",newApiKeysWarning:"Diese Schlüssel werden nur einmal angezeigt. Kopieren Sie sie jetzt!",processingBackup:"Backup-Datei wird verarbeitet...",noDataFound:"In der Backup-Datei wurden keine wiederherzustellenden Daten gefunden.",failedToRestore:"Backup konnte nicht wiederhergestellt werden. Bitte überprüfen Sie das Dateiformat."},backupExport:{title:"Backup exportieren",selectData:"Zu exportierende Daten auswählen",selectAll:"Alle auswählen",selectNone:"Keine auswählen",categoryDescriptions:{settings:"Sprache, Theme, Update-Einstellungen",notifications:"ntfy, Pushover, Discord, usw.",templates:"Benutzerdefinierte Nachrichtenvorlagen",smartPlugs:"Tasmota-Plug-Konfigurationen",externalLinks:"Seitenleiste Links zu externen Diensten",printers:"Druckerinformationen (Zugangscodes ausgeschlossen)",plateDetection:"Leere Platten-Referenzbilder",filaments:"Filamenttypen und -kosten",maintenance:"Benutzerdefinierte Wartungspläne",archives:"Alle Druckdaten + Dateien (3MF, Thumbnails, Fotos)",projects:"Projekte, BOM-Elemente und Anhänge",pendingUploads:"Virtueller Drucker-Uploads zur Überprüfung",apiKeys:"Webhook-API-Schlüssel (neue Schlüssel bei Import generiert)"},requiresPrinters:"Drucker müssen ausgewählt sein",zipFileWarning:"ZIP-Datei wird erstellt.",zipFileDescription:"Enthält alle 3MF-Dateien, Thumbnails, Zeitraffer und Fotos. Dies kann eine Weile dauern und zu einer großen Datei führen.",includeAccessCodes:"Zugangscodes einschließen",includeAccessCodesDescription:"Für die Übertragung auf eine andere Maschine",includeAccessCodesWarning:"Zugangscodes werden im Klartext eingeschlossen. Bewahren Sie diese Backup-Datei sicher auf!",categoriesSelected:"{{selectedCount}} Kategorien ausgewählt"},pendingUploads:{placeholders:{notes:"Notizen zu diesem Druck hinzufügen..."},discardUpload:"Upload verwerfen",archiveAllUploads:"Alle Uploads archivieren",discardAllUploads:"Alle Uploads verwerfen",archive:"Archivieren",timeAgo:{justNow:"Gerade eben",minutesAgo:"vor {{minutes}}m",hoursAgo:"vor {{hours}}h",daysAgo:"vor {{days}}d"}},apiBrowser:{placeholders:{requestBody:"JSON-Anforderungstext...",searchEndpoints:"Endpunkte suchen..."}},configureAmsSlot:{title:"AMS-Slot konfigurieren",slotConfigured:"Slot konfiguriert!",configuringSlot:"Slot wird konfiguriert:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Voreinstellungen suchen...",colorPlaceholder:"Farbname oder Hex (z.B. braun, FF8800)",clearCustomColor:"Benutzerdefinierte Farbe löschen",noCloudPresets:"Keine Cloud-Voreinstellungen. Melden Sie sich bei Bambu Cloud an, um zu synchronisieren.",noPresetsAvailable:"Keine Voreinstellungen verfügbar. Melden Sie sich bei Bambu Cloud an oder importieren Sie lokale Profile.",noMatchingPresets:"Keine passenden Voreinstellungen gefunden.",custom:"Benutzerdefiniert",builtin:"Integriert",settingsSentToPrinter:"Einstellungen an Drucker gesendet",filamentProfile:"Filamentprofil",kProfileLabel:"K-Profil (Pressure Advance)",filteringFor:"Filtern nach: {{material}}",noKProfile:"Kein K-Profil (Standard 0.020 verwenden)",noMatchingKProfiles:"Keine passenden K-Profile gefunden. Standard K=0.020 wird verwendet.",selectFilamentFirst:"Zuerst ein Filamentprofil auswählen",kFromCalibration:"K={{value}} aus Druckerkalibrierung",customColorLabel:"Benutzerdefinierte Farbe (optional)",presetColors:"{{name}} Farben:",showLessColors:"Weniger Farben anzeigen",showMoreColors:"Mehr Farben anzeigen",clear:"Löschen",hexLabel:"Hex: #{{hex}}",resetting:"Wird zurückgesetzt...",resetSlot:"Slot zurücksetzen",cancel:"Abbrechen",configuring:"Wird konfiguriert...",configureSlot:"Slot konfigurieren"},githubBackup:{title:"GitHub-Backup",history:"Verlauf",downloadBackup:"Backup herunterladen",restoreBackup:"Backup wiederherstellen",noBackupsYet:"Noch keine Backups"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Tags suchen...",renameTag:"Tag umbenennen",deleteTag:"Tag löschen"},notificationTemplates:{placeholders:{title:"Benachrichtigungstitel...",body:"Benachrichtigungstext..."}},batchTag:{placeholders:{newTag:"Neuen Tag eingeben..."}},photoGallery:{deletePhoto:"Foto löschen"},filamentHoverCard:{copySpoolUuid:"Spulen-UUID kopieren"},kProfilesView:{hasNote:"Hat Notiz",copyProfile:"Profil kopieren"},layout:{openMenu:"Menü öffnen",noPermissionSystemInfo:"Sie haben keine Berechtigung zum Anzeigen von Systeminformationen"},dashboard:{dragToReorder:"Ziehen zum Neuordnen",hideWidget:"Widget ausblenden"},notificationProviderCard:{deleteNotificationProvider:"Benachrichtigungsanbieter löschen"},fileManagerModal:{closeFileManager:"Dateimanager schließen",sortFiles:"Dateien sortieren",goToParentFolder:"Zum übergeordneten Ordner gehen",threeView:"3D-Ansicht"},embeddedCameraViewer:{refreshStream:"Stream aktualisieren",close:"Schließen",zoomOut:"Verkleinern",resetZoom:"Zoom zurücksetzen",zoomIn:"Vergrößern",dragToResize:"Ziehen zum Größe ändern"},timelapseViewer:{skipBack5s:"5s zurückspringen",skipForward5s:"5s vorspringen"},notificationProviders:{descriptions:{email:"SMTP-E-Mail-Benachrichtigungen",telegram:"Benachrichtigungen über Telegram-Bot",discord:"An Discord-Kanal über Webhook senden",ntfy:"Kostenlose, selbst hostbare Push-Benachrichtigungen",pushover:"Einfache, zuverlässige Push-Benachrichtigungen",callmebot:"Kostenlose WhatsApp-Benachrichtigungen über CallMeBot",webhook:"Generischer HTTP POST zu beliebiger URL"}},logViewer:{searchPlaceholder:"Nachricht oder Logger-Name suchen...",noLogEntries:"Keine Logeinträge gefunden"},switchbarPopover:{noSwitchesInSwitchbar:"Keine Schalter in Schalterleiste"},projectPageModal:{placeholders:{title:"Titel",designer:"Designer",license:"Lizenz",description:"Beschreibung eingeben...",profileTitle:"Profil-Titel",profileDescription:"Profilbeschreibung..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"Wartend",justNow:"Gerade eben",now:"Jetzt",minsAgo:"vor {{count}}m",inMins:"in {{count}}m",hoursAgo:"vor {{count}}h",inHours:"in {{count}}h",daysAgo:"vor {{count}}d",inDays:"in {{count}}d"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventar",printers:"Drucker",settings:"Einstellungen"},status:{nfcReady:"Bereit",nfcOff:"Aus",offline:"Gerät offline"},dashboard:{idleMessage:"Spule auf die Waage legen und NFC-Tag scannen"},weight:{noReading:"Kein Messwert",stable:"Stabil",measuring:"Messung",tare:"Tara",calibrate:"Kalibrieren",tareQueued:"Tara-Befehl gesendet"},spool:{remaining:"Verbleibend"},tag:{unknownTitle:"Unbekannter Tag",linkExisting:"Mit vorhandener Spule verknüpfen",createNew:"Neue Spule erstellen"},actions:{assignAms:"AMS zuweisen",updateWeight:"Gewicht aktualisieren",editSpool:"Spule bearbeiten",viewHistory:"Verlauf anzeigen",weightUpdated:"Spulengewicht aktualisiert"},ams:{noData:"Keine AMS-Daten verfügbar"},inventory:{search:"Spulen suchen...",empty:"Keine Spulen gefunden"},printers:{noPrinters:"Keine Drucker konfiguriert"},settings:{scaleCalibration:"Waagenkalibrierung",currentWeight:"Aktuelles Gewicht",tareOffset:"Tara-Offset",knownWeight:"Bekanntes Gewicht",calibrated:"Kalibrierung aktualisiert",tareQueued:"Tara-Befehl in Warteschlange",nfcReader:"NFC-Leser",nfcConnected:"Verbunden",nfcDisconnected:"Getrennt",deviceInfo:"Geräteinformation",deviceId:"Geräte-ID",uptime:"Betriebszeit",firmware:"Firmware"}}},uce={nav:{printers:"Imprimantes",archives:"Archives",queue:"File d'attente",stats:"Statistiques",profiles:"Profils",maintenance:"Maintenance",projects:"Projets",inventory:"Filament",files:"Gestionnaire de fichiers",settings:"Paramètres",system:"Système",collapseSidebar:"Réduire la barre latérale",expandSidebar:"Développer la barre latérale",update:"Mise à jour",updateAvailable:"Mise à jour disponible : v{{version}}",updateAvailableBanner:"La version {{version}} est disponible !",viewUpdate:"Voir la mise à jour",viewOnGithub:"Voir sur GitHub",keyboardShortcuts:"Raccourcis clavier (?)",switchToLight:"Passer au mode clair",switchToDark:"Passer au mode sombre",smartSwitches:"Interrupteurs intelligents",logout:"Déconnexion"},common:{save:"Enregistrer",saving:"Enregistrement...",cancel:"Annuler",delete:"Supprimer",edit:"Modifier",add:"Ajouter",close:"Fermer",confirm:"Confirmer",loading:"Chargement...",error:"Erreur",success:"Succès",warning:"Avertissement",enabled:"Activé",disabled:"Désactivé",yes:"Oui",no:"Non",on:"On",off:"Off",all:"Tous",none:"Aucun",search:"Rechercher",filter:"Filtrer",sort:"Trier",refresh:"Actualiser",download:"Télécharger",upload:"Téléverser",actions:"Actions",status:"Statut",name:"Nom",description:"Description",date:"Date",time:"Heure",hours:"heures",minutes:"minutes",seconds:"secondes",days:"jours",enable:"Activer",disable:"Désactiver",permissions:"Autorisations",noPrinters:"Aucune imprimante configurée",noData:"Aucune donnée disponible",linkNotFound:"Lien non trouvé",required:"Requis",optional:"Optionnel",dismiss:"Ignorer",apply:"Appliquer",reset:"Réinitialiser",export:"Exporter",import:"Importer",clear:"Effacer",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",noChange:"— Aucun changement —",unchanged:"Inchangé",unassigned:"Non assigné",unknown:"Inconnu",unknownError:"Erreur inconnue",today:"Aujourd'hui",tomorrow:"Demain",asap:"Dès que possible",overdue:"En retard",now:"Maintenant",collapse:"Réduire",expand:"Développer",viewArchive:"Voir l'archive",viewInFileManager:"Voir dans le gestionnaire de fichiers",addedBy:"Ajouté par {{username}}",prints:"impressions",more:"+{{count}} de plus",ascending:"Croissant",descending:"Décroissant",printer:"Imprimante",remove:"Retirer",type:"Type",print:"Imprimer",rename:"Renommer",move:"Déplacer",create:"Créer",duplicate:"Dupliquer",left:"Gauche",right:"Droite"},printers:{title:"Imprimantes",addPrinter:"Ajouter une imprimante",editPrinter:"Modifier l'imprimante",deletePrinter:"Supprimer l'imprimante",printerName:"Nom de l'imprimante",serialNumber:"Numéro de série",ipAddress:"Adresse IP / Nom d'hôte",accessCode:"Code d'accès",model:"Modèle",nozzleCount:"Nombre de buses",autoArchive:"Auto-archivage",status:{available:"Disponible",idle:"Inactif",printing:"Impression en cours",paused:"En pause",offline:"Hors ligne",error:"Erreur",finished:"Terminé",unknown:"Inconnu"},temperatures:{nozzle:"Buse",bed:"Plateau",chamber:"Chambre"},progress:"{{percent}}% terminé",timeRemaining:"{{time}} restant",deleteConfirm:'Êtes-vous sûr de vouloir supprimer "{{name}}" ?',maintenanceOk:"Maintenance OK",maintenanceWarning:"{{count}} avertissement",maintenanceWarning_plural:"{{count}} avertissements",maintenanceDue:"{{count}} échéance",maintenanceDue_plural:"{{count}} échéances",sort:{name:"Nom",status:"Statut",model:"Modèle",location:"Emplacement",ascending:"Tri croissant",descending:"Tri décroissant"},cardSize:{small:"Petites cartes",medium:"Cartes moyennes",large:"Grandes cartes",extraLarge:"Très grandes cartes"},hideOffline:"Masquer hors ligne",nextAvailable:"Prochaine disponible",powerOn:"Allumer",offlinePrintersWithPlugs:"Imprimantes hors ligne avec prises connectées",noPrintersConfigured:"Aucune imprimante configurée pour le moment",readyToPrint:"Prête à imprimer",external:"Externe",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Supprimer les archives d'impression",noLabel:"Pas d'étiquette",printPreview:"Aperçu avant impression",width:"Largeur",height:"Hauteur",noObjectsFound:"Aucun objet trouvé",objectsLoadedOnPrintStart:"Les objets sont chargés au début de l'impression",willBeSkipped:"Sera sauté",name:"Nom",serialCannotBeChanged:"Le numéro de série ne peut pas être modifié",locationHelp:"Utilisé pour grouper les imprimantes et filtrer la file d'attente",wifiSignal:{veryWeak:"Très faible",weak:"Faible",fair:"Moyen",good:"Bon",excellent:"Excellent"},maintenanceUpToDate:"Maintenance à jour - Cliquez pour voir",chamberLightOn:"Allumer la lumière de la chambre",chamberLightOff:"Éteindre la lumière de la chambre",browseFiles:"Parcourir les fichiers de l'imprimante",autoOffAfterPrint:"Extinction auto après impression",autoOffExecuted:"Extinction auto exécutée - rallumez pour réinitialiser",hmsErrors:"Erreurs HMS",viewHmsErrors:"Voir {{count}} erreur(s) HMS",resume:"Reprendre",pause:"Pause",stop:"Arrêter",camera:"Caméra",skipObject:"Sauter l'objet",reconnect:"Reconnecter",mqttDebug:"Débogage MQTT",activeNozzle:"Active : buse {{nozzle}}",nozzleRack:"Rack à buses",nozzleDocked:"Rangée",nozzleMounted:"Montée",nozzleActive:"Active",nozzleIdle:"Inactive",nozzleDiameter:"Diamètre",nozzleType:"Type",nozzleStatus:"Statut",nozzleFilament:"Filament",nozzleWear:"Usure",nozzleMaxTemp:"Temp Max",nozzleSerial:"Série",nozzleHardenedSteel:"Acier Trempé",nozzleStainlessSteel:"Acier Inoxydable",nozzleTungstenCarbide:"Carbure de Tungstène",nozzleFlow:"Débit",nozzleHighFlow:"Haut débit",nozzleStandardFlow:"Standard",firmwareUpdate:"Mise à jour Firmware",firmwareInstructions:"Sur l'écran de l'imprimante, allez dans",firmwareNav:"Naviguez vers",settings:"Paramètres",firmware:"Firmware",discoverPrinters:"Découvrir les imprimantes",searching:"Recherche...",manualEntry:"Saisie manuelle",addFromCloud:"Ajouter depuis le Cloud",toast:{printerDeleted:"Imprimante supprimée",printerAdded:"Imprimante ajoutée",printerUpdated:"Imprimante mise à jour",failedToDelete:"Échec de la suppression",failedToAdd:"Échec de l'ajout",failedToUpdate:"Échec de la mise à jour",commandSent:"Commande envoyée",failedToSendCommand:"Échec de l'envoi de la commande",turnedOn:"{{name}} allumée",failedToPowerOn:"Échec de l'allumage de {{name}}",scriptTriggered:"Script déclenché",printStopped:"Impression arrêtée",printPaused:"Impression en pause",printResumed:"Impression reprise",referenceDeleted:"Référence supprimée",detectionAreaSaved:"Zone de détection enregistrée",failedToRunScript:"Échec du script",failedToStopPrint:"Échec de l'arrêt",failedToPausePrint:"Échec de la mise en pause",failedToResumePrint:"Échec de la reprise",failedToControlChamberLight:"Échec du contrôle de la lumière",failedToUpdateSetting:"Échec de mise à jour du paramètre",failedToSkipObjects:"Échec du saut d'objets",failedToRereadRfid:"Échec lecture RFID",failedToCheckPlate:"Échec vérification plateau",failedToUpdateLabel:"Échec mise à jour étiquette",failedToDeleteReference:"Échec suppression référence",failedToSaveDetectionArea:"Échec enregistrement zone",plateCheckEnabled:"Vérification plateau activée",plateCheckDisabled:"Vérification plateau désactivée",calibrationSaved:"Calibration enregistrée !",calibrationFailed:"Échec de la calibration",rfidRereadInitiated:"Lecture RFID initiée"},connection:{connected:"Connecté",offline:"Hors ligne"},queue:{inQueue:"{{count}} impression en file",inQueue_plural:"{{count}} impressions en file"},controls:"Contrôles",rfid:{reread:"Relire RFID"},permission:{noAdd:"Pas d'autorisation pour ajouter",noEdit:"Pas d'autorisation pour modifier",noDelete:"Pas d'autorisation pour supprimer",noControl:"Pas d'autorisation pour contrôler",noFiles:"Pas d'autorisation pour les fichiers",noAmsRfid:"Pas d'autorisation pour le RFID",noSmartPlugControl:"Pas d'autorisation pour les prises"},modal:{addTitle:"Ajouter une imprimante",editTitle:"Modifier l'imprimante",myPrinter:"Mon imprimante",selectModel:"Choisir un modèle...",locationGroup:"Emplacement / Groupe (optionnel)",locationPlaceholder:"ex: Atelier, Bureau",autoArchiveLabel:"Auto-archiver les impressions terminées",fromPrinterSettings:"Depuis les paramètres imprimante",modelOptional:"Modèle (optionnel)",saveChanges:"Enregistrer les modifications"},skipObjects:{tooltip:"Sauter des objets",onlyWhilePrinting:"Sauter (uniquement pendant l'impression)",requiresMultiple:"Sauter (nécessite 2+ objets)",title:"Sauter des objets",matchIdsInfo:"Faites correspondre les IDs avec l'écran de l'imprimante",printerShowsIds:"L'écran affiche les IDs des objets sur le plateau",skipSelected:"Sauter la sélection",skipping:"Saut en cours...",noObjectsSelected:"Aucun objet sélectionné",selectObjectsToSkip:"Sélectionnez les objets à ignorer",skipped:"sauté",objectsSkipped:"Objets sautés",activeCount:"{{count}} actifs",waitForLayer:"Attendez la couche 2 pour sauter des objets (actuelle : {{layer}})",skip:"Sauter",confirmTitle:"Sauter l'objet ?",confirmMessage:'Voulez-vous vraiment sauter "{{name}}" ? Cette action est irréversible.'},confirm:{deleteTitle:"Supprimer l'imprimante",deleteMessage:'Supprimer "{{name}}" ? Cela retirera tous les paramètres de connexion.',deleteArchivesNote:"Tout l'historique sera définitivement supprimé.",keepArchivesNote:"L'historique sera conservé mais plus associé à cette imprimante.",stopTitle:"Arrêter l'impression",stopMessage:`Arrêter l'impression sur "{{name}}" ?`,stopButton:"Arrêter",pauseTitle:"Mettre en pause",pauseMessage:`Mettre en pause l'impression sur "{{name}}" ?`,pauseButton:"Pause",resumeTitle:"Reprendre l'impression",resumeMessage:`Reprendre l'impression sur "{{name}}" ?`,resumeButton:"Reprendre",powerOnTitle:"Allumer l'imprimante",powerOnMessage:'Allumer "{{name}}" ?',powerOnButton:"Allumer",powerOffTitle:"Éteindre l'imprimante",powerOffMessage:'Éteindre "{{name}}" ?',powerOffWarning:`ATTENTION : "{{name}}" imprime ! L'éteindre maintenant peut endommager l'imprimante.`,powerOffButton:"Éteindre"},discovery:{title:"Découvrir les imprimantes",searching:"Recherche...",scanning:"Scan en cours...",scanProgress:"Scan... {{scanned}}/{{total}}",foundPrinters:"{{count}} imprimante(s) trouvée(s)",noPrintersFound:"Aucune imprimante trouvée",noPrintersFoundSubnet:"Aucune imprimante dans ce sous-réseau.",noPrintersFoundNetwork:"Aucune imprimante sur le réseau.",allConfigured:"Toutes les imprimantes trouvées sont déjà configurées.",alreadyAdded:"Déjà ajoutée",select:"Sélectionner",manualEntry:"Saisie manuelle",addFromCloud:"Ajouter depuis le Cloud",subnetToScan:"Sous-réseau à scanner",dockerNote:"Docker détecté. Entrez le sous-réseau en notation CIDR. Nécessite network_mode: host.",scanSubnet:"Scanner le sous-réseau",discoverNetwork:"Découvrir sur le réseau",scanningSubnet:"Scan du sous-réseau pour imprimantes Bambu...",scanningNetwork:"Scan du réseau...",serialRequired:"Série requis",unknown:"Inconnu",failedToStart:"Échec du démarrage de la découverte"},filaments:"Filaments",openCameraOverlay:"Ouvrir la caméra en superposition",openCameraWindow:"Ouvrir la caméra dans une fenêtre",firmwareUpdateAvailable:"Mise à jour firmware : {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — À jour",firmwareUpdateButton:"Mettre à jour",plateDetection:{noPermission:"Pas d'autorisation de modification",enabledClick:"Vérification activée - Cliquez pour désactiver",disabledClick:"Vérification désactivée - Cliquez pour activer",manageCalibration:"Gérer la calibration de détection",calibrationRequired:"Calibration requise",calibrationInstructions:"Videz le plateau, puis cliquez sur Calibrer.",calibrationDescription:"Capture une image de référence du plateau vide.",calibrationTip:"Conseil : Stockez jusqu'à 5 références. Le système utilise la meilleure correspondance.",plateEmpty:"Le plateau semble vide",objectsDetected:"Objets détectés sur le plateau",confidence:"Confiance",difference:"Différence",analysisPreview:"Aperçu de l'analyse :",analysisLegend:"Cadre vert = zone, Rouge = différences",savedReferences:"Références ({{count}}/{{max}})",deleteReference:"Supprimer la référence",labelPlaceholder:"Étiquette...",clickToEdit:"{{label}} - Modifier",clickToAddLabel:"Ajouter une étiquette"},fans:{partCooling:"Ventilateur pièce",auxiliary:"Ventilateur auxiliaire",chamber:"Ventilateur chambre"},clickToViewHmsErrors:"Cliquez pour voir les erreurs HMS",estimatedCompletion:"Fin estimée",slotOptions:"Options du slot",firmwareModal:{title:"Mise à jour Firmware",titleUpToDate:"Infos Firmware",currentVersion:"Actuelle :",latestVersion:"Dernière :",releaseNotes:"Notes de version",checkingPrereqs:"Vérification des prérequis...",sdCardReady:"Carte SD prête. Cliquez pour téléverser.",uploadedSuccess:"Firmware téléversé !",applyInstructions:"Pour appliquer sur l'imprimante :",step1:"Sur l'écran, allez dans Paramètres",step2:"Allez dans Firmware",step3:'Sélectionnez "Mettre à jour depuis carte SD"',step4:"Prévoyez 10-20 minutes",done:"Terminé",starting:"Démarrage...",uploadFirmware:"Téléverser le Firmware",uploadFailed:"Échec du téléversement : {{error}}",uploadedToast:"Firmware téléversé ! Lancez la mise à jour sur l'écran."},accessCodePlaceholder:"Laissez vide pour garder l'actuel",roi:{title:"Zone de détection (ROI)",xStart:"Début X",yStart:"Début Y",width:"Largeur",height:"Hauteur",instruction:"Ajustez le cadre vert pour cibler le plateau."},developerModeWarning:"Le mode développeur LAN n'est pas activé sur : {{names}}. Certaines fonctionnalités peuvent ne pas fonctionner.",howToEnable:"Comment activer"},archives:{title:"Archives d'impression",searchPlaceholder:"Chercher dans les archives...",filterByPrinter:"Par imprimante",filterByStatus:"Par statut",sortBy:"Trier par",sortNewest:"Plus récent",sortOldest:"Plus ancien",sortName:"Nom",sortDuration:"Durée",sortLargest:"Plus volumineux",sortSmallest:"Plus léger",sortSize:"Taille",noArchives:"Aucune archive trouvée",noArchivesSearch:"Aucune archive ne correspond",noArchivesYet:"Pas encore d'archive",loadingArchives:"Chargement...",releaseToUpload:"Relâcher pour téléverser",showAll:"Tout afficher",showFavoritesOnly:"Favoris uniquement",gridView:"Grille",listView:"Liste",calendarView:"Calendrier",logView:"Journal d'impression",manageTags:"Gérer les tags",showFailedPrints:"Afficher les échecs",hideFailedPrints:"Masquer les échecs",printTime:"Temps d'impression",filamentUsed:"Filament utilisé",cost:"Coût",reprint:"Réimprimer",preview:"Aperçu",deleteArchive:"Supprimer l'archive",deleteConfirm:"Supprimer cette archive ?",favorite:"Favori",unfavorite:"Retirer des favoris",viewDetails:"Détails",status:{completed:"Réussi",failed:"Échoué",stopped:"Arrêté"},toast:{source3mfAttached:"Source 3MF attachée : {{filename}}",failedUploadSource3mf:"Échec téléversement 3MF",source3mfRemoved:"Source 3MF retirée",failedRemoveSource3mf:"Échec retrait 3MF",f3dAttached:"F3D attaché : {{filename}}",failedUploadF3d:"Échec téléversement F3D",f3dRemoved:"F3D retiré",failedRemoveF3d:"Échec retrait F3D",timelapseAttached:"Timelapse attaché : {{filename}}",timelapseAlreadyAttached:"Timelapse déjà présent",noMatchingTimelapse:"Pas de timelapse correspondant",failedScanTimelapse:"Échec scan timelapse",failedAttachTimelapse:"Échec attache timelapse",archiveDeleted:"Archive supprimée",failedDeleteArchive:"Échec suppression",addedToFavorites:"Ajouté aux favoris",removedFromFavorites:"Retiré des favoris",projectUpdated:"Projet mis à jour",failedUpdateProject:"Échec mise à jour projet",linkCopied:"Lien copié",failedCopyLink:"Échec copie lien",photoDeleted:"Photo supprimée",failedDeletePhoto:"Échec suppression photo",failedDeleteArchives:"Échec suppression archives",failedUpdateFavorites:"Échec mise à jour favoris",exportDownloaded:"Export téléchargé",exportFailed:"Échec export"},menu:{print:"Imprimer",schedule:"Planifier",openInBambuStudio:"Ouvrir dans le Slicer",slice:"Découper",externalLink:"Lien externe",viewOnMakerWorld:"Voir sur MakerWorld",preview3d:"Aperçu 3D",viewTimelapse:"Voir le Timelapse",scanForTimelapse:"Scanner pour Timelapse",downloadSource3mf:"Télécharger Source 3MF",uploadSource3mf:"Téléverser Source 3MF",replaceSource3mf:"Remplacer Source 3MF",removeSource3mf:"Retirer Source 3MF",uploadF3d:"Téléverser F3D",replaceF3d:"Remplacer F3D",downloadF3d:"Télécharger F3D",removeF3d:"Retirer F3D",download:"Télécharger",copyDownloadLink:"Copier lien de téléchargement",qrCode:"Code QR",viewPhotos:"Voir les photos",viewPhotosCount:"Voir les photos ({{count}})",projectPage:"Page du Projet",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",edit:"Modifier",goToProject:"Aller au Projet : {{name}}",addToProject:"Ajouter au Projet",removeFromProject:"Retirer du Projet",loading:"Chargement...",noProjectsAvailable:"Aucun projet disponible",select:"Sélectionner",deselect:"Désélectionner",delete:"Supprimer"},permission:{noReprint:"Pas d'autorisation de réimpression",noAddToQueue:"Pas d'autorisation pour la file",noUpdateArchives:"Pas d'autorisation de mise à jour",noUploadFiles:"Pas d'autorisation de téléversement",noDownload:"Pas d'autorisation de téléchargement",noCopyLink:"Pas d'autorisation de copie lien",noDelete:"Pas d'autorisation de suppression",noCreate:"Pas d'autorisation de création"},card:{previousPlate:"Plateau précédent",nextPlate:"Plateau suivant",plateNumber:"Plateau {{index}}",moreOptions:"Clic droit pour plus d'options",addToFavorites:"Ajouter aux favoris",removeFromFavorites:"Retirer des favoris",cancelled:"annulé",failed:"échoué",duplicate:"doublon",duplicateTitle:"Ce modèle a déjà été imprimé",openSource3mf:"Ouvrir 3MF dans Bambu Studio (clic droit pour plus)",downloadF3d:"Télécharger fichier Fusion 360",viewTimelapse:"Voir timelapse",viewPhoto:"Voir 1 photo",viewPhotos:"Voir {{count}} photos",openFolder:"Ouvrir le dossier : {{name}}",slicedFile:"Fichier découpé - prêt",sourceFile:"Fichier source uniquement - pas de mapping AMS",gcode:"GCODE",source:"SOURCE",project:"Projet : {{name}}",estimated:"Estimé : {{time}}",actual:"Réel : {{time}}",accuracy:"Précision : {{percent}}%",filament:"{{weight}}g",layer:"{{count}} couche",layers:"{{count}} couches",object:"{{count}} objet",objects:"{{count}} objets",slicedFor:"Découpé pour {{model}}",uploadedBy:"Téléversé par",noPermissionReprint:"Pas d'autorisation de réimpression",noFileForReprint:"Aucun fichier 3MF disponible — le fichier n'a pas pu être téléchargé depuis l'imprimante lors de l'enregistrement",noPermissionEdit:"Pas d'autorisation de modification",noPermissionDelete:"Pas d'autorisation de suppression",reprint:"Réimprimer",schedulePrint:"Planifier",schedule:"Planifier",openInBambuStudio:"Ouvrir dans le Slicer",openInBambuStudioToSlice:"Ouvrir dans le Slicer pour découper",slice:"Découper",externalLink:"Lien externe",makerWorld:"MakerWorld : {{designer}}",viewProject:"Voir projet",noExternalLink:"Aucun lien externe",preview3d:"Aperçu 3D",download:"Télécharger",edit:"Modifier",delete:"Supprimer"},modal:{deleteArchive:"Supprimer l'archive",deleteConfirm:'Supprimer "{{name}}" ? Cette action est irréversible.',deleteButton:"Supprimer",removeSource3mf:"Retirer Source 3MF",removeSource3mfConfirm:'Retirer le fichier 3MF de "{{name}}" ?',removeButton:"Retirer",removeF3d:"Retirer F3D",removeF3dConfirm:'Retirer le fichier Fusion 360 de "{{name}}" ?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Choisir un Timelapse",selectTimelapseDesc:"Sélectionnez manuellement le timelapse :",deleteArchives:"Supprimer les archives",deleteArchivesConfirm:"Supprimer {{count}} archive(s) ?",deleteCount:"Supprimer {{count}}"},page:{title:"Archives",printsCount:"{{filtered}} sur {{total}} impressions",dropFilesHere:"Déposez les fichiers .3mf ici",releaseToUpload:"Relâcher pour téléverser",only3mfSupported:"Seuls les fichiers .3mf sont supportés",close:"Fermer",selected:"{{count}} sélectionnés",selectAll:"Tout sélectionner",tags:"Tags",project:"Projet",favorite:"Favori",delete:"Supprimer",toggledFavorites:"Favoris mis à jour pour {{count}} archive(s)",failedUpdateFavorites:"Échec mise à jour favoris",archivesDeleted:"{{count}} archive(s) supprimée(s)",failedDeleteArchives:"Échec suppression",photoDeleted:"Photo supprimée",failedDeletePhoto:"Échec suppression photo"},list:{name:"Nom",printer:"Imprimante",date:"Date",size:"Taille",actions:"Actions",hasTimelapse:"A un timelapse"},log:{date:"Date",printName:"Nom de l'impression",printer:"Imprimante",user:"Utilisateur",status:"Statut",duration:"Durée",filament:"Filament",allPrinters:"Toutes les imprimantes",allUsers:"Tous les utilisateurs",allStatuses:"Tous les statuts",cancelled:"Annulé",skipped:"Ignoré",dateFrom:"Du",dateTo:"Au",noEntries:"Aucune entrée de journal trouvée",showing:"{{count}} sur {{total}} entrées",rowsPerPage:"Lignes",page:"Page",prev:"Préc.",next:"Suiv.",clearLog:"Effacer le journal",clearLogTitle:"Effacer le journal d'impression",clearLogConfirm:"Toutes les entrées du journal d'impression seront supprimées définitivement. Les archives et les éléments de file d'attente ne sont pas affectés. Cette action est irréversible. Êtes-vous sûr ?",clearLogButton:"Tout effacer",cleared:"{{count}} entrées de journal effacées",clearFailed:"Échec de l'effacement du journal d'impression"}},queue:{title:"File d'attente",subtitle:"Gérez vos travaux d'impression",addToQueue:"Ajouter à la file",print:"Imprimer",reprint:"Réimprimer",schedulePrint:"Planifier",editQueueItem:"Modifier l'élément",printToPrinters:"Imprimer sur {{count}} imprimantes",queueToPrinters:"Ajouter à la file pour {{count}} imprimantes",sending:"Envoi...",sendingProgress:"Envoi {{current}}/{{total}}...",adding:"Ajout...",addingProgress:"Ajout {{current}}/{{total}}...",savingProgress:"Enregistrement {{current}}/{{total}}...",clearQueue:"Vider la file",clearHistory:"Effacer l'historique",emptyQueue:"La file est vide",position:"Position",scheduledTime:"Heure prévue",moveUp:"Monter",moveDown:"Descendre",startNow:"Démarrer maintenant",printingInProgress:"Impression en cours...",viewArchive:"Voir l'archive",viewInFileManager:"Voir dans le gestionnaire",itemCount:"{{count}} élément",itemCount_plural:"{{count}} éléments",dragToReorder:"Glisser pour réordonner (ASAP uniquement)",reorderHint:"La position n'affecte que les éléments ASAP.",addedBy:"Ajouté par {{name}}",nextInQueue:"Prochain en file",clearPlate:"Vider plateau & lancer suivant",clearPlateSuccess:"Plateau vidé — prêt pour l'impression suivante",plateReady:"Plateau vidé — prêt pour l'impression suivante",plateNumber:"Plateau {{index}}",sections:{currentlyPrinting:"En cours",queued:"En attente",history:"Historique"},status:{pending:"En attente",waiting:"En attente",printing:"Impression",paused:"En pause",completed:"Terminé",failed:"Échoué",skipped:"Sauté",cancelled:"Annulé"},summary:{printing:"Impressions",queued:"En attente",totalTime:"Temps total estimé",totalWeight:"Poids total estimé",history:"Historique"},filter:{allPrinters:"Toutes les imprimantes",unassigned:"Non assigné",allStatus:"Tous les statuts",allLocations:"Tous les emplacements",any:"Tout"},sort:{byPosition:"Par position",byName:"Par nom",byPrinter:"Par imprimante",bySchedule:"Par planification",byDate:"Par date",ascendingOldest:"Croissant (plus vieux)",descendingNewest:"Décroissant (plus récent)"},badges:{staged:"Préparé",requiresPrevious:"Nécessite succès précédent",autoPowerOff:"Extinction auto"},empty:{title:"Aucune impression prévue",description:"Planifiez depuis les Archives ou glissez des fichiers ici."},time:{asap:"Dès que possible",overdue:"En retard",now:"Maintenant",lessThanMinute:"Dans moins d'une minute",inMinutes:"Dans {{count}} min",inHours:"Dans {{count}} heures"},actions:{stopPrint:"Arrêter",startPrint:"Démarrer",requeue:"Remettre en file"},bulkEdit:{title:"Modifier {{count}} élément",title_plural:"Modifier {{count}} éléments",description:"Seuls les changements seront appliqués.",printer:"Imprimante",noChange:"— Aucun changement —",queueOptions:"Options de file",staged:"Préparé (manuel)",autoPowerOff:"Extinction auto après",requirePrevious:"Requiert succès précédent",printOptions:"Options d'impression",bedLevelling:"Nivellement plateau",flowCalibration:"Calibration débit",vibrationCalibration:"Vibration (Input Shaper)",layerInspection:"Inspection 1ère couche",timelapse:"Timelapse",useAms:"Utiliser AMS",applyChanges:"Appliquer",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",selected:"{{count}} sélectionnés",editSelected:"Modifier la sélection",cancelSelected:"Annuler la sélection"},confirm:{cancelTitle:"Annuler l'impression prévue",cancelMessage:'Annuler "{{name}}" ?',stopTitle:"Arrêter l'impression",stopMessage:`Arrêter "{{name}}" sur l'imprimante ?`,removeTitle:"Retirer de l'historique",removeMessage:`Retirer "{{name}}" de l'historique ?`,clearHistoryTitle:"Effacer l'historique",clearHistoryMessage:"Retirer les {{count}} éléments ?",cancelButton:"Annuler l'impression",stopButton:"Arrêter l'impression",thisPrint:"cette impression",thisItem:"cet élément"},toast:{cancelled:"Élément annulé",cancelFailed:"Échec annulation",removed:"Élément retiré",removeFailed:"Échec retrait",stopped:"Impression arrêtée",stopFailed:"Échec arrêt",released:"Libéré dans la file",startFailed:"Échec démarrage",reorderFailed:"Échec réorganisation",historyCleared:"{{count}} éléments effacés",clearHistoryFailed:"Échec effacement",updateFailed:"Échec mise à jour",bulkCancelled:"{{count}} éléments annulés",bulkCancelFailed:"Échec annulation"},permissions:{noStopPrint:"Pas d'autorisation d'arrêt",noStartPrint:"Pas d'autorisation de démarrage",noEdit:"Pas d'autorisation de modification",noCancel:"Pas d'autorisation d'annulation",noRequeue:"Pas d'autorisation de remise en file",noRemove:"Pas d'autorisation de retrait",noClearHistory:"Pas d'autorisation historique",noEditItems:"Pas d'autorisation modification groupée",noCancelItems:"Pas d'autorisation annulation groupée"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded"}},stats:{title:"Tableau de bord",subtitle:"Glissez les widgets pour réorganiser. Cliquez sur l'œil pour masquer.",overview:"Vue d'ensemble",totalPrints:"Total impressions",successRate:"Taux de succès",totalPrintTime:"Temps total d'impression",printTime:"Temps d'impression",totalFilament:"Total filament utilisé",filamentUsed:"Filament utilisé",filamentCost:"Coût filament",totalCost:"Coût total",energyUsed:"Énergie consommée",energyCost:"Coût énergie",averagePrintTime:"Temps moyen par impression",printsPerDay:"Impressions par jour",byPrinter:"Par imprimante",printsByPrinter:"Impressions par imprimante",byMaterial:"Par matériau",byMonth:"Par mois",last7Days:"7 derniers jours",last30Days:"30 derniers jours",last90Days:"90 derniers jours",allTime:"Tout le temps",quickStats:"Stats rapides",printActivity:"Activité d'impression",filamentTypes:"Types de filament",filamentTrends:"Tendances filament",failureAnalysis:"Analyse des échecs",timeAccuracy:"Précision du temps",successful:"Succès :",failed:"Échecs :",perfectEstimate:"100% = estimation parfaite",noTimeAccuracyData:"Pas encore de données de précision",noFilamentData:"Aucune donnée de filament",noPrinterData:"Aucune donnée d'imprimante",noPrintData:"Aucune donnée d'impression",noPrintDataLast30Days:"Aucune impression ces 30 derniers jours",failureReasons:"Raisons des échecs",topFailureReasons:"Top raisons d'échec",failedPrintsCount:"{{failed}} / {{total}} impressions ont échoué",lastWeekRate:"Semaine dernière : {{rate}}%",resetLayout:"Réinitialiser la mise en page",recalculateCosts:"Recalculer les coûts",recalculateCostsHint:"Recalcule les coûts avec les prix actuels des filaments",exportStats:"Exporter les stats",exportAsCsv:"Exporter en CSV",exportAsExcel:"Exporter en Excel",hiddenCount:"{{count}} Masqués",exportDownloaded:"Export téléchargé",exportFailed:"Échec export",layoutReset:"Mise en page réinitialisée",recalculatedCosts:"Coûts recalculés pour {{count}} archives",recalculateFailed:"Échec du calcul",loadingStats:"Chargement des statistiques...",noPermissionResetLayout:"Pas d'autorisation de réinitialisation",noPermissionRecalculate:"Pas d'autorisation de recalcul"},maintenance:{title:"Maintenance",overview:"Vue d'ensemble",allOk:"Toute la maintenance est à jour",dueCount:"{{count}} tâche à faire",dueCount_plural:"{{count}} tâches à faire",warningCount:"{{count}} avertissement",warningCount_plural:"{{count}} avertissements",totalPrintTime:"Temps d'impression total",nextMaintenance:"Prochaine maintenance",nothingDue:"Rien de prévu",tasks:"Tâches",lastPerformed:"Dernière réalisation",interval:"Intervalle",hoursRemaining:"{{hours}}h restantes",hoursOverdue:"{{hours}}h de retard",markDone:"Marquer comme fait",performMaintenance:"Effectuer la maintenance",history:"Historique",noHistory:"Aucun historique",editPrintHours:"Modifier les heures d'impression",currentHours:"Heures actuelles",statusTab:"Statut",settingsTab:"Paramètres",overdueCount:"{{count}} en retard",dueSoonCount:"{{count}} bientôt",dueSoon:"Bientôt",allGood:"Tout va bien",overdueBy:"Retard de {{duration}}",dueIn:"Dans {{duration}}",timeLeft:"{{duration}} restant",day:"1 jour",days:"{{count}} jours",week:"1 semaine",weeks:"{{count}} semaines",month:"1 mois",months:"{{count}} mois",year:"1 an",maintenanceTypes:"Types de maintenance",maintenanceTypesDescription:"Types système et tâches personnalisées",addCustomType:"Ajouter un type",intervalType:"Type d'intervalle",intervalValue:"Intervalle ({{type}})",icon:"Icône",documentationLink:"Lien documentation (optionnel)",assignToPrinters:"Assigner aux imprimantes",selectAtLeastOnePrinter:"Sélectionnez au moins une imprimante",addType:"Ajouter le type",custom:"Personnalisé",printHours:"Heures d'impression",calendarDays:"Jours calendaires",exampleName:"ex: Remplacement filtre HEPA",viewDocumentation:"Voir documentation",timeBasedInterval:"Intervalle temporel",intervalOverrides:"Exceptions d'intervalle",intervalOverridesDescription:"Intervalles spécifiques par imprimante",assignedToPrinters:"Assigné aux imprimantes :",noPrintersAssigned:"Aucune imprimante assignée",addPrinterShort:"Ajouter :",printersAssignedClick:"{{count}} imprimante(s) assignée(s) - gérer",removeFromPrinter:"Retirer de cette imprimante",types:{lubricateCarbonRods:"Lubrifier les tiges carbone",lubricateRails:"Lubrifier les rails linéaires",cleanNozzle:"Nettoyer la buse / hotend",checkBelts:"Vérifier la tension des courroies",cleanBuildPlate:"Nettoyer le plateau",checkExtruder:"Vérifier les engrenages de l'extrudeur",checkCooling:"Vérifier les ventilateurs",generalInspection:"Inspection générale",cleanCarbonRods:"Nettoyer les tiges carbone",cleanLinearRails:"Nettoyer les rails linéaires",checkPtfeTube:"Vérifier le tube PTFE",replaceHepaFilter:"Remplacer le filtre HEPA",replaceCarbonFilter:"Remplacer le filtre charbon",lubricateLeftNozzleRail:"Lubrifier le rail de buse gauche"},maintenanceComplete:"Maintenance marquée comme faite",typeUpdated:"Type mis à jour",typeDeleted:"Type supprimé",printHoursUpdated:"Heures mises à jour",printerAssigned:"Imprimante assignée",printerRemoved:"Imprimante retirée",deleteTypeConfirm:'Supprimer "{{name}}" ?',noPermissionUpdate:"Pas d'autorisation de mise à jour",noPermissionPerform:"Pas d'autorisation d'action",noPermissionEditTypes:"Pas d'autorisation de modification types",noPermissionDeleteTypes:"Pas d'autorisation de suppression types",noPermissionEditHours:"Pas d'autorisation de modification heures",noPermissionRemovePrinter:"Pas d'autorisation retrait imprimante",noPermissionAssignPrinter:"Pas d'autorisation assignation",noPermissionEditIntervals:"Pas d'autorisation modification intervalles",configureSettings:"Configurer types et intervalles"},settings:{title:"Paramètres",general:"Général",tabs:{general:"Général",smartPlugs:"Prises connectées",notifications:"Notifications",filament:"Filament",network:"Réseau",apiKeys:"Clés API",virtualPrinter:"Imprimante virtuelle",users:"Authentification",backup:"Sauvegarde",emailAuth:"Authentification Email"},email:{smtpSettings:"Configuration SMTP",smtpHost:"Serveur SMTP",smtpPort:"Port SMTP",security:"Sécurité",authentication:"Authentification",username:"Utilisateur",password:"Mot de passe",fromEmail:"Email expéditeur",fromName:"Nom expéditeur",testConnection:"Tester la connexion SMTP",testRecipient:"Email test destinataire",sendTest:"Envoyer email test",sending:"Envoi...",save:"Enregistrer les paramètres",saving:"Enregistrement...",advancedAuth:"Authentification avancée",advancedAuthEnabled:"L'authentification avancée est activée",advancedAuthEnabledDesc:"La gestion des utilisateurs par email est active. Les nouveaux utilisateurs recevront un mot de passe auto-généré.",advancedAuthDisabled:"Authentification avancée désactivée",advancedAuthDisabledDesc:"Activez pour les fonctionnalités liées à l'email (mot de passe oublié, etc).",enable:"Activer",disable:"Désactiver",feature1:"Génération auto et envoi de mots de passe par email",feature2:"Connexion par utilisateur ou email",feature3:"Réinitialisation mot de passe oublié disponible",feature4:"Réinitialisation admin par email",errors:{requiredFields:"Remplissez tous les champs requis",usernameRequired:"L'utilisateur est requis pour l'authentification",enterTestEmail:"Entrez une adresse email de test",smtpServerAndEmail:"Serveur et expéditeur requis pour le test",usernamePasswordRequired:"Utilisateur et mot de passe requis pour l'auth",configureSmtpFirst:"Configurez et testez le SMTP d'abord"},success:{settingsSaved:"Paramètres SMTP enregistrés"},securityOptions:{starttls:"STARTTLS (Port 587)",ssl:"SSL/TLS (Port 465)",none:"Aucun (Port 25)"},authOptions:{enabled:"Activée",disabled:"Désactivée"}},appearance:"Apparence",notifications:"Notifications",smartPlugs:"Prises connectées",spoolman:"Spoolman",updates:"Mises à jour",language:"Langue",languageDescription:"Choisissez votre langue",theme:"Thème",themeLight:"Clair",themeDark:"Sombre",themeSystem:"Système",defaultView:"Vue par défaut",defaultViewDescription:"Page affichée au démarrage",checkForUpdates:"Vérifier les mises à jour",autoUpdate:"Mise à jour auto",currentVersion:"Version actuelle",latestVersion:"Dernière version",upToDate:"Bambuddy est à jour",updateAvailable:"Mise à jour disponible",notificationLanguage:"Langue des notifications",notificationLanguageDescription:"Langue pour les notifications push",bedCooledThreshold:"Seuil de refroidissement du plateau",bedCooledThresholdDescription:"Température en dessous de laquelle le plateau est considéré comme refroidi",notificationProviders:"Fournisseurs de notifications",addProvider:"Ajouter un fournisseur",editProvider:"Modifier le fournisseur",providerType:"Type de fournisseur",testNotification:"Tester la notification",testSuccess:"Notification de test envoyée",testFailed:"Échec de l'envoi du test",quietHours:"Heures de silence",quietHoursDescription:"Ne pas déranger pendant ces heures",quietHoursStart:"Début",quietHoursEnd:"Fin",events:{title:"Événements de notification",printStart:"Impression démarrée",printComplete:"Impression terminée",printFailed:"Impression échouée",printStopped:"Impression arrêtée",printProgress:"Jalons de progression",printProgressDescription:"Notifier à 25%, 50%, 75%",printerOffline:"Imprimante hors ligne",printerError:"Erreur imprimante",filamentLow:"Filament bas",maintenanceDue:"Maintenance due",maintenanceDueDescription:"Notifier quand une tâche est due"},smartPlug:{title:"Prises connectées",add:"Ajouter une prise",edit:"Modifier la prise",name:"Nom",ipAddress:"Adresse IP",linkedPrinter:"Imprimante liée",autoOn:"Allumage auto",autoOnDescription:"Allumer au début de l'impression",autoOff:"Extinction auto",autoOffDescription:"Éteindre après l'impression",offDelay:"Délai d'extinction",offDelayMinutes:"Minutes après fin",offDelayTemp:"Quand la buse est sous",currentState:"État actuel",turnOn:"Allumer",turnOff:"Éteindre"},filamentTracking:"Suivi de Filament",filamentTrackingDesc:"Choisissez comment suivre vos bobines. Utilisez l'inventaire intégré ou connectez un serveur Spoolman.",trackingModeBuiltIn:"Inventaire Intégré",trackingModeBuiltInDesc:"Correspondance RFID et suivi de consommation inclus",trackingModeSpoolmanDesc:"Serveur de gestion externe",builtInFeatureRfid:"Détecte auto les bobines RFID Bambu Lab dans l'AMS",builtInFeatureUsage:"Suit la consommation par impression",builtInFeatureCatalog:"Gère bobines, couleurs et profils facteur K",builtInFeatureThirdParty:"Les bobines tierces peuvent être assignées aux bobines d'inventaire",amsSyncButton:"Synchroniser les poids depuis l'AMS",amsSyncTitle:"Synchroniser les poids des bobines depuis l'AMS",amsSyncMessage:"Tous les poids des bobines de l'inventaire seront écrasés par les valeurs actuelles de l'AMS des imprimantes connectées. Utilisez ceci pour récupérer des données de poids corrompues. Les imprimantes doivent être en ligne.",amsSyncing:"Synchronisation...",amsSyncSuccess:"{{synced}} bobine(s) synchronisée(s), {{skipped}} ignorée(s)",amsSyncError:"Échec de la synchronisation des poids depuis l'AMS",spoolmanUrl:"URL Spoolman",spoolmanUrlHint:"URL de votre serveur Spoolman (ex: http://localhost:7912)",spoolmanConnected:"Connecté",spoolmanDisconnected:"Déconnecté",status:"Statut",connect:"Connecter",disconnect:"Déconnecter",howSyncWorks:"Fonctionnement de la Sync",syncInfoRfidOnly:"Seules les bobines officielles RFID sont synchronisées",syncInfoAutoCreate:"Les bobines sont créées dans Spoolman à la 1ère sync",syncInfoThirdPartySkipped:"Les bobines tierces ou rechargées sont ignorées",linkingExistingSpools:"Lier des bobines existantes",linkingExistingSpoolsDesc:'Pour lier une bobine Spoolman, survolez un slot AMS et cliquez sur "Lier à Spoolman".',syncMode:"Mode de Sync",syncModeAuto:"Automatique",syncModeManual:"Manuel uniquement",syncModeAutoDesc:"Sync auto lors de changements AMS",syncModeManualDesc:"Sync uniquement sur déclenchement manuel",syncAmsData:"Synchroniser AMS",syncAmsDataDesc:"Synchroniser manuellement les données vers Spoolman",allPrinters:"Toutes les imprimantes",noDefaultPrinter:"Aucune par défaut (demander à chaque fois)",sidebarOrder:"Ordre de la barre latérale",saveThumbnails:"Enregistrer les vignettes",captureFinishPhoto:"Prendre une photo à la fin",noPrintersConfigured:"Aucune imprimante configurée",archiveMode:{always:"Toujours créer une archive",never:"Ne jamais créer d'archive",ask:"Demander à chaque fois"},checkForUpdatesLabel:"Vérifier les mises à jour",checkPrinterFirmware:"Vérifier le firmware imprimante",includeBetaUpdates:"Inclure les versions bêta",includeBetaUpdatesDesc:"Notifier des versions bêta et préliminaires lors de la vérification des mises à jour",enableRetry:"Activer la rétentative",homeAssistantDescription:"Contrôler les prises via Home Assistant",environmentManagedLabel:"(Géré par l'environnement)",autoEnabledViaEnv:"Activé via variables d'environnement",urlFromEnvReadOnly:"Valeur HA_URL (lecture seule)",tokenFromEnvReadOnly:"Valeur HA_TOKEN (lecture seule)",mqttConnectedTo:"Connecté à",prometheusDescription:"Exposer les données au format Prometheus",noSmartPlugsTitle:"Aucune prise configurée",noSmartPlugsDescription:"Ajoutez une prise Tasmota pour suivre l'énergie et automatiser.",noProvidersTitle:"Aucun fournisseur configuré",noProvidersDescription:"Ajoutez un fournisseur pour recevoir des alertes.",noTemplatesAvailable:"Aucun modèle dispo. Redémarrez pour les générer.",apiPermissionView:"Voir statut et file",apiPermissionEdit:"Gérer la file d'attente",apiKeysEmptyTitle:"Aucune clé API",apiKeysEmptyDescription:"Créez une clé pour vos intégrations.",noUsersFound:"Aucun utilisateur trouvé",noGroupsFound:"Aucun groupe trouvé",noGroupsAvailable:"Aucun groupe disponible",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",systemGroupWarning:"Les noms des groupes système sont fixes",authDisabledTitle:"Authentification désactivée",authDisabledFeature1:"Requis pour accéder au système",authDisabledFeature2:"Gestion multi-utilisateurs et groupes",authDisabledFeature3:"Plus de 50 permissions granulaires",userHasCreated:"Cet utilisateur a créé :",userItemsQuestion:"Que faire de ces éléments ?",deleteUserConfirm:"Supprimer cet utilisateur ?",actionCannotBeUndone:"Cette action est irréversible.",addFirstSmartPlug:"Ajoutez votre première prise",providers:"Fournisseurs",log:"Journal",testAll:"Tout tester",testResults:"Résultats du test",testPassedCount:"{{count}} succès",testFailedCount:"{{count}} échecs",messageTemplates:"Modèles de message",messageTemplatesDescription:"Personnalisez les messages par événement.",apiKeys:"Clés API",apiKeysDescription:"Créez des clés pour webhooks et API.",createKey:"Créer une clé",apiKeyCreated:"Clé API créée avec succès",apiKeyCopyWarning:"Copiez cette clé maintenant - elle ne sera plus affichée !",useInApiBrowser:"Utiliser dans l'explorateur API",createNewApiKey:"Nouvelle clé API",keyName:"Nom de la clé",keyNamePlaceholder:"ex: Home Assistant, OctoPrint",readStatus:"Lire le statut",readStatusDescription:"Voir les imprimantes et la file",manageQueue:"Gérer la file",manageQueueDescription:"Ajouter/retirer des éléments",controlPrinter:"Contrôler l'imprimante",controlPrinterDescription:"Pause, reprise, arrêt",unnamedKey:"Clé sans nom",lastUsed:"Dernière utilisation",read:"Lecture",control:"Contrôle",createFirstKey:"Créez votre première clé",webhookEndpoints:"Points de terminaison Webhook",webhookApiKeyHint:"Utilisez la clé dans l'en-tête X-API-Key.",webhook:{getAllStatus:"Tous les statuts",getSpecificStatus:"Statut spécifique",addToQueue:"Ajouter à la file",pausePrint:"Pause",resumePrint:"Reprise",stopPrint:"Arrêt"},apiBrowser:"Explorateur API",apiBrowserDescription:"Testez les endpoints API.",apiKeyForTesting:"Clé API pour test",apiKeyPlaceholder:"Collez votre clé pour tester...",apiKeyHint:"Sera envoyée via l'en-tête X-API-Key.",deleteApiKeyTitle:"Supprimer la clé API",deleteApiKeyMessage:"Les intégrations utilisant cette clé cesseront de fonctionner.",deleteKey:"Supprimer la clé",amsDisplayThresholds:"Seuils d'affichage AMS",amsThresholdsDescription:"Seuils de couleur pour humidité et température.",humidity:"Humidité",goodGreen:"Bon (vert)",fairOrange:"Moyen (orange)",aboveFairBad:"Au-dessus = rouge (mauvais)",temperature:"Température",goodBlue:"Bon (bleu)",aboveFairHot:"Au-dessus = rouge (chaud)",historyRetention:"Rétention d'historique",keepSensorHistory:"Garder l'historique pendant",historyRetentionDescription:"Les anciennes données seront supprimées.",printModal:"Fenêtre d'impression",expandCustomMapping:"Étendre le mapping personnalisé par défaut",expandCustomMappingDescription:"Affiche le mapping AMS par imprimante étendu.",authentication:"Authentification",authEnabledDescription:"L'instance est sécurisée",authDisabledDescription:"Activez pour restreindre l'accès",authDisabledMessage:"Activez l'authentification pour gérer comptes et permissions.",enableAuthentication:"Activer l'authentification",currentUser:"Utilisateur actuel",changePassword:"Changer le mot de passe",admin:"Admin",users:"Utilisateurs",addUser:"Ajouter un utilisateur",groups:"Groupes",addGroup:"Ajouter un groupe",system:"Système",noDescription:"Pas de description",userCount:"{{count}} utilisateurs",permissionCount:"{{count}} permissions",createUser:"Créer un utilisateur",username:"Nom d'utilisateur",enterUsername:"Entrez l'utilisateur",password:"Mot de passe",enterPassword:"Mot de passe (min 6 char)",confirmPassword:"Confirmer le mot de passe",confirmPasswordPlaceholder:"Confirmez le mot de passe",viewReleaseOnGitHub:"Voir la version sur GitHub",turnAllPlugsOn:"Tout allumer",turnAllPlugsOff:"Tout éteindre",clearNotificationLogs:"Effacer les journaux",clearLogsMessage:"Efface définitivement les logs de plus de 30 jours.",clearLogs:"Effacer les logs",resetUiPreferences:"Réinitialiser l'UI",resetUiPreferencesMessage:"Réinitialise l'ordre, thème, widgets, etc. N'affecte pas vos données.",resetPreferences:"Réinitialiser",deleteGroupTitle:"Supprimer le groupe",deleteGroupMessage:"Les utilisateurs de ce groupe perdront ces permissions.",deleteGroup:"Supprimer le groupe",disableAuthenticationTitle:"Désactiver l'authentification",disableAuthenticationMessage:"Instance accessible sans connexion. Les comptes sont conservés.",disableAuthentication:"Désactiver",configureBambuddy:"Configurer Bambuddy",systemDefault:"Défaut système",archiveSettings:"Réglages Archives",newWindow:"Nouvelle fenêtre",embeddedOverlay:"Superposition intégrée",preferredSlicer:"Slicer préféré",preferredSlicerDescription:"Application pour ouvrir les fichiers",externalCameras:"Caméras externes",costTracking:"Suivi des coûts",printsOnly:"Impressions uniquement",totalConsumption:"Consommation totale",dataManagement:"Gestion des données",storageUsage:"Utilisation du stockage",storageUsageDescription:"Répartition de l'utilisation des données par catégorie",storageUsageTotal:"Total",storageUsageErrors:"Erreurs",storageUsageOtherBreakdown:"Autre (inclut ressources statiques, scripts et fichiers de configuration)",storageUsageSystem:"Système",storageUsageData:"Données",storageUsageUnavailable:"Informations d'utilisation du stockage non disponibles",clearNotificationLogsDescription:"Supprimer logs de plus de 30 jours",resetUiPreferencesDescription:"Réinitialise thèmes et affichage sans toucher aux données.",enableHomeAssistant:"Activer Home Assistant",enableMqtt:"Activer MQTT",useTls:"Utiliser TLS",enableMetricsEndpoint:"Activer l'endpoint Metrics",availableMetrics:"Metrics disponibles",editUser:"Modifier l'utilisateur",deleteUserTitle:"Supprimer l'utilisateur",groupName:"Nom du groupe",leaveEmptyForAnonymous:"Vide pour anonyme",leaveEmptyForNoAuth:"Vide si pas d'auth",enterNewPassword:"Nouveau mot de passe",confirmNewPassword:"Confirmer nouveau mdp",enterGroupName:"Entrez le nom du groupe",enterDescriptionOptional:"Description (optionnel)",enterCurrentPassword:"Mdp actuel",enterNewPasswordMin6:"Nouveau mdp (min 6 char)",toast:{keyCopied:"Clé copiée",copyFailed:"Échec copie",keyAddedToBrowser:"Clé ajoutée à l'explorateur",clearLogsFailed:"Échec effacement logs",uiPreferencesReset:"Préférences UI réinitialisées. Rafraîchissement...",authDisabled:"Authentification désactivée",authDisableFailed:"Échec désactivation",apiKeyCreated:"Clé API créée",apiKeyDeleted:"Clé API supprimée",userCreated:"Utilisateur créé",userUpdated:"Utilisateur mis à jour",userDeleted:"Utilisateur supprimé",groupCreated:"Groupe créé",groupUpdated:"Groupe mis à jour",groupDeleted:"Groupe supprimé",fillRequiredFields:"Remplissez les champs requis",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères",enterGroupName:"Entrez un nom de groupe",settingsSaved:"Paramètres enregistrés",cameraSettingsSaved:"Réglages caméra enregistrés",enterCameraUrl:"Entrez une URL caméra",passwordChanged:"Mot de passe modifié",connectionFailed:"Échec connexion",testFailed:"Échec test",cameraConnected:"Caméra connectée {{resolution}}"},testConnection:"Tester la connexion",catalog:{spoolCatalog:"Catalogue de Bobines",spoolCatalogDescription:"Poids des bobines vides par marque/type. Utilisé pour le calcul auto du poids restant.",searchCatalog:"Chercher dans le catalogue...",addNewEntry:"Nouvelle Entrée",namePlaceholder:"Nom (ex: Bambu Lab - Plastique)",weight:"Poids",type:"Type",default:"Défaut",custom:"Perso",noMatch:"Aucune entrée correspondante",empty:"Catalogue vide",deleteEntry:"Supprimer l'entrée",deleteConfirm:'Supprimer "{{name}}" ?',resetCatalog:"Réinitialiser le catalogue",resetConfirm:"Réinitialiser aux valeurs par défaut ? Vos entrées personnalisées seront supprimées.",loadFailed:"Échec chargement catalogue",nameWeightRequired:"Nom et poids requis",entryAdded:"Entrée ajoutée",addFailed:"Échec ajout",entryUpdated:"Entrée mise à jour",updateFailed:"Échec mise à jour",entryDeleted:"Entrée supprimée",deleteFailed:"Échec suppression",resetSuccess:"Catalogue réinitialisé",resetFailed:"Échec réinitialisation",exported:"{{count}} entrées exportées",imported:"{{added}} entrées importées ({{skipped}} ignorées)",importFailed:"Échec import : format JSON invalide",exportTooltip:"Exporter en JSON",importTooltip:"Importer depuis JSON",resetTooltip:"Réinitialiser par défaut"},colorCatalog:{title:"Catalogue de Couleurs",description:"Couleurs de filament par fabricant. Utilisé pour la recherche auto lors de l'ajout de bobines.",searchColors:"Chercher couleurs...",allManufacturers:"Tous les fabricants",addNewColor:"Nouvelle Couleur",manufacturer:"Fabricant",colorName:"Nom couleur",hex:"Hex",materialOptional:"Matériau (optionnel)",showing:"Affichage {{filtered}} sur {{total}} couleurs",noMatch:"Aucune couleur correspondante",empty:"Catalogue vide",deleteColor:"Supprimer couleur",deleteConfirm:'Supprimer "{{name}}" ?',resetCatalog:"Réinitialiser catalogue couleurs",resetConfirm:"Réinitialiser aux valeurs par défaut ?",sync:"Sync",starting:"Démarrage...",syncTooltip:"Sync depuis FilamentColors.xyz (2000+ couleurs, peut être long)",loadFailed:"Échec chargement catalogue couleurs",fieldsRequired:"Fabricant, nom et code Hex requis",colorAdded:"Couleur ajoutée",addFailed:"Échec ajout",colorUpdated:"Couleur mise à jour",updateFailed:"Échec mise à jour",colorDeleted:"Couleur supprimée",deleteFailed:"Échec suppression",resetSuccess:"Catalogue réinitialisé",resetFailed:"Échec réinitialisation",syncUpToDate:"Déjà à jour ({{count}} couleurs vérifiées)",syncComplete:"{{added}} couleurs ajoutées ({{skipped}} déjà présentes)",syncError:"Erreur de sync",syncFailed:"Échec sync FilamentColors.xyz",exported:"{{count}} couleurs exportées",imported:"{{added}} couleurs importées ({{skipped}} ignorées)",importFailed:"Échec import : format JSON invalide"}},notification:{printStarted:{title:"Impression démarrée",body:"{{printer}} : {{filename}} commence l'impression"},printCompleted:{title:"Impression terminée",body:"{{printer}} : {{filename}} a réussi"},printFailed:{title:"Impression échouée",body:"{{printer}} : {{filename}} a échoué"},printStopped:{title:"Impression arrêtée",body:"{{printer}} : {{filename}} a été arrêtée"},printProgress:{title:"Progression d'impression",body:"{{printer}} : {{filename}} est à {{percent}}%"},printerOffline:{title:"Imprimante hors ligne",body:"{{printer}} est déconnectée"},printerError:{title:"Erreur imprimante",body:"{{printer}} : {{error}}"},filamentLow:{title:"Filament bas",body:"{{printer}} : Le filament est presque vide"},maintenanceDue:{title:"Maintenance due",body:"{{printer}} : {{items}} demandent votre attention"}},errors:{generic:"Une erreur est survenue",networkError:"Erreur réseau. Vérifiez votre connexion.",notFound:"Non trouvé",unauthorized:"Non autorisé",serverError:"Erreur serveur",validationError:"Vérifiez vos saisies",printerConnectionFailed:"Échec connexion imprimante",saveFailed:"Échec enregistrement",deleteFailed:"Échec suppression",loadFailed:"Échec chargement"},hmsErrors:{title:"Erreurs - {{name}}",noErrors:"Aucune erreur",viewOnWiki:"Voir sur le Wiki Bambu Lab",clearInstructions:"Effacez les erreurs sur l'imprimante pour les retirer ici.",clearErrors:"Effacer les erreurs",clearSuccess:"Erreurs HMS effacées",clearFailed:"Échec de l'effacement des erreurs HMS"},mqttDebug:{title:"Journal de débogage MQTT",searchPlaceholder:"Chercher topic ou message...",noMessages:"Aucun message enregistré",startLoggingHint:'Cliquez sur "Démarrer" pour capturer les messages MQTT',noMessagesMatch:"Aucun message ne correspond",adjustFilterHint:"Ajustez votre recherche",incoming:"Entrant",outgoing:"Sortant",loggingStopped:"Enregistrement arrêté",loggingActive:"Enregistrement actif - rafraîchissement auto",startLogging:"Démarrer",stopLogging:"Arrêter",clearLog:"Effacer le journal",topic:"Topic",timestamp:"Horodatage",direction:"Direction",all:"Tous"},printerFiles:{title:"Gestionnaire de fichiers",storageUsed:"Utilisé :",storageFree:"Libre :",filterPlaceholder:"Filtrer les fichiers...",deleteButton:"Supprimer",deleteFiles:"Supprimer {{count}} fichiers",deleteFileConfirm:'Supprimer "{{name}}" ?',deleteFilesConfirm:"Supprimer les {{count}} fichiers sélectionnés ?",noFiles:"Aucun fichier sur l'imprimante",loadingFiles:"Chargement...",failedToLoad:"Échec chargement fichiers",toast:{filesDeleted:"{{count}} fichier(s) supprimé(s)",deleteFailed:"Échec suppression : {{error}}"}},confirm:{delete:"Voulez-vous vraiment supprimer cet élément ?",unsavedChanges:"Changements non sauvegardés. Voulez-vous quitter ?",clearQueue:"Voulez-vous vraiment vider la file d'attente ?"},login:{title:"Connexion Bambuddy",subtitle:"Connectez-vous à votre compte",username:"Utilisateur",usernamePlaceholder:"Entrez votre utilisateur",usernameOrEmail:"Utilisateur ou Email",usernameOrEmailPlaceholder:"Utilisateur ou @ Email",password:"Mot de passe",passwordPlaceholder:"Entrez votre mot de passe",signIn:"Se connecter",signingIn:"Connexion...",forgotPassword:"Mot de passe oublié ?",loginSuccess:"Connecté avec succès",loginFailed:"Échec de connexion",enterCredentials:"Entrez vos identifiants",forgotPasswordTitle:"Mot de passe oublié",forgotPasswordMessage:"Contactez votre administrateur pour réinitialiser votre accès.",forgotPasswordEmailMessage:"Entrez votre email pour recevoir un nouveau mot de passe.",emailAddress:"Adresse Email",emailPlaceholder:"votre.email@exemple.com",cancel:"Annuler",sending:"Envoi...",sendResetEmail:"Envoyer l'email",howToReset:"Comment réinitialiser :",resetStep1:"Contactez votre admin Bambuddy",resetStep2:"Demandez une réinitialisation dans la Gestion Utilisateurs",resetStep3:"Il vous donnera un mot de passe temporaire",resetStep4:"Connectez-vous et changez-le dans les Paramètres",gotIt:"Compris"},setup:{title:"Configuration Bambuddy",subtitle:"Configurez l'authentification",enableAuth:"Activer l'authentification",adminAccount:"Compte Admin",adminAccountDesc:"Si des admins existent, ils seront utilisés. Sinon, créez-en un ci-dessous.",adminUsername:"Utilisateur Admin",adminPassword:"Mot de passe Admin",optionalIfAdminExists:"(optionnel si admin existe)",adminUsernamePlaceholder:"Nom admin (optionnel)",adminPasswordPlaceholder:"Mdp admin (optionnel)",confirmPassword:"Confirmer mdp",confirmPasswordPlaceholder:"Confirmez mdp admin",settingUp:"Configuration...",completeSetup:"Terminer la configuration",toast:{authEnabledAdminCreated:"Authentification activée et admin créé",authEnabledExistingAdmins:"Authentification activée avec admins existants",setupCompleted:"Configuration terminée",enterBothCredentials:"Entrez les deux ou laissez vide pour utiliser les admins existants",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères"}},changePassword:{title:"Changer le mot de passe",currentPassword:"Mot de passe actuel",currentPasswordPlaceholder:"Entrez mdp actuel",newPassword:"Nouveau mot de passe",newPasswordPlaceholder:"Nouveau mdp (min 6 char)",confirmPassword:"Confirmer nouveau mdp",confirmPasswordPlaceholder:"Confirmez nouveau mdp",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères",changing:"Changement...",success:"Mot de passe modifié",failed:"Échec modification"},plateAlert:{title:"Impression en Pause !",message:"Objets détectés sur le plateau. L'impression a été suspendue automatiquement. Videz le plateau avant de reprendre.",understand:"J'ai compris"},camera:{title:"Vue Caméra",invalidPrinterId:"ID imprimante invalide",live:"Direct",snapshot:"Instantané",restartStream:"Redémarrer le flux",refreshSnapshot:"Rafraîchir l'image",fullscreen:"Plein écran",exitFullscreen:"Quitter plein écran",connectingToCamera:"Connexion caméra...",capturingSnapshot:"Capture...",connectionLost:"Connexion perdue",connectionFailed:"Échec connexion caméra",reconnecting:"Reconnexion dans {{countdown}}s... (essai {{attempt}}/{{max}})",reconnectNow:"Reconnexion immédiate",cameraUnavailable:"Caméra indisponible",cameraUnavailableDesc:"Vérifiez que l'imprimante est allumée.",noCamera:"Aucune caméra disponible",retry:"Réessayer",cameraStream:"Flux caméra",zoomOut:"Zoom arrière",zoomIn:"Zoom avant",resetZoom:"Réinitialiser zoom",recording:"Enregistrement",startRecording:"Démarrer l'enregistrement",stopRecording:"Arrêter l'enregistrement",chamberLight:"Basculer lumière chambre"},groups:{title:"Gestion des Groupes",subtitle:"Gérez les permissions pour le contrôle d'accès",backToSettings:"Retour aux paramètres",createGroup:"Créer un groupe",noPermission:"Accès refusé.",system:"Système",noDescription:"Pas de description",usersCount:"{{count}} utilisateurs",permissionsCount:"{{count}} permissions",edit:"Modifier",delete:"Supprimer",toast:{created:"Groupe créé",updated:"Groupe mis à jour",deleted:"Groupe supprimé",enterGroupName:"Entrez un nom de groupe"},modal:{editGroup:"Modifier le groupe",createGroup:"Créer un groupe",cancel:"Annuler",saving:"Enregistrement...",creating:"Création...",saveChanges:"Enregistrer"},form:{groupName:"Nom du groupe",groupNamePlaceholder:"Nom du groupe",systemGroupWarning:"Les groupes système sont fixes",description:"Description",descriptionPlaceholder:"Description (optionnel)",permissions:"Permissions ({{count}} sélectionnées)"},deleteModal:{title:"Supprimer le groupe",message:"Les utilisateurs de ce groupe perdront ces permissions.",confirm:"Supprimer"},editor:{title:"Modifier le groupe",createTitle:"Créer un groupe",search:"Rechercher des permissions...",selectAll:"Tout sélectionner",clearAll:"Tout désélectionner",permissionsSelected:"{{count}} sélectionnée(s)",noResults:"Aucune permission ne correspond à votre recherche"}},users:{title:"Gestion des Utilisateurs",subtitle:"Gérez les accès à Bambuddy",backToSettings:"Retour aux paramètres",createUser:"Créer un utilisateur",noPermission:"Accès refusé.",admin:"Admin",noGroups:"Aucun groupe",active:"Actif",inactive:"Inactif",edit:"Modifier",delete:"Supprimer",system:"Système",noGroupsAvailable:"Aucun groupe disponible",table:{username:"Utilisateur",groups:"Groupes",status:"Statut",actions:"Actions"},toast:{created:"Utilisateur créé",updated:"Utilisateur mis à jour",deleted:"Utilisateur supprimé",fillRequired:"Remplissez les champs requis",passwordsDoNotMatch:"Les mots de passe ne correspondent pas",passwordTooShort:"Minimum 6 caractères"},modal:{createUser:"Créer utilisateur",editUser:"Modifier utilisateur",cancel:"Annuler",creating:"Création...",saving:"Enregistrement...",saveChanges:"Enregistrer",advancedAuthSubtitle:"avec Authentification Avancée"},form:{username:"Utilisateur",usernamePlaceholder:"Nom utilisateur",email:"Email",emailPlaceholder:"utilisateur@exemple.com",password:"Mot de passe",passwordPlaceholder:"Mot de passe",confirmPassword:"Confirmer mdp",confirmPasswordPlaceholder:"Confirmez mdp",newPasswordPlaceholder:"Nouveau mdp",confirmNewPasswordPlaceholder:"Confirmez nouveau mdp",leaveBlankToKeep:"Laissez vide pour conserver l'actuel",groups:"Groupes",optional:"optionnel",autoGeneratedPassword:"Un mot de passe sera généré et envoyé par email.",passwordManagedByAdvancedAuth:'Géré par Auth Avancée. Utilisez "Réinitialiser" pour envoyer un nouveau mdp par email.',resetPassword:"Réinitialiser le mot de passe",resettingPassword:"Réinitialisation..."},deleteModal:{title:"Supprimer utilisateur",message:"Cette action est irréversible.",confirm:"Supprimer"}},streamOverlay:{title:"Superposition Flux",invalidPrinterId:"ID invalide",cameraStream:"Flux caméra",progress:"Progression",eta:"Fin estimée",printerIdle:"Imprimante inactive",printerOffline:"Imprimante hors ligne",status:{printing:"Impression",paused:"En pause",finished:"Terminée",failed:"Échouée",idle:"Inactive",unknown:"Inconnue"}},profiles:{title:"Profils",subtitle:"Gérez vos presets slicer et calibrations Pressure Advance",tabs:{cloud:"Profils Cloud",local:"Profils Locaux",kprofiles:"K-Profiles"},localProfiles:{title:"Profils Locaux",subtitle:"Gérez vos presets OrcaSlicer",import:"Importer Profils",importDesc:"Déposez les fichiers .bbscfg, .bbsflmt, .orca_filament, .zip ou .json",importing:"Importation...",search:"Chercher un preset...",noPresets:"Aucun preset local",badge:"Local",edit:"Modifier",delete:"Supprimer",cancel:"Annuler",deleteConfirmTitle:"Supprimer Preset",deleteConfirm:"Supprimer définitivement ce preset ?",source:"Source",inheritsFrom:"Hérite de",filamentType:"Type",vendor:"Vendeur",compatiblePrinters:"Imprimantes",nozzleTemp:"Temp Buse",cost:"Coût",density:"Densité",pressureAdvance:"Pressure Advance",filament:"Filament",process:"Processus",printer:"Imprimante",toast:{importSuccess:"{{count}} profil(s) importé(s)",importSkipped:"{{count}} profil(s) ignoré(s) (doublons)",importError:"{{count}} erreur(s) d'import",deleted:"Preset supprimé",updated:"Preset mis à jour"}},connectedAs:"Connecté en tant que",logout:"Déconnexion",noLogoutPermission:"Pas d'autorisation de déconnexion",failedToLoad:"Échec chargement profils",retry:"Réessayer",time:{justNow:"À l'instant",minsAgo:"Il y a {{count}}m",hoursAgo:"Il y a {{count}}h",daysAgo:"Il y a {{count}}j"},toast:{loggedOut:"Déconnecté"},login:{title:"Connexion Bambu Cloud",subtitle:"Synchronisez vos presets slicer",email:"Email",password:"Mot de passe",region:"Région",regionGlobal:"Global",regionChina:"Chine",verificationCode:"Code de vérification",totpCode:"Code Authenticator",checkEmail:"Code envoyé à {{email}}",enterTotpHint:"Entrez le code 2FA",accessToken:"Jeton d'accès (Access Token)",accessTokenHint:"Collez le jeton (depuis Bambu Studio)",back:"Retour",loginButton:"Connexion",verifyButton:"Vérifier",setTokenButton:"Définir Jeton",useToken:"Utiliser jeton d'accès",useEmail:"Connexion par email",toast:{loggedIn:"Connecté avec succès",codeSent:"Code envoyé par email",enterTotp:"Entrez le code Authenticator",tokenSet:"Jeton défini"}},presets:{myPreset:"Mon preset (modifiable)",duplicate:"Dupliquer",editable:"Modifiable",failedToLoadDetails:"Échec détails preset",deleteConfirm:"Supprimer ce preset ?",deleteWarning:'Ceci supprimera "{{name}}" de Bambu Cloud définitivement.',noDuplicatePermission:"Pas d'autorisation duplication",noEditPermission:"Pas d'autorisation modification",noDeletePermission:"Pas d'autorisation suppression",types:{filament:"Preset filament",printer:"Preset imprimante",process:"Preset processus"},toast:{deleted:"Preset supprimé",created:"Preset créé",updated:"Preset mis à jour",duplicated:"Preset dupliqué",fieldAdded:'Champ "{{key}}" ajouté',exported:"Preset exporté"},baseLabel:"Base : {{name}}",currentLabel:"Actuel : {{name}}",newPreset:"Nouveau Preset",editPreset:"Modifier Preset",duplicatePreset:"Dupliquer Preset",createNewPreset:"Créer un nouveau Preset",customizeSettings:"Personnalisez vos réglages",compareWithBase:"Comparer avec la base",compare:"Comparer",basePreset:"Preset de base",selectBasePreset:"Choisir preset de base...",presetName:"Nom du preset",myCustomPreset:"Mon preset personnalisé",inheritsFrom:"Hérite de",dropJsonToImport:"Glissez JSON pour importer",tabs:{common:"Commun",allFields:"Tous les champs"},availableFields:"Champs disponibles",searchFieldsPlaceholder:"Chercher un champ...",noMatchingFields:"Aucun champ trouvé",allFieldsAdded:"Tous les champs sont ajoutés",addCustomField:"Ajouter un champ personnalisé",yourOverrides:"Vos modifications",noOverridesYet:"Aucune modification",clickFieldsToAdd:"Cliquez à gauche pour ajouter",saveAsTemplate:"Enregistrer comme modèle",jsonTip:"Conseil : Glissez un .json pour importer les réglages"},cloudView:{searchPlaceholder:"Chercher presets...",templates:"Modèles",refresh:"Rafraîchir",newPreset:"Nouveau Preset",clearFilters:"Effacer filtres",compareMode:"Mode Comparaison",selectAnotherPreset:"Choisir un autre preset {{type}}",clickTwoPresets:"Choisissez deux presets de même type",selectFirst:"1. Sélectionner premier",selectSecond:"2. Sélectionner second",compareNow:"Comparer maintenant",lastSynced:"Synchronisé :",showingCount:"{{showing}} sur {{total}} presets",noPresetsFound:"Aucun preset trouvé",columns:{filament:"Filament",process:"Processus",printer:"Imprimante"},noFilamentPresets:"Pas de preset filament",noProcessPresets:"Pas de preset processus",noPrinterPresets:"Pas de preset imprimante",filters:{type:"Type",owner:"Propriétaire",printer:"Imprimante",nozzle:"Buse",filament:"Filament",layer:"Couche",all:"Tous",myPresets:"Mes Presets",builtIn:"Inclus",process:"Processus"},noTemplatesPermission:"Pas d'autorisation modèles",noRefreshPermission:"Pas d'autorisation rafraîchissement",noCreatePermission:"Pas d'autorisation création"},templates:{title:"Modèles rapides",noTemplates:"Aucun modèle",createFirst:"Créez-en depuis l'éditeur de preset",typeFilter:"Type :",deleteTitle:"Supprimer modèle",deleteWarning:"Action irréversible",deleteConfirm:'Supprimer "{{name}}" ?',namePlaceholder:"Nom du modèle",descriptionPlaceholder:"Description",settingsJson:"Paramètres (JSON)",fieldsCount:"{{count}} champs",shownInModals:"Visible dans fenêtres",hiddenInModals:"Masqué dans fenêtres",apply:"Appliquer",toast:{deleted:"Modèle supprimé",updated:"Modèle mis à jour",created:"Modèle créé",applied:"Modèle appliqué"}}},support:{debugLoggingActive:"Débogage actif",manageLogs:"Gérer",collectItem7:"Connectivité et versions firmware",collectItem8:"Statut intégrations (Spoolman, MQTT, HA)",collectItem9:"Interfaces réseau (sous-réseaux)",collectItem10:"Versions packages Python",collectItem11:"Santé base de données",collectItem12:"Détails environnement Docker"},fileManager:{title:"Gestionnaire de fichiers",subtitle:"Organisez vos fichiers d'impression",uploadFiles:"Téléverser fichiers",newFolder:"Nouveau dossier",folderName:"Nom du dossier",folderNamePlaceholder:"ex: Pièces Utiles",renameFile:"Renommer fichier",renameFolder:"Renommer dossier",moveFiles:"Déplacer {{count}} fichier(s)",rootNoFolder:"Racine (aucun dossier)",current:"actuel",linkFolder:"Lier le dossier",linkFolderDescription:'Lier "{{name}}" à un projet ou archive.',project:"Projet",archive:"Archive",noProjectsFound:"Aucun projet trouvé",noArchivesFound:"Aucune archive trouvée",unlink:"Délier",link:"Lier",dragDropFiles:"Glissez les fichiers ici",dropFilesHere:"Déposez ici",orClickToBrowse:"ou cliquez pour parcourir",allFileTypesSupported:"Tous types supportés. ZIP extraits.",zipFilesDetected:"ZIP détectés",zipExtractOptions:"Choix de structure pour ZIP :",preserveZipStructure:"Garder structure ZIP",createFolderFromZip:"Dossier par nom du ZIP",stlThumbnailGeneration:"Vignettes STL",zipMayContainStl:"Extraction vignettes possible pour STL.",thumbnailsCanBeGenerated:"Génération vignettes (peut être long).",generateThumbnailsForStl:"Générer vignettes STL",threemfDetected:"Fichiers 3MF détectés",threemfExtractionInfo:"Réglages extraits auto du 3MF.",willBeExtracted:"Sera extrait",filesExtracted:"{{count}} fichiers extraits",uploadComplete:"Terminé : {{succeeded}} succès",uploadFailed:"{{count}} échecs",uploading:"Téléversement...",changeLink:"Modifier lien...",linkTo:"Lier à...",linkToProjectOrArchive:"Lier à projet ou archive",addToQueue:"Ajouter à la file",schedulePrint:"Planifier",generateThumbnail:"Générer vignette",generateThumbnails:"Générer vignettes",generateThumbnailsForMissing:"Vignettes STL manquantes",gridView:"Grille",listView:"Liste",lowDiskSpaceWarning:"Espace disque faible",lowDiskSpaceDetails:"{{free}} libre sur {{total}}. Seuil : {{threshold}} Go.",files:"Fichiers",folders:"Dossiers",size:"Taille",free:"Libre",allFiles:"Tous les fichiers",wrap:"Retour ligne",enableTextWrapping:"Activer retour ligne",disableTextWrapping:"Désactiver retour ligne",dragToResizeTooltip:"Glisser pour redimensionner, double-clic reset",searchFiles:"Chercher fichiers...",allTypes:"Tous types",prints:"Impressions",ascending:"Croissant",descending:"Décroissant",resultsCount:"{{showing}} sur {{total}} fichiers",selectAll:"Tout sélectionner",deselectAll:"Tout désélectionner",selected:"{{count}} sélectionnés",adding:"Ajout...",loadingFiles:"Chargement...",folderIsEmpty:"Dossier vide",noFilesYet:"Aucun fichier",folderEmptyDescription:"Téléversez ou déplacez des fichiers ici.",noFilesDescription:"Téléversez des fichiers pour organiser.",noMatchingFiles:"Aucun fichier correspondant",noMatchingFilesDescription:"Ajustez votre recherche.",clearFilters:"Effacer filtres",printedCount:"Imprimé {{count}}x",uploadedBy:"Téléversé par",deleteFolder:"Supprimer dossier",deleteFile:"Supprimer fichier",deleteFilesCount:"Supprimer {{count}} fichiers",deleteFolderConfirm:"Supprimer le dossier et son contenu ?",deleteFileConfirm:"Supprimer ce fichier ?",deleteFilesConfirm:"Supprimer {{count}} fichiers définitivement ?",deleting:"Suppression...",noPermissionRenameFolder:"Pas d'autorisation renommage",noPermissionLinkFolder:"Pas d'autorisation lien",noPermissionDeleteFolder:"Pas d'autorisation suppression dossier",noPermissionPrint:"Pas d'autorisation impression",noPermissionAddToQueue:"Pas d'autorisation file",noPermissionDownload:"Pas d'autorisation téléchargement",noPermissionRenameFile:"Pas d'autorisation renommage fichier",noPermissionGenerateThumbnail:"Pas d'autorisation vignettes",noPermissionDeleteFile:"Pas d'autorisation suppression fichier",noPermissionCreateFolder:"Pas d'autorisation nouveau dossier",noPermissionUpload:"Pas d'autorisation téléversement",noPermissionMoveFiles:"Pas d'autorisation déplacement",noPermissionDeleteFiles:"Pas d'autorisation suppression groupée",toast:{folderCreated:"Dossier créé",folderDeleted:"Dossier supprimé",fileDeleted:"Fichier supprimé",filesDeleted:"{{count}} fichiers supprimés",filesMoved:"Fichiers déplacés",folderLinked:"Dossier lié",folderUnlinked:"Dossier délié",addedToQueue:"{{count}} fichier(s) ajouté(s)",addedToQueuePartial:"{{added}} ajoutés, {{failed}} échecs",failedToAddToQueue:"Échec ajout file : {{error}}",fileRenamed:"Fichier renommé",folderRenamed:"Dossier renommé",thumbnailsGenerated:"{{count}} vignette(s) générée(s)",thumbnailsGeneratedPartial:"{{succeeded}} succès, {{failed}} échecs",noStlMissingThumbnails:"Aucun STL sans vignette",failedToGenerateThumbnails:"Échec vignettes : {{error}}",thumbnailGenerated:"Vignette générée",failedToGenerateThumbnail:"Échec vignette : {{error}}"}},projects:{title:"Projets",subtitle:"Suivez vos projets d'impression 3D",newProject:"Nouveau Projet",editProject:"Modifier Projet",deleteProject:"Supprimer Projet",projectName:"Nom du Projet",description:"Description",noProjects:"Aucun projet",noProjectsFiltered:"Aucun projet {{status}}",noProjectsFilteredHelp:"Les projets apparaîtront ici quand leur statut changera.",createFirst:"Créez votre premier projet pour organiser vos builds.",createFirstButton:"Créer votre premier projet",create:"Créer",files:"Fichiers",prints:"Impressions",plates:"plateaux",parts:"pièces",lastModified:"Modifié le",deleteConfirm:"Supprimer ce projet ? Les archives seront déliées mais conservées.",addFiles:"Ajouter fichiers",removeFile:"Retirer fichier",viewDetails:"Détails",namePlaceholder:"ex: Build Voron 2.4",descriptionPlaceholder:"Description optionnelle...",color:"Couleur",targetPlates:"Plateaux cibles",targetPlatesPlaceholder:"ex: 25",targetPlatesHelp:"Nombre total de jobs",targetParts:"Pièces cibles",targetPartsPlaceholder:"ex: 150",targetPartsHelp:"Nombre total d'objets",tagsLabel:"Tags (séparés par virgules)",tagsPlaceholder:"ex: voron, cadeau",dueDate:"Échéance",priority:"Priorité",priorityLow:"Basse",priorityNormal:"Normale",priorityHigh:"Haute",priorityUrgent:"Urgente",statusActive:"Actif",statusCompleted:"Terminé",statusArchived:"Archivé",done:"Fait",completed:"terminé",failed:"échoué",inQueue:"en file",noPrintsYet:"Aucune impression",printJobs:"Jobs (plateaux)",partsPrinted:"Pièces imprimées",failedParts:"Pièces échouées",import:"Importer",export:"Exporter",importProject:"Importer projet",exportAll:"Exporter tous les projets",loading:"Chargement des projets...",noEditPermission:"Pas d'autorisation de modification",noDeletePermission:"Pas d'autorisation de suppression",noCreatePermission:"Pas d'autorisation de création",noImportPermission:"Pas d'autorisation d'import",noExportPermission:"Pas d'autorisation d'export",toast:{created:"Projet créé",updated:"Projet mis à jour",deleted:"Projet supprimé",imported:"Projet importé",multipleImported:"{{count}} projets importés",importFailed:"Échec d'import",exported:"Projets exportés (métadonnées)"}},projectDetail:{notFound:"Projet non trouvé",backToProjects:"Retour aux Projets",export:"Exporter",exportProject:"Exporter projet",noExportPermission:"Pas d'autorisation export",noEditPermission:"Pas d'autorisation modification",partOf:"Fait partie de :",priorityLabel:"Priorité :",noPrints:"Aucune impression dans ce projet",status:{active:"Actif",completed:"Terminé",archived:"Archivé"},priority:{low:"Basse",normal:"Normale",high:"Haute",urgent:"Urgente"},dueDate:{overdue:"En retard",today:"Aujourd'hui",daysLeft:"{{count}} jours restants"},progress:{platesProgress:"Progression Plateaux",partsProgress:"Progression Pièces",printJobs:"jobs d'impression",parts:"pièces",percentComplete:"{{percent}}% terminé",remaining:"{{count}} restant(s)"},stats:{printJobs:"Jobs d'Impression",total:"total",failed:"{{count}} échecs",partsPrinted:"{{count}} pièces imprimées",printTime:"Temps d'Impression",filamentUsed:"Filament utilisé"},cost:{title:"Suivi des coûts",filamentCost:"Coût Filament",energy:"Énergie",budget:"Budget",remaining:"Restant"},subProjects:{title:"Sous-projets ({{count}})"},notes:{title:"Notes",noEditPermission:"Pas d'autorisation modification",placeholder:"Ajouter des notes...",empty:"Aucune note. Cliquez sur modifier."},files:{title:"Fichiers",linkFolders:"Liez des dossiers depuis le gestionnaire",forQuickAccess:"pour un accès rapide.",fileCount:"{{count}} fichier(s)",empty:"Aucun dossier lié."},bom:{title:"BOM (Liste matériel)",acquired:"{{completed}}/{{total}} acquis",showAll:"Tout afficher",hideDone:"Masquer acquis",addPart:"Ajouter matériel",noAddPermission:"Pas d'autorisation ajout",partNamePlaceholder:"Nom (ex: Vis M3x8)",partName:"Nom de pièce",qty:"Qté",price:"Prix ({{currency}})",sourcingUrlPlaceholder:"Lien d'achat (optionnel)",remarksPlaceholder:"Remarques (optionnel)",deletePart:"Supprimer pièce",deleteConfirm:'Supprimer "{{name}}" ?',noUpdatePermission:"Pas d'autorisation mise à jour",noEditPermission:"Pas d'autorisation modification",noDeletePermission:"Pas d'autorisation suppression",totalCost:"Coût total :",empty:"BOM vide. Ajoutez du matériel ou de l'électronique."},timeline:{title:"Historique d'activité",empty:"Aucune activité."},template:{saveAsTemplate:"Enregistrer comme modèle",noCreatePermission:"Pas d'autorisation modèle"},queue:{title:"File d'attente",viewAll:"Tout voir",printing:"{{count}} en cours",queued:"{{count}} en file"},prints:{title:"Impressions ({{count}})"},toast:{projectUpdated:"Projet mis à jour",partAdded:"Pièce ajoutée",partRemoved:"Pièce retirée",exportFailed:"Échec export",projectExported:"Projet exporté",templateCreated:"Modèle créé"}},system:{title:"Informations Système",version:"Version",uptime:"Temps de fonctionnement",cpuUsage:"Utilisation CPU",memoryUsage:"Utilisation RAM",diskUsage:"Utilisation Disque",networkInfo:"Infos Réseau",logs:"Journaux",debugMode:"Mode Débogage",enableDebug:"Activer débogage",disableDebug:"Désactiver débogage",downloadLogs:"Télécharger logs",clearLogs:"Effacer logs",dockerInfo:"Infos Docker",containerName:"Nom conteneur",imageName:"Nom image",platform:"Plateforme",architecture:"Architecture"},library:{title:"Bibliothèque Filament",addFilament:"Ajouter Filament",editFilament:"Modifier Filament",deleteFilament:"Supprimer Filament",vendor:"Vendeur",material:"Matériau",color:"Couleur",kFactor:"Facteur K",temperature:"Température",noFilaments:"Bibliothèque vide",deleteConfirm:"Supprimer ce filament ?",importFromPrinter:"Importer de l'imprimante",exportToFile:"Exporter vers fichier"},spoolman:{title:"Intégration Spoolman",enabled:"Spoolman Activé",url:"URL Spoolman",connected:"Connecté",disconnected:"Non Connecté",testConnection:"Tester connexion",sync:"Synchroniser",syncing:"Sync...",lastSync:"Dernière Sync",linkToSpoolman:"Lier à Spoolman",openInSpoolman:"Ouvrir Spoolman",unlinkSpool:"Délier bobine",selectSpool:"Choisir bobine",noUnlinkedSpools:"Pas de bobine libre",linkSuccess:"Lien réussi",linkFailed:"Échec lien",spoolId:"ID Bobine",fillSourceLabel:"(Spoolman)",weight:"Poids",remaining:"Restant",disableWeightSync:"Désactiver Sync poids estimé AMS",disableWeightSyncDesc:"Ne pas utiliser les estimations AMS. Utile si vous préférez le suivi Spoolman.",reportPartialUsage:"Rapporter consommation partielle pour échecs",reportPartialUsageDesc:"Si l'impression échoue, rapporte le filament consommé selon les couches."},inventory:{title:"Inventaire de Bobines",addSpool:"Ajouter Bobine",editSpool:"Modifier Bobine",material:"Matériau",selectMaterial:"Choisir matériau...",subtype:"Sous-type",brand:"Marque",searchBrand:"Chercher marque...",useCustomBrand:'Utiliser "{{brand}}"',useCustomMaterial:"Utiliser un matériau personnalisé : {{material}}",colorName:"Nom de couleur",colorNamePlaceholder:"Jade White, Fire Red...",color:"Couleur",hexColor:"Code Hex",pickColor:"Choisir couleur perso",labelWeight:"Poids net",coreWeight:"Poids bobine vide",searchSpoolWeight:"Chercher poids bobine...",weightUsed:"Consommé",currentWeight:"Poids restant",measuredWeight:"Poids mesuré",costPerKg:"Coût par kg",measuredWeightError:"Le poids mesuré doit être entre {{min}}g et {{max}}g.",slicerFilament:"Filament Slicer",slicerFilamentName:"Nom du Preset Slicer",slicerPreset:"Preset Slicer",searchPresets:"Chercher presets...",selectedPreset:"Sélectionné",noPresetsFound:"Aucun preset trouvé",tempOverrides:"Exceptions Température",note:"Note",notePlaceholder:"Notes additionnelles sur cette bobine...",archive:"Archiver",restore:"Restaurer",noSpools:"Aucune bobine. Ajoutez votre première bobine pour commencer.",noManualSpools:"Aucune bobine manuelle disponible. Ajoutez-en une d'abord.",kProfiles:"K-Profiles",addKProfile:"Ajouter K-Profile",assignSpool:"Assigner Bobine",unassignSpool:"Désassigner",assignSuccess:"Bobine assignée et slot AMS configuré",assignFailed:"Échec assignation",selectSpool:"Choisir une bobine pour ce slot",assigned:"Assigné",assigning:"Assignation...",searchSpools:"Chercher bobines...",allMaterials:"Tous Matériaux",filterByBrand:"Filtrer par marque...",showArchived:"Afficher archivées",quickAdd:"Ajout rapide (Stock)",quantity:"Quantité",stock:"Stock",configured:"Configuré",spoolsCreated:"{{count}} bobines créées",spoolCreated:"Bobine créée",spoolUpdated:"Bobine mise à jour",spoolDeleted:"Bobine supprimée",spoolArchived:"Bobine archivée",spoolRestored:"Bobine restaurée",deleteConfirm:"Supprimer définitivement cette bobine ?",archiveConfirm:"Voulez-vous vraiment archiver cette bobine ?",advancedSettings:"Paramètres Avancés",filamentInfoTab:"Infos Filament",paProfileTab:"Profil PA",filamentInfo:"Filament",additional:"Additionnel",loadingPresets:"Chargement des presets cloud...",cloudConnected:"Cloud connecté",cloudNotConnected:"Cloud déconnecté (valeurs par défaut)",recentColors:"Récentes",searchColors:"Chercher couleurs...",searchResults:"Résultats",allColors:"Toutes",commonColors:"Communes",showLess:"Moins",showAll:"Toutes",noColorsFound:"Aucune couleur correspondante",noResults:"Aucun résultat",selectMaterialFirst:"Veuillez choisir un matériau dans l'onglet Infos Filament.",noPrintersConfigured:"Ajoutez une imprimante pour utiliser les profils PA.",matchingFilter:"Correspondant",anyBrand:"Toute marque",anyVariant:"Toute variante",autoSelect:"Auto-sélection",matches:"correspondances",match:"correspondance",noMatches:"Aucune correspondance",connected:"Connecté",offline:"Hors ligne",printerOffline:"Imprimante hors ligne. Connectez-vous pour voir les profils.",noKProfilesMatch:"Aucun profil K ne correspond au filament.",leftNozzle:"Buse Gauche",rightNozzle:"Buse Droite",profilesSelected:"profil(s) de calibration sélectionné(s)",totalInventory:"Total Inventaire",totalConsumed:"Total Consommé",byMaterial:"Par Matériau",inPrinter:"Dans Imprimante",lowStock:"Stock Bas",sinceTracking:"Depuis le début du suivi",loadedInAms:"Chargé dans AMS/Ext",remaining:"Restant",lowStockThreshold:"<20% restant",search:"Chercher bobines...",showing:"Affichage",to:"à",of:"sur",show:"Voir",spools:"bobines",spool:"bobine",page:"Page",noSpoolsMatch:"Aucun résultat trouvé",noSpoolsMatchDesc:"Ajustez votre recherche ou vos filtres.",active:"Actif",archived:"Archivé",all:"Tous",used:"Occasion",new:"Neuf",clearFilters:"Effacer filtres",table:"Tableau",cards:"Cartes",net:"Net",columns:"Colonnes",configureColumns:"Configurer Colonnes",configureColumnsDesc:"Glissez pour ordonner ou utilisez les flèches. Cliquez sur l'œil pour masquer.",visible:"visible",reset:"Reset",cancel:"Annuler",applyChanges:"Appliquer",moveUp:"Monter",moveDown:"Descendre",hideColumn:"Masquer",showColumn:"Afficher",linkToSpool:"Lier à une Bobine",tagLinked:"Tag lié à la bobine",tagLinkFailed:"Échec lien tag",tagAlreadyLinked:"Tag déjà lié à une autre bobine",unknownTag:"Tag RFID inconnu détecté",usageHistory:"Historique de Consommation",noUsageHistory:"Aucune consommation enregistrée",printName:"Nom Impression",weightConsumed:"Poids consommé",clearHistory:"Effacer",historyCleared:"Historique effacé",fillSourceLabel:"(Inv)"},timelapse:{title:"Timelapse",create:"Créer Timelapse",download:"Télécharger",delete:"Supprimer",preview:"Aperçu",frameRate:"Images/sec",quality:"Qualité",processing:"Traitement...",noTimelapses:"Aucun timelapse"},ams:{title:"AMS",slot:"Slot",empty:"Vide",emptySlot:"Slot vide",unknown:"Inconnu",humidity:"Humidité",temperature:"Température",filamentType:"Type filament",filamentColor:"Couleur",remaining:"Restant",history:"Historique AMS",noHistory:"Aucun historique",configureSlot:"Configurer Slot",externalSpool:"Bobine externe",profile:"Profil",kFactor:"Facteur K",fill:"Remplir",configure:"Configurer",used:"utilisé",remainingUnit:"restant"},printModal:{title:"Lancer l'impression",selectPrinter:"Choisir l'imprimante",selectPlate:"Choisir le plateau",filamentMapping:"Mapping Filament",totalCost:"Coût total :",printSettings:"Réglages d'impression",bedLeveling:"Nivellement plateau",flowCalibration:"Calibration débit",vibrationCalibration:"Vibration (Input Shaper)",layerInspection:"Inspection 1ère couche",timelapse:"Timelapse",startPrint:"Démarrer",addToQueue:"Ajouter à la file",cancel:"Annuler",noPrintersAvailable:"Aucune imprimante disponible",printerBusy:"L'imprimante est occupée",printerOffline:"L'imprimante est hors ligne",sameTypeDifferentColor:"Même type, couleur différente",filamentTypeNotLoaded:"Type de filament non chargé",openCalendar:"Ouvrir calendrier",leftNozzle:"G",rightNozzle:"D",leftNozzleTooltip:"Buse gauche",rightNozzleTooltip:"Buse droite",filamentOverride:"Remplacement de filament",filamentOverrideHint:"Remplacez optionnellement les filaments pour l'affectation par modèle. Le planificateur utilisera vos filaments sélectionnés au lieu des valeurs 3MF d'origine.",originalFilament:"Original",overrideWith:"Remplacer par",resetToOriginal:"Revenir à l'original"},backup:{title:"Sauvegarde & Restauration",createBackup:"Créer Sauvegarde",restoreBackup:"Restaurer Sauvegarde",restoreDescription:"Remplace les données par un fichier de sauvegarde",downloadBackup:"Télécharger Sauvegarde",uploadBackup:"Téléverser Sauvegarde",lastBackup:"Dernière sauvegarde",autoBackup:"Sauvegarde auto",backupNow:"Sauvegarder maintenant",restoreWarning:"Attention : Écrase TOUTES les données actuelles.",includeArchives:"Inclure Archives",includeSettings:"Inclure Paramètres",includeProfiles:"Inclure Profils",backupSuccess:"Sauvegarde réussie",restoreSuccess:"Restauration réussie",backupFailed:"Échec sauvegarde",restoreFailed:"Échec restauration",restoreNote:"L'imprimante virtuelle sera arrêtée pendant la restauration"},tags:{title:"Tags",addTag:"Ajouter Tag",editTag:"Modifier Tag",deleteTag:"Supprimer Tag",tagName:"Nom du Tag",tagColor:"Couleur du Tag",noTags:"Aucun tag",deleteConfirm:"Supprimer ce tag ?",manageTags:"Gérer les Tags"},uploadModal:{title:"Téléverser des fichiers 3MF",dragDrop:"Glissez les fichiers .3mf ici",or:"ou",browseFiles:"Parcourir",extractionInfo:"Le modèle d'imprimante est extrait des métadonnées 3MF.",uploaded:"téléversé",failed:"échoué",uploading:"En cours...",upload:"Téléverser",uploadFailed:"Échec du téléversement"},editArchive:{title:"Modifier l'archive",name:"Nom",namePlaceholder:"Nom de l'impression",printer:"Imprimante",noPrinter:"Aucune imprimante",project:"Projet",noProject:"Aucun projet",itemsPrinted:"Nombre de pièces",itemsPrintedHelp:"Nombre d'objets produits",notes:"Notes",notesPlaceholder:"Notes sur l'impression...",externalLink:"Lien externe",externalLinkPlaceholder:"https://...",externalLinkHelp:"Lien vers Printables, Thingiverse, etc.",tags:"Tags",tagsPlaceholder:"Ajouter des tags...",addMoreTags:"Plus de tags...",matchingTags:'Correspondant à "{{query}}"',existingTags:"Tags existants",clickToAdd:"(cliquer pour ajouter)",status:"Statut",failureReason:"Raison de l'échec",selectReason:"Choisir raison...",photos:"Photos du résultat",photosHelp:"Cliquez sur + pour ajouter des photos",printResult:"Résultat d'impression",saving:"Enregistrement...",failureReasons:{adhesionFailure:"Défaut d'adhésion",spaghettiDetached:"Spaghetti / Détaché",layerShift:"Décalage de couche",cloggedNozzle:"Buse bouchée",filamentRunout:"Filament fini",warping:"Warping (Déformation)",stringing:"Stringing (Cheveux d'ange)",underExtrusion:"Sous-extrusion",powerFailure:"Coupure courant",userCancelled:"Annulé par l'utilisateur",other:"Autre"},statuses:{completed:"Réussie",failed:"Échouée",aborted:"Annulée",printing:"Impression"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Aucune imprimante configurée",addPrinterInSettings:"Ajoutez une imprimante pour gérer les K-profiles",noActivePrinters:"Aucune imprimante active",enablePrinterConnection:"Activez la connexion pour voir les K-profiles",loadingProfiles:"Chargement des K-Profiles...",printerOffline:"Imprimante hors ligne",printerOfflineDesc:"L'imprimante doit être allumée.",noMatchingProfiles:"Aucun profil correspondant",noMatchingProfilesDesc:"Ajustez votre recherche",noKProfiles:"Aucun K-Profile",noKProfilesDesc:"Aucun profil trouvé pour une buse de {{diameter}}mm",createFirstProfile:"Créer le premier profil",printer:"Imprimante",nozzle:"Buse",refresh:"Rafraîchir",addProfile:"Ajouter Profil",export:"Exporter",import:"Importer",select:"Choisir",selectAll:"Tout sélectionner",delete:"Supprimer",searchPlaceholder:"Nom ou filament...",allExtruders:"Tous les extrudeurs",leftOnly:"Gauche uniquement",rightOnly:"Droite uniquement",allFlow:"Tout débit",hfOnly:"HF uniquement",sOnly:"S uniquement",sortName:"Tri : Nom",sortKValue:"Tri : Valeur K",sortFilament:"Tri : Filament",leftExtruder:"Extrudeur gauche",rightExtruder:"Extrudeur droit",modal:{addTitle:"Ajouter K-Profile",editTitle:"Modifier K-Profile",profileName:"Nom du profil",profileNamePlaceholder:"ex: Mon profil PLA",kValue:"Valeur K",kValuePlaceholder:"0.020",kValueHelp:"Plage type : 0.01-0.06 (PLA), 0.02-0.10 (PETG)",filament:"Filament",selectFilament:"Choisir filament...",noFilamentsHelp:"Créez d'abord un profil dans Bambu Studio.",flowType:"Type de débit",highFlow:"Haut Débit (HF)",standard:"Standard",nozzleSize:"Taille buse",extruder:"Extrudeur",extruders:"Extrudeurs",left:"Gauche",right:"Droite",notes:"Notes (locales)",notesPlaceholder:"Notes sur ce profil...",notesHelp:"Enregistré dans Bambuddy, pas sur l'imprimante",syncing:"Sync avec l'imprimante...",savingExtruder:"Sauvegarde extrudeur {{current}}/{{total}}...",pleaseWait:"Patientez..."},deleteConfirm:{title:"Supprimer profil",cannotUndo:"Action irréversible",message:`Supprimer "{{name}}" de l'imprimante ?`},bulkDelete:{title:"Supprimer les profils",cannotUndo:"Action irréversible",message:"Supprimer les {{count}} profils de l'imprimante ?"},toast:{profileSaved:"Profil K enregistré",profilesSaved:"Profil K enregistré sur {{count}} extrudeur(s)",selectAtLeastOneExtruder:"Sélectionnez un extrudeur",profileDeleted:"Profil K supprimé",profilesDeleted:"{{count}} profils supprimés",exportedProfiles:"{{count}} profils exportés",importedProfiles:"{{count}} sur {{total}} profils importés",noProfilesToExport:"Rien à exporter",invalidFileFormat:"Format invalide",failedToParseImport:"Échec analyse fichier",failedToSaveBatch:"Échec enregistrement groupé",noteSaved:"Note enregistrée",failedToSaveNote:"Échec note"},permission:{noRead:"Pas d'autorisation lecture",noCreate:"Pas d'autorisation création",noUpdate:"Pas d'autorisation mise à jour",noDelete:"Pas d'autorisation suppression",noExport:"Pas d'autorisation export",noImport:"Pas d'autorisation import"}},virtualPrinter:{title:"Imprimante Virtuelle",running:"En cours",stopped:"Arrêtée",description:{default:"Active une imprimante qui apparaît dans Bambu Studio. Les fichiers envoyés sont archivés sans impression.",proxy:"Active un proxy qui relaie le trafic vers une imprimante réelle, permettant l'impression à distance."},enable:{title:"Activer l'imprimante virtuelle",visibleInSlicer:'Visible comme "Bambuddy" dans le Slicer',proxyingTo:"Proxy vers {{name}}",notActive:"Inactive"},model:{title:"Modèle d'imprimante",description:"Choisissez le modèle à émuler.",restartWarning:"Changer le modèle redémarrera le service"},accessCode:{title:"Code d'accès",isSet:"Code défini",notSet:"Code requis pour activer",placeholder:"Code 8 char",placeholderChange:"Entrez nouveau code",hint:"Exactement 8 caractères. Sert à l'auth du Slicer.",charCount:"({{count}}/8)"},targetPrinter:{title:"Imprimante cible",configured:"Cible configurée",notConfigured:"Imprimante requise pour mode Proxy",placeholder:"Choisir imprimante...",hint:"L'imprimante doit être en mode LAN.",noPrinters:"Ajoutez une imprimante réelle d'abord."},remoteInterface:{title:"Exception Interface Réseau",configured:"Override actif",optional:"Optionnel - si IP auto est fausse (VPN, Docker, multi-NIC).",placeholder:"Auto (défaut)...",hint:"Force l'IP annoncée via SSDP."},bindIp:{title:"Interface réseau",placeholder:"Sélectionner interface...",hint:"Interface réseau sur laquelle cette imprimante virtuelle écoute. Doit être unique par imprimante."},proxy:{accessCodeHint:"En mode proxy, utilisez le code d'accès de l'imprimante cible dans le slicer. La connexion est transmise de manière transparente à l'imprimante réelle."},mode:{title:"Mode",archive:"Archiver",archiveDesc:"Archive immédiatement",review:"Revue",reviewDesc:"Attendre revue avant archive",queue:"File",queueDesc:"Archiver et ajouter à la file",proxy:"Proxy",proxyDesc:"Relais vers imprimante réelle"},setupRequired:{title:"Configuration requise",description:"Nécessite des réglages système (ports, pare-feu).",readGuide:"Lire le guide de configuration"},howItWorks:{title:"Fonctionnement",step1:"Sur le même LAN, les imprimantes virtuelles apparaissent automatiquement dans votre slicer (Bambu Studio / OrcaSlicer). Depuis d'autres réseaux, ajoutez-les manuellement par adresse IP et code d'accès.",step2:`En mode Archive, Revue et File d'attente, utilisez le bouton "Envoyer" dans votre slicer pour envoyer des fichiers 3MF à Bambuddy. Le slicer affichera "Impression réussie" — le fichier est stocké, pas imprimé.`,step3:"En mode Proxy, l'imprimante virtuelle relaie tout le trafic vers une vraie imprimante — les impressions démarrent immédiatement comme en connexion directe."},status:{title:"Détails du statut",printerName:"Nom",model:"Modèle",serialNumber:"Série",mode:"Mode",pendingFiles:"Fichiers en attente",targetPrinter:"Cible",ftpPort:"Port FTP",mqttPort:"Port MQTT",ftpConnections:"Connexions FTP",mqttConnections:"Connexions MQTT"},toast:{updated:"Réglages virtuels mis à jour",failedToUpdate:"Échec mise à jour",accessCodeRequired:"Code d'accès requis",targetPrinterRequired:"Imprimante cible requise",accessCodeEmpty:"Le code ne peut pas être vide",accessCodeLength:"Le code doit faire 8 caractères"}},modelViewer:{openInSlicer:"Ouvrir dans le Slicer",tabs:{model:"Modèle 3D",gcode:"Aperçu G-code"},notAvailable:"indisponible",notSliced:"pas découpé",plates:"Plateaux",allPlates:"Tous les plateaux",plateNumber:"Plateau {{number}}",plateCount:"{{count}} plateau",plateCount_other:"{{count}} plateaux",objectCount:"{{count}} objet",objectCount_other:"{{count}} objets",filamentCount:"{{count}} filament",filamentCount_other:"{{count}} filaments",eta:"Fin {{minutes}} min",noPreview:"Aucun aperçu pour ce fichier",pagination:{pageOf:"Page {{current}} sur {{total}}",prev:"Préc",next:"Suiv"},errors:{failedToLoad:"Échec chargement fichier",noMeshes:"Aucun maillage trouvé dans le 3MF",unsupportedFormat:"Format non supporté"}},maintenanceDescriptions:{lubricateCarbonRods:"Appliquer du lubrifiant sur les tiges carbone pour un mouvement fluide",lubricateRails:"Appliquer du lubrifiant sur les rails linéaires",cleanNozzle:"Nettoyer buse et hotend anti-bouchage",checkBelts:"Tension des courroies pour la précision",cleanBuildPlate:"Nettoyage plateau pour l'adhésion",checkExtruder:"Usure des engrenages de l'extrudeur",checkCooling:"Bon fonctionnement des ventilateurs",generalInspection:"Inspection générale de la machine",cleanCarbonRods:"Nettoyer les tiges carbone (friction)",cleanLinearRails:"Essuyer les rails linéaires (poussière/débris)",checkPtfeTube:"Usure ou dommage du tube PTFE",replaceHepaFilter:"Filtre HEPA pour la qualité de l'air",replaceCarbonFilter:"Filtre charbon actif (odeurs)",lubricateLeftNozzleRail:"Lubrifier le rail de buse gauche (Série H2)"},smartPlugs:{offline:"Hors ligne",admin:"Admin",openPlugAdminPage:"Page admin de la prise",deleteSmartPlug:"Supprimer la prise",turnOnSmartPlug:"Allumer la prise",turnOffSmartPlug:"Éteindre la prise",turnOn:"Allumer",turnOff:"Éteindre",addSmartPlug:{scanningNetwork:"Scan réseau...",chooseEntity:"Choisir une entité...",connectionFailed:"Échec connexion",searchEntities:"Chercher entités...",searchPowerSensors:"Capteurs puissance...",searchEnergySensors:"Capteurs énergie...",placeholders:{plugName:"Prise Salon",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Identique au topic puissance, ou différent"}}},richTextEditor:{bold:"Gras",italic:"Italique",underline:"Souligné",bulletList:"Liste à puces",numberedList:"Liste numérotée",alignLeft:"Aligner à gauche",alignCenter:"Centrer",alignRight:"Aligner à droite",addLink:"Ajouter lien",removeLink:"Retirer lien"},externalLinks:{noLinksConfigured:"Aucun lien externe configuré",deleteLink:"Supprimer lien",removeCustomIcon:"Retirer icône personnalisée",openInNewTab:"Ouvrir dans un nouvel onglet",placeholders:{linkName:"Mon Lien"}},keyboardShortcuts:{title:"Raccourcis Clavier",navigation:"Navigation",archivesSection:"Archives",kProfilesSection:"K-Profiles",generalSection:"Général",shortcuts:{goToPrinters:"Aller aux Imprimantes",goToArchives:"Aller aux Archives",goToQueue:"Aller à la File",goToStats:"Aller aux Stats",goToProfiles:"Aller aux Profils Cloud",goToSettings:"Aller aux Paramètres",focusSearch:"Focus recherche",openUploadModal:"Ouvrir téléversement",clearSelection:"Tout déselectionner",contextMenu:"Menu contextuel (cartes)",refreshProfiles:"Rafraîchir profils",newProfile:"Nouveau profil",exitSelectionMode:"Quitter mode sélection",showHelp:"Afficher cette aide"},footer:"Échap ou clic extérieur pour fermer"},notificationLog:{title:"Journal de Notification",events:{printStarted:"Début impression",printComplete:"Fin impression",printFailed:"Échec impression",printStopped:"Arrêt impression",progress:"Progression",printerOffline:"Hors ligne",printerError:"Erreur",lowFilament:"Filament bas",maintenanceDue:"Maintenance",test:"Test"},timeAgo:{justNow:"À l'instant",minutesAgo:"Il y a {{minutes}}m",hoursAgo:"Il y a {{hours}}h"}},restoreBackup:{title:"Restaurer Sauvegarde",restoring:"Restauration...",restoreComplete:"Restauration terminée",restoreFailed:"Échec restauration",importSettings:"Importer les réglages d'un fichier",pleaseWait:"Patientez pendant la restauration",clickToSelect:"Fichier .json ou .zip",howDuplicateHandling:"Gestion des doublons :",categories:{printers:"Imprimantes",smartPlugs:"Prises",notificationProviders:"Fournisseurs",filaments:"Filaments",archives:"Archives",pendingUploads:"Téléversements en attente",settingsTemplates:"Réglages & Modèles"},matchingInfo:{printers:"par numéro de série",smartPlugs:"par adresse IP",notificationProviders:"par nom",filaments:"par nom+type+marque",archives:"par empreinte numérique (hash)",pendingUploads:"par nom de fichier",settingsTemplates:"toujours écrasés"},replaceExisting:"Remplacer existant",keepExisting:"Garder existant",replaceDescription:"Écrase les doublons avec la sauvegarde",keepDescription:"Ne restaure que les éléments absents",caution:"Attention :",cautionText:"L'écrasement remplacera vos réglages. Les codes d'accès imprimantes sont exclus par sécurité.",itemsRestored:"Éléments restaurés",itemsSkipped:"Éléments ignorés",restored:"Restaurés",skipped:"Ignorés (déjà présents)",filesLabel:"Fichiers (3MF, vignettes, etc.)",newApiKeysGenerated:"Nouvelles clés API générées",newApiKeysWarning:"Copiées maintenant, elles ne seront plus visibles !",processingBackup:"Traitement du fichier...",noDataFound:"Aucune donnée trouvée dans le fichier.",failedToRestore:"Échec restaure. Vérifiez le format."},backupExport:{title:"Exporter Sauvegarde",selectData:"Données à inclure",selectAll:"Tout sélectionner",selectNone:"Ne rien sélectionner",categoryDescriptions:{settings:"Langue, thèmes, préférences",notifications:"ntfy, Pushover, Discord, etc.",templates:"Modèles de messages personnalisés",smartPlugs:"Configuration des prises Tasmota",externalLinks:"Liens externes de la barre latérale",printers:"Infos imprimantes (codes d'accès exclus par défaut)",plateDetection:"Images références des plateaux vides",filaments:"Types et coûts filaments",maintenance:"Plannings de maintenance personnalisés",archives:"Données impressions + fichiers (3MF, vignettes, etc.)",projects:"Projets, BOM, pièces jointes",pendingUploads:"En attente revue virtuelle",apiKeys:"Clés Webhook (nouvelles clés générées à l'import)"},requiresPrinters:"Nécessite sélection des imprimantes",zipFileWarning:"Fichier ZIP créé.",zipFileDescription:"Contient tous les médias. Peut être volumineux.",includeAccessCodes:"Inclure Codes d'accès",includeAccessCodesDescription:"Pour migrer vers une autre machine",includeAccessCodesWarning:"Codes en texte clair. Sécurisez ce fichier !",categoriesSelected:"{{selectedCount}} catégories choisies"},pendingUploads:{placeholders:{notes:"Notes sur l'impression..."},discardUpload:"Rejeter",archiveAllUploads:"Tout archiver",discardAllUploads:"Tout rejeter",archive:"Archiver",timeAgo:{justNow:"À l'instant",minutesAgo:"Il y a {{minutes}}m",hoursAgo:"Il y a {{hours}}h",daysAgo:"Il y a {{days}}j"}},apiBrowser:{placeholders:{requestBody:"Corps JSON...",searchEndpoints:"Chercher endpoints..."}},configureAmsSlot:{title:"Configurer le slot AMS",slotConfigured:"Slot configuré !",configuringSlot:"Configuration du slot :",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Chercher presets...",colorPlaceholder:"Nom couleur ou hex (ex: brown, FF8800)",clearCustomColor:"Effacer couleur perso",noCloudPresets:"Profils Cloud absents. Connectez-vous.",noPresetsAvailable:"Aucun preset disponible. Connectez-vous à Bambu Cloud ou importez des profils locaux.",noMatchingPresets:"Aucun profil trouvé.",custom:"Perso",builtin:"Inclus",settingsSentToPrinter:"Réglages envoyés",filamentProfile:"Profil Filament",kProfileLabel:"Profil K (Pressure Advance)",filteringFor:"Filtrage pour : {{material}}",noKProfile:"Pas de profil K (utiliser défaut 0.020)",noMatchingKProfiles:"Aucun profil K trouvé. K=0.020 par défaut sera utilisé.",selectFilamentFirst:"Sélectionnez d'abord un profil filament",kFromCalibration:"K={{value}} de la calibration imprimante",customColorLabel:"Couleur personnalisée (optionnel)",presetColors:"Couleurs {{name}} :",showLessColors:"Moins de couleurs",showMoreColors:"Plus de couleurs",clear:"Effacer",hexLabel:"Hex : #{{hex}}",resetting:"Réinitialisation...",resetSlot:"Réinitialiser le slot",cancel:"Annuler",configuring:"Configuration...",configureSlot:"Configurer le slot"},githubBackup:{title:"Sauvegarde GitHub",history:"Historique",downloadBackup:"Télécharger",restoreBackup:"Restaurer",noBackupsYet:"Aucune sauvegarde"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Chercher tags...",renameTag:"Renommer tag",deleteTag:"Supprimer tag"},notificationTemplates:{placeholders:{title:"Titre notification...",body:"Message notification..."}},batchTag:{placeholders:{newTag:"Nouveau tag..."}},photoGallery:{deletePhoto:"Supprimer photo"},filamentHoverCard:{copySpoolUuid:"Copier UUID bobine"},kProfilesView:{hasNote:"A une note",copyProfile:"Copier profil"},layout:{openMenu:"Ouvrir menu",noPermissionSystemInfo:"Pas d'autorisation système"},dashboard:{dragToReorder:"Glisser pour réorganiser",hideWidget:"Masquer widget"},notificationProviderCard:{deleteNotificationProvider:"Supprimer fournisseur"},fileManagerModal:{closeFileManager:"Fermer gestionnaire",sortFiles:"Trier fichiers",goToParentFolder:"Dossier parent",threeView:"Vue 3D"},embeddedCameraViewer:{refreshStream:"Actualiser flux",close:"Fermer",zoomOut:"Zoom -",resetZoom:"Reset zoom",zoomIn:"Zoom +",dragToResize:"Glisser pour dimension"},timelapseViewer:{skipBack5s:"-5s",skipForward5s:"+5s"},notificationProviders:{descriptions:{email:"Notifications par email SMTP",telegram:"Via bot Telegram",discord:"Via webhook Discord",ntfy:"Push auto-hébergé (ntfy)",pushover:"Push fiable (Pushover)",callmebot:"WhatsApp gratuit via CallMeBot",webhook:"Requête HTTP POST personnalisée"}},logViewer:{searchPlaceholder:"Message ou nom...",noLogEntries:"Aucune entrée journal"},switchbarPopover:{noSwitchesInSwitchbar:"Aucun interrupteur"},projectPageModal:{placeholders:{title:"Titre",designer:"Designer",license:"Licence",description:"Description...",profileTitle:"Titre du profil",profileDescription:"Description du profil..."}},spoolmanSettings:{},time:{unknown:"-",waiting:"En attente",justNow:"À l'instant",now:"Maintenant",minsAgo:"il y a {{count}}m",inMins:"dans {{count}}m",hoursAgo:"il y a {{count}}h",inHours:"dans {{count}}h",daysAgo:"il y a {{count}}j",inDays:"dans {{count}}j"},spoolbuddy:{nav:{dashboard:"Tableau de bord",ams:"AMS",inventory:"Inventaire",printers:"Imprimantes",settings:"Paramètres"},status:{nfcReady:"Prêt",nfcOff:"Désactivé",offline:"Appareil hors ligne"},dashboard:{idleMessage:"Placez la bobine sur la balance et scannez le tag NFC"},weight:{noReading:"Aucune mesure",stable:"Stable",measuring:"Mesure en cours",tare:"Tare",calibrate:"Calibrer",tareQueued:"Commande de tare envoyée"},spool:{remaining:"Restant"},tag:{unknownTitle:"Tag inconnu",linkExisting:"Lier à une bobine existante",createNew:"Créer une nouvelle bobine"},actions:{assignAms:"Assigner AMS",updateWeight:"Mettre à jour le poids",editSpool:"Modifier la bobine",viewHistory:"Voir l'historique",weightUpdated:"Poids de la bobine mis à jour"},ams:{noData:"Aucune donnée AMS disponible"},inventory:{search:"Rechercher des bobines...",empty:"Aucune bobine trouvée"},printers:{noPrinters:"Aucune imprimante configurée"},settings:{scaleCalibration:"Calibration de la balance",currentWeight:"Poids actuel",tareOffset:"Offset de tare",knownWeight:"Poids connu",calibrated:"Calibration mise à jour",tareQueued:"Commande de tare en file d'attente",nfcReader:"Lecteur NFC",nfcConnected:"Connecté",nfcDisconnected:"Déconnecté",deviceInfo:"Info appareil",deviceId:"ID appareil",uptime:"Temps de fonctionnement",firmware:"Firmware"}}},dce={nav:{printers:"プリンター",archives:"アーカイブ",queue:"キュー",stats:"統計",profiles:"プロファイル",maintenance:"メンテナンス",projects:"プロジェクト",inventory:"フィラメント",files:"ファイル管理",settings:"設定",system:"システム",collapseSidebar:"サイドバーを閉じる",expandSidebar:"サイドバーを開く",update:"アップデート",updateAvailable:"アップデートあり: v{{version}}",viewOnGithub:"GitHubで表示",keyboardShortcuts:"キーボードショートカット (?)",switchToLight:"ライトモードに切替",switchToDark:"ダークモードに切替",smartSwitches:"スマートスイッチ",logout:"ログアウト",updateAvailableBanner:"バージョン {{version}} が利用可能です!",viewUpdate:"アップデートを表示"},common:{save:"保存",saving:"保存中...",cancel:"キャンセル",delete:"削除",edit:"編集",add:"追加",close:"閉じる",confirm:"確認",loading:"読み込み中...",error:"エラー",success:"成功",warning:"警告",enabled:"有効",disabled:"無効",yes:"はい",no:"いいえ",on:"オン",off:"オフ",all:"すべて",none:"なし",search:"検索",filter:"フィルター",sort:"並べ替え",refresh:"更新",download:"ダウンロード",upload:"アップロード",actions:"操作",status:"ステータス",name:"名前",description:"説明",date:"日付",time:"時間",hours:"時間",minutes:"分",seconds:"秒",disable:"無効にする",permissions:"権限",noPrinters:"プリンターが登録されていません",noData:"データがありません",required:"必須",optional:"オプション",dismiss:"閉じる",apply:"適用",clear:"クリア",noChange:"— 変更なし —",unassigned:"未割当",unknown:"不明",unknownError:"不明なエラー",today:"今日",tomorrow:"明日",asap:"即時",now:"今すぐ",collapse:"折りたたむ",expand:"展開",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",addedBy:"{{username}}が追加",more:"もっと見る",printer:"プリンター",type:"種類",print:"印刷",rename:"名前変更",move:"移動",create:"作成",days:"日",enable:"有効化",linkNotFound:"リンクが見つかりません",reset:"リセット",export:"エクスポート",import:"インポート",selectAll:"すべて選択",deselectAll:"すべて選択解除",unchanged:"変更なし",overdue:"期限超過",prints:"プリント",ascending:"昇順",descending:"降順",remove:"削除",duplicate:"複製",left:"左",right:"右",done:"完了",saveChanges:"変更を保存",turnOn:"オンにする",turnOff:"オフにする",deletePhoto:"写真を削除",deletePhotoConfirm:"この写真を削除しますか?元に戻せません。",project:"プロジェクト",archive:"アーカイブ",show:"表示",hide:"非表示",back:"戻る",retry:"リトライ",model:"モデル",ok:"OK"},printers:{title:"プリンター",addPrinter:"プリンターを追加",editPrinter:"プリンターを編集",deletePrinter:"プリンターを削除",printerName:"プリンター名",serialNumber:"シリアル番号",ipAddress:"IPアドレス / ホスト名",accessCode:"アクセスコード",model:"モデル",nozzleCount:"ノズル数",autoArchive:"自動アーカイブ",status:{available:"利用可能",idle:"待機中",printing:"印刷中",paused:"一時停止",offline:"オフライン",finished:"完了",unknown:"不明",error:"エラー"},temperatures:{nozzle:"ノズル",bed:"ベッド",chamber:"チャンバー"},progress:"{{percent}}% 完了",timeRemaining:"残り {{time}}",maintenanceOk:"メンテナンス正常",maintenanceWarning:"{{count}}件の警告",maintenanceWarning_plural:"{{count}}件の警告",maintenanceDue:"{{count}}件のメンテナンス期限",sort:{name:"名前",status:"ステータス",model:"モデル",location:"ロケーション",ascending:"昇順で並べ替え",descending:"降順で並べ替え"},cardSize:{small:"小",medium:"中",large:"大",extraLarge:"特大"},hideOffline:"オフラインを非表示",nextAvailable:"次に完了",powerOn:"電源オン",noPrintersConfigured:"プリンターが設定されていません",readyToPrint:"印刷可能",external:"外部",extL:"Ext-L",extR:"Ext-R",deleteArchives:"印刷アーカイブを削除",willBeSkipped:"スキップされます",name:"名前",wifiSignal:{veryWeak:"非常に弱い",weak:"弱い",fair:"注意",good:"良好",excellent:"非常に良い"},maintenanceUpToDate:"すべてのメンテナンスが最新です",chamberLightOn:"チャンバーライトをオンにしました",chamberLightOff:"チャンバーライトをオフにしました",browseFiles:"プリンターのファイルを参照",hmsErrors:"クリックしてHMSエラーを表示",resume:"再開",pause:"一時停止",stop:"停止",reconnect:"再接続",mqttDebug:"MQTTデバッグ",activeNozzle:"アクティブ: {{side}}ノズル",nozzleRack:"ノズルラック",nozzleDocked:"ドッキング中",nozzleMounted:"マウント中",nozzleActive:"アクティブ",nozzleIdle:"アイドル",nozzleDiameter:"直径",nozzleType:"タイプ",nozzleStatus:"ステータス",nozzleFilament:"フィラメント",nozzleWear:"摩耗",nozzleMaxTemp:"最高温度",nozzleSerial:"シリアル",nozzleHardenedSteel:"焼入れ鋼",nozzleStainlessSteel:"ステンレス鋼",nozzleTungstenCarbide:"タングステンカーバイド",nozzleFlow:"フロー",nozzleHighFlow:"ハイフロー",nozzleStandardFlow:"スタンダード",toast:{printStopped:"印刷を停止しました",printPaused:"印刷を一時停止しました",printResumed:"印刷を再開しました",failedToSkipObjects:"オブジェクトのスキップに失敗しました",rfidRereadInitiated:"RFID再読み取りを開始しました",printerDeleted:"プリンターを削除しました",printerAdded:"プリンターを追加しました",printerUpdated:"プリンターを更新しました",failedToDelete:"プリンターの削除に失敗しました",failedToAdd:"プリンターの追加に失敗しました",failedToUpdate:"プリンターの更新に失敗しました",commandSent:"コマンドを送信しました",failedToSendCommand:"コマンドの送信に失敗しました",turnedOn:"{{name}} の電源をオンにしました",failedToPowerOn:"{{name}} の電源オンに失敗しました",scriptTriggered:"スクリプトを実行しました",referenceDeleted:"リファレンスを削除しました",detectionAreaSaved:"検出エリアを保存しました",failedToDiscover:"プリンターの検出に失敗しました",cloudLoginRequired:"クラウドログインが必要です",failedToRunScript:"スクリプトの実行に失敗しました",failedToStopPrint:"印刷の停止に失敗しました",failedToPausePrint:"印刷の一時停止に失敗しました",failedToResumePrint:"印刷の再開に失敗しました",failedToControlChamberLight:"チャンバーライトの制御に失敗しました",failedToUpdateSetting:"設定の更新に失敗しました",failedToRereadRfid:"RFIDの再読み取りに失敗しました",failedToCheckPlate:"プレートの確認に失敗しました",failedToUpdateLabel:"ラベルの更新に失敗しました",failedToDeleteReference:"リファレンスの削除に失敗しました",failedToSaveDetectionArea:"検出エリアの保存に失敗しました",plateCheckEnabled:"プレートチェックを有効にしました",plateCheckDisabled:"プレートチェックを無効にしました",calibrationSaved:"キャリブレーションを保存しました!",calibrationFailed:"キャリブレーションに失敗しました"},connection:{connected:"接続中",offline:"オフライン"},queue:{inQueue:"キュー内",inQueue_plural:"{{count}}件がキュー内"},controls:"コントロール",permission:{noFiles:"このディレクトリにファイルがありません",noAdd:"プリンターを追加する権限がありません",noEdit:"プリンターを編集する権限がありません",noDelete:"プリンターを削除する権限がありません",noControl:"プリンターを制御する権限がありません",noAmsRfid:"AMS RFIDを再読み取りする権限がありません",noSmartPlugControl:"スマートプラグを制御する権限がありません"},modal:{selectModel:"モデルを選択...",locationGroup:"ロケーション / グループ",locationPlaceholder:"例: 工房、オフィス、地下室",modelOptional:"モデル(任意)",addTitle:"プリンターを追加",editTitle:"プリンターを編集",myPrinter:"マイプリンター",autoArchiveLabel:"完了した印刷を自動アーカイブ",fromPrinterSettings:"プリンターの設定から取得",saveChanges:"変更を保存"},skipObjects:{onlyWhilePrinting:"オブジェクトスキップ(印刷中のみ)",title:"オブジェクトスキップ",skipped:"スキップ済み",objectsSkipped:"オブジェクトをスキップしました",activeCount:"{{count}}個アクティブ",waitForLayer:"オブジェクトをスキップするにはレイヤー2以降をお待ちください(現在レイヤー{{layer}})",skip:"スキップ",tooltip:"オブジェクトスキップ",requiresMultiple:"オブジェクトスキップ(2個以上必要)",matchIdsInfo:"プリンター画面のIDと照合してください",printerShowsIds:"プリンター画面にビルドプレート上のオブジェクトIDが表示されます",skipSelected:"選択をスキップ",skipping:"スキップ中...",noObjectsSelected:"オブジェクトが選択されていません",selectObjectsToSkip:"現在の印刷からスキップするオブジェクトを選択してください",confirmTitle:"オブジェクトをスキップしますか?",confirmMessage:"「{{name}}」をスキップしますか?この操作は元に戻せません。"},confirm:{deleteTitle:"プリンターを削除",deleteMessage:"「{{name}}」を削除しますか?すべての接続設定が削除されます。",stopTitle:"印刷を停止",stopMessage:"「{{name}}」の現在の印刷を停止しますか?印刷ジョブがキャンセルされます。",stopButton:"印刷を停止",pauseTitle:"印刷を一時停止",pauseMessage:"「{{name}}」の現在の印刷を一時停止しますか?",pauseButton:"印刷を一時停止",resumeTitle:"印刷を再開",resumeMessage:"「{{name}}」の印刷を再開しますか?",resumeButton:"印刷を再開",powerOnTitle:"プリンターの電源をオン",powerOnMessage:"「{{name}}」の電源をオンにしますか?",powerOffTitle:"プリンターの電源をオフ",powerOffMessage:"「{{name}}」の電源をオフにしますか?",powerOffWarning:"警告: 「{{name}}」は現在印刷中です!電源をオフにしますか?印刷が中断され、プリンターが損傷する可能性があります。",deleteArchivesNote:"このプリンターのすべての印刷履歴が完全に削除されます。",keepArchivesNote:"印刷履歴は保持されますが、このプリンターとの関連は解除されます。",powerOnButton:"電源オン",powerOffButton:"電源オフ"},discovery:{title:"プリンター",scanning:"スキャン中...",allConfigured:"検出されたすべてのプリンターは既に設定済みです。",subnetToScan:"スキャンするサブネット",scanSubnet:"サブネットをスキャンしてプリンターを検出",discoverNetwork:"ネットワーク上のプリンターを検出",scanningSubnet:"サブネットでBambuプリンターをスキャン中...",scanningNetwork:"ネットワークをスキャン中...",serialRequired:"シリアル番号が必要です",unknown:"不明",failedToStart:"印刷の開始に失敗しました",searching:"検索中...",scanProgress:"スキャン中... {{scanned}}/{{total}}",foundPrinters:"{{count}}台のプリンターを検出",noPrintersFound:"プリンターが見つかりません",noPrintersFoundSubnet:"指定されたサブネットにプリンターが見つかりません。",noPrintersFoundNetwork:"ネットワーク上にプリンターが見つかりません。",alreadyAdded:"追加済み",select:"選択",manualEntry:"手動入力",addFromCloud:"クラウドから追加",dockerNote:"Dockerを検出しました。プリンターのサブネットをCIDR表記で入力してください。docker-compose.ymlでnetwork_mode: hostが必要です。"},filaments:"フィラメント",firmwareUpdateAvailable:"ファームウェアアップデートあり: {{current}} → {{latest}}",firmwareUpToDate:"ファームウェア {{version}} — 最新",plateDetection:{noPermission:"このページにアクセスする権限がありません。",title:"プレート検出",description:"印刷前にビルドプレート上のオブジェクトを検出",referenceCapture:"リファレンス画像を撮影",captureReference:"リファレンスを撮影",deleteReference:"リファレンスを削除",sensitivity:"感度",detectionArea:"検出エリア",saveArea:"エリアを保存",resetArea:"エリアをリセット",testDetection:"検出テスト",testing:"テスト中...",objectsDetected:"オブジェクトを検出しました",noObjectsDetected:"オブジェクトは検出されませんでした",requiresCamera:"カメラが必要です",referenceRequired:"まずリファレンス画像を撮影してください",enabledClick:"プレートチェック有効 - クリックして無効化",disabledClick:"プレートチェック無効 - クリックして有効化",manageCalibration:"プレート検出キャリブレーションを管理",calibrationRequired:"キャリブレーションが必要です",calibrationInstructions:"ビルドプレートが<strong>完全に空</strong>であることを確認してから、キャリブレーションをクリックしてください。",calibrationDescription:"キャリブレーションは空のプレートのリファレンス画像を撮影します。以降のチェックではこのリファレンスと比較してオブジェクトを検出します。",calibrationTip:"<strong>ヒント:</strong> 異なるプレート用に最大5つのキャリブレーションを保存できます。チェック時に最適なものが自動的に使用されます。",plateEmpty:"プレートは空のようです",confidence:"信頼度",difference:"差分",analysisPreview:"分析プレビュー:",analysisLegend:"緑の枠 = 検出エリア、赤のオーバーレイ = キャリブレーションとの差分",savedReferences:"保存済みリファレンス ({{count}}/{{max}})",labelPlaceholder:"ラベル...",clickToEdit:"{{label}} - クリックして編集",clickToAddLabel:"クリックしてラベルを追加"},fans:{partCooling:"パーツ冷却ファン",auxiliary:"補助ファン",chamber:"チャンバーファン"},estimatedCompletion:"完了予定時刻",slotOptions:"スロットオプション",firmwareModal:{title:"ファームウェアアップデート",titleUpToDate:"ファームウェア情報",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",releaseNotes:"リリースノート",sdCardReady:"SDカード準備完了。下をクリックしてファームウェアをアップロードしてください。",applyInstructions:"プリンターでアップデートを適用するには:",step1:"プリンターのタッチスクリーンで設定に移動",step2:"ファームウェアに移動",step3:"SDカードからアップデートを選択",step4:"アップデートには10〜20分かかります",done:"完了",starting:"開始中...",uploadFirmware:"ファームウェアをアップロード",checkingPrereqs:"前提条件を確認中...",uploadedSuccess:"ファームウェアをSDカードにアップロードしました!",uploadFailed:"アップロード開始に失敗しました: {{error}}",uploadedToast:"ファームウェアをアップロードしました!プリンター画面からアップデートを実行してください。"},accessCodePlaceholder:"プリンター設定から取得",roi:{title:"プリンター",xStart:"X開始",yStart:"Y開始",width:"幅",height:"高さ",instruction:"ビルドプレートに焦点を合わせるように検出エリアを調整してください。プレビューの緑の枠が現在のエリアを示しています。"},deleteConfirm:"「{{name}}」を削除しますか?",maintenanceDue_plural:"{{count}}件の期限",offlinePrintersWithPlugs:"スマートプラグ付きオフラインプリンター",noLabel:"ラベルなし",printPreview:"印刷プレビュー",width:"幅",height:"高さ",noObjectsFound:"オブジェクトが見つかりません",objectsLoadedOnPrintStart:"オブジェクトは印刷開始時に読み込まれます",serialCannotBeChanged:"シリアル番号は変更できません",locationHelp:"プリンターのグループ化とキュージョブのフィルタリングに使用",autoOffAfterPrint:"印刷後に自動電源オフ",autoOffExecuted:"自動オフが実行されました - リセットするにはプリンターの電源を入れてください",viewHmsErrors:"{{count}}件のHMSエラーを表示",camera:"カメラ",skipObject:"オブジェクトスキップ",firmwareUpdate:"ファームウェアアップデート",firmwareInstructions:"プリンターのタッチスクリーンで",firmwareNav:"に移動",settings:"設定",firmware:"ファームウェア",discoverPrinters:"プリンターを検出",searching:"検索中...",manualEntry:"手動入力",addFromCloud:"クラウドから追加",cloud:{title:"Bambu Cloud プリンター",loginRequired:"クラウドにログインしてプリンターを追加してください",loginFirst:"まずプロファイルページからBambu Cloudにログインしてください",goToProfiles:"プロファイルへ移動",loadingPrinters:"クラウドプリンターを読み込み中...",noPrinters:"クラウドにプリンターが見つかりません",alreadyConfigured:"設定済み",accessCodeRequired:"アクセスコードが必要です",addPrinter:"プリンターを追加",adding:"追加中..."},name_field:"名前",nozzleSize:"ノズルサイズ",rfid:{reread:"RFID再読み取り"},openCameraOverlay:"カメラオーバーレイを開く",openCameraWindow:"カメラを新しいウィンドウで開く",firmwareUpdateButton:"アップデート",clickToViewHmsErrors:"クリックしてHMSエラーを表示",developerModeWarning:"開発者LANモードが有効になっていません: {{names}}。一部の機能が動作しない可能性があります。",howToEnable:"有効化方法"},archives:{title:"印刷アーカイブ",searchPlaceholder:"アーカイブを検索...",filterByPrinter:"プリンターで絞り込み",filterByStatus:"ステータスで絞り込み",sortBy:"並べ替え",sortNewest:"新しい順",sortOldest:"古い順",sortName:"名前順",sortDuration:"時間順",noArchives:"アーカイブが見つかりません",noArchivesYet:"アーカイブはまだありません",releaseToUpload:"ドロップしてアップロード",showAll:"すべて表示",showFavoritesOnly:"お気に入りのみ表示",gridView:"グリッド表示",listView:"リスト表示",calendarView:"カレンダー表示",logView:"印刷ログ",showFailedPrints:"失敗した印刷を表示",hideFailedPrints:"失敗した印刷を非表示",printTime:"印刷時間",filamentUsed:"フィラメント使用量",cost:"コスト",reprint:"再印刷",preview:"プレビュー",deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",favorite:"お気に入り",unfavorite:"お気に入りから削除",viewDetails:"詳細を表示",status:{completed:"完了",failed:"失敗",stopped:"中止"},toast:{source3mfAttached:"ソース3MFを添付しました: {{filename}}",source3mfRemoved:"ソース3MFを削除しました",f3dAttached:"F3Dを添付しました: {{filename}}",f3dRemoved:"F3Dを削除しました",timelapseAttached:"タイムラプスを添付しました: {{filename}}",addedToFavorites:"お気に入りに追加しました",removedFromFavorites:"お気に入りから削除しました",linkCopied:"リンクをクリップボードにコピーしました",photoDeleted:"写真を削除しました",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました",addedToProject:"プロジェクトに追加しました",removedFromProject:"プロジェクトから削除しました",failedToAddToProject:"プロジェクトへの追加に失敗しました",failedToRemoveFromProject:"プロジェクトからの削除に失敗しました",noFile:"印刷ファイルがありません",slicerOpened:"スライサーを開きました",failedToOpenSlicer:"スライサーの起動に失敗しました",archived:"アーカイブしました",sentToFileManager:"ファイルマネージャーに送信しました",deleted:"アーカイブを削除しました",updated:"アーカイブを更新しました",failedToDelete:"アーカイブの削除に失敗しました",failedToUpdate:"アーカイブの更新に失敗しました",failedToSend:"送信に失敗しました",sentToPrinter:"プリンターに送信しました",addedToQueue:"キューに追加しました",failedUploadSource3mf:"ソース3MFのアップロードに失敗しました",failedRemoveSource3mf:"ソース3MFの削除に失敗しました",failedUploadF3d:"F3Dのアップロードに失敗しました",failedRemoveF3d:"F3Dの削除に失敗しました",timelapseAlreadyAttached:"タイムラプスは既に添付されています",noMatchingTimelapse:"一致するタイムラプスが見つかりません",failedScanTimelapse:"タイムラプスのスキャンに失敗しました",failedAttachTimelapse:"タイムラプスの添付に失敗しました",timelapseRemoved:"タイムラプスを削除しました",failedRemoveTimelapse:"タイムラプスの削除に失敗しました",timelapseUploaded:"タイムラプスをアップロードしました: {{filename}}",failedUploadTimelapse:"タイムラプスのアップロードに失敗しました",archiveDeleted:"アーカイブを削除しました",failedDeleteArchive:"アーカイブの削除に失敗しました",projectUpdated:"プロジェクトを更新しました",failedUpdateProject:"プロジェクトの更新に失敗しました",failedCopyLink:"リンクのコピーに失敗しました",failedDeletePhoto:"写真の削除に失敗しました",failedDeleteArchives:"アーカイブの削除に失敗しました",failedUpdateFavorites:"お気に入りの更新に失敗しました"},menu:{schedule:"スケジュール",slice:"スライス",externalLink:"外部リンク",viewOnMakerWorld:"MakerWorldで表示",preview3d:"3Dプレビュー",viewTimelapse:"タイムラプスを表示",downloadSource3mf:"ソース3MFをダウンロード",uploadSource3mf:"ソース3MFをアップロード",replaceSource3mf:"ソース3MFを置換",removeSource3mf:"ソース3MFを削除",uploadF3d:"F3Dをアップロード",replaceF3d:"F3Dを置換",downloadF3d:"Fusion 360デザインファイルをダウンロード",removeF3d:"F3Dを削除",download:"ダウンロード",qrCode:"QRコード",viewPhotos:"{{count}}枚の写真を表示",projectPage:"プロジェクトページ",goToProject:"プロジェクトへ: {{name}}",addToProject:"プロジェクトに追加",loading:"アーカイブを読み込み中...",select:"選択",deselect:"選択解除",print:"印刷",openInBambuStudio:"スライサーで開く",scanForTimelapse:"タイムラプスをスキャン",uploadTimelapse:"タイムラプスをアップロード",removeTimelapse:"タイムラプスを削除",copyDownloadLink:"ダウンロードリンクをコピー",viewPhotosCount:"写真を表示 ({{count}})",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",edit:"編集",removeFromProject:"プロジェクトから削除",noProjectsAvailable:"利用可能なプロジェクトがありません",delete:"削除"},card:{plateNumber:"プレート {{number}}",moreOptions:"その他のオプション",failed:"失敗",openSource3mf:"ソース3MFをBambu Studioで開く(右クリックでオプション表示)",downloadF3d:"Fusion 360デザインファイルをダウンロード",viewTimelapse:"タイムラプスを表示",viewPhotos:"{{count}}枚の写真を表示",openFolder:"フォルダーを開く: {{name}}",source:"ソース",project:"プロジェクト",layer:"レイヤー",layers:"レイヤー",objects:"{{count}}オブジェクト",noPermissionEdit:"プロファイルを編集する権限がありません",reprint:"再印刷",schedulePrint:"印刷をスケジュール",schedule:"スケジュール",slice:"スライス",externalLink:"外部リンク",preview3d:"3Dプレビュー",download:"ダウンロード",previousPlate:"前のプレート",nextPlate:"次のプレート",addToFavorites:"お気に入りに追加",removeFromFavorites:"お気に入りから削除",cancelled:"キャンセル",duplicate:"重複",duplicateTitle:"このモデルは以前印刷されています",viewPhoto:"写真を表示",slicedFile:"スライス済みファイル - 印刷可能",sourceFile:"ソースファイルのみ - AMSマッピング不可",gcode:"GCODE",estimated:"推定: {{time}}",actual:"実際: {{time}}",accuracy:"精度: {{percent}}%",filament:"{{weight}}g",object:"{{count}}オブジェクト",slicedFor:"{{model}}用にスライス",uploadedBy:"アップロード者",noPermissionReprint:"再印刷する権限がありません",noFileForReprint:"3MFファイルがありません — 印刷記録時にプリンターからファイルをダウンロードできませんでした",noPermissionDelete:"アーカイブを削除する権限がありません",openInBambuStudio:"スライサーで開く",openInBambuStudioToSlice:"スライサーでスライス",makerWorld:"MakerWorld: {{designer}}",viewProject:"プロジェクトを表示",noExternalLink:"外部リンクなし",edit:"編集",delete:"削除"},modal:{deleteArchive:"アーカイブを削除",deleteConfirm:"このアーカイブを削除しますか?",removeSource3mf:"ソース3MFを削除",removeSource3mfConfirm:'"{{name}}"からソース3MFファイルを削除してもよろしいですか?元のスライサープロジェクトファイルが削除されます。',removeF3d:"F3Dを削除",removeF3dConfirm:'"{{name}}"からFusion 360デザインファイルを削除してもよろしいですか?',removeTimelapse:"タイムラプスを削除",removeTimelapseConfirm:'"{{name}}"からタイムラプス動画を削除してもよろしいですか?',selectTimelapse:"タイムラプスを選択",selectTimelapseDesc:"自動一致が見つかりませんでした。この印刷のタイムラプスを選択してください:",deleteArchives:"印刷アーカイブを削除",deleteCount:"{{count}}件を削除",deleteButton:"削除",removeButton:"削除",timelapse:"{{name}} - タイムラプス",deleteArchivesConfirm:"{{count}}件のアーカイブを削除しますか?この操作は元に戻せません。"},page:{title:"印刷アーカイブ",printsCount:"{{count}}回印刷",dropFilesHere:".3mfファイルをここにドロップ",releaseToUpload:"ドロップしてアップロード",only3mfSupported:".3mfファイルのみ対応しています",selected:"{{count}}件選択中",selectAll:"すべて選択",tags:"タグ",project:"プロジェクト",favorite:"お気に入り",toggledFavorites:"{{count}}件のアーカイブのお気に入りを切替えました",photoDeleted:"写真を削除しました",close:"閉じる",delete:"削除",failedUpdateFavorites:"お気に入りの更新に失敗しました",archivesDeleted:"{{count}}件のアーカイブを削除しました",failedDeleteArchives:"アーカイブの削除に失敗しました",failedDeletePhoto:"写真の削除に失敗しました"},list:{size:"サイズ",hasTimelapse:"タイムラプスあり",name:"名前",printer:"プリンター",date:"日付",actions:"操作"},log:{date:"日時",printName:"印刷名",printer:"プリンター",user:"ユーザー",status:"ステータス",duration:"所要時間",filament:"フィラメント",allPrinters:"全プリンター",allUsers:"全ユーザー",allStatuses:"全ステータス",cancelled:"キャンセル",skipped:"スキップ",dateFrom:"開始日",dateTo:"終了日",noEntries:"印刷ログが見つかりません",showing:"{{total}}件中{{count}}件を表示",rowsPerPage:"行数",page:"ページ",prev:"前へ",next:"次へ",clearLog:"ログをクリア",clearLogTitle:"印刷ログをクリア",clearLogConfirm:"すべての印刷ログエントリが完全に削除されます。アーカイブとキューアイテムには影響しません。この操作は元に戻せません。よろしいですか?",clearLogButton:"すべてクリア",cleared:"{{count}}件のログエントリを削除しました",clearFailed:"印刷ログの削除に失敗しました"},noPrinterAvailable:"利用可能なプリンターがありません",archiveOrReprint:"アーカイブまたは再印刷",multiPrinterPrint:"マルチプリンター印刷",noPrintersForReprint:"再印刷用のプリンターがありません",searchMakerworld:"MakerWorldで検索",searchPrintables:"Printablesで検索",searchThingiverse:"Thingiverseで検索",openInSlicer:"スライサーで開く",openWithProtocol:"{{slicer}}で開く",context:{reprint:"再印刷",addToQueue:"キューに追加",delete:"削除",edit:"編集",compare:"比較",viewTimelapse:"タイムラプスを表示",downloadTimelapse:"タイムラプスをダウンロード",openInBambuStudio:"スライサーで開く",openInOrcaSlicer:"OrcaSlicerで開く",addToProject:"プロジェクトに追加",removeFromProject:"プロジェクトから削除",downloadGcode:"GCodeをダウンロード",download3mf:"3MFをダウンロード",downloadModel:"モデルをダウンロード",viewPhotos:"写真を表示",searchOnline:"オンラインで検索",sendToFileManager:"ファイルマネージャーに送信",sendToPrinter:"プリンターに送信",openStlViewer:"STLビューアーで開く"},permissions:{noReprint:"再印刷する権限がありません",noDelete:"削除する権限がありません",noEdit:"編集する権限がありません",noDownload:"ダウンロードする権限がありません",noQueue:"キューに追加する権限がありません",noSendToPrinter:"プリンターに送信する権限がありません",noSendToFileManager:"ファイルマネージャーに送信する権限がありません",noUpload:"アップロードする権限がありません",noBulkDelete:"一括削除する権限がありません"},costPerPrint:"印刷あたりのコスト",energyCost:"エネルギーコスト",totalCost:"合計コスト",noFilament:"フィラメントデータなし",printCount:"{{count}}回印刷",timesShort:"{{count}}回",perPrint:"/1回あたり",gcodeAvailable:"GCode利用可能",noGcode:"GCodeなし",plates:"プレート",filaments:"フィラメント",settings_label:"設定",weight:"重量",printSettings:"印刷設定",layerHeight:"レイヤー高さ",nozzleTemp:"ノズル温度",bedTemp:"ベッド温度",infill:"インフィル",supports:"サポート",model3d:"3Dモデル",noModel:"モデルなし",printNumber:"印刷 #{{number}}",sortLargest:"大きい順",sortSmallest:"小さい順",sortSize:"サイズ",noArchivesSearch:"検索条件に一致するアーカイブがありません",loadingArchives:"アーカイブを読み込み中...",manageTags:"タグを管理",permission:{noReprint:"このアーカイブを再印刷する権限がありません",noAddToQueue:"キューに追加する権限がありません",noUpdateArchives:"アーカイブを更新する権限がありません",noUploadFiles:"ファイルをアップロードする権限がありません",noDownload:"アーカイブをダウンロードする権限がありません",noCopyLink:"ダウンロードリンクをコピーする権限がありません",noDelete:"このアーカイブを削除する権限がありません",noCreate:"アーカイブを作成する権限がありません"}},queue:{title:"印刷キュー",addToQueue:"キューに追加",schedulePrint:"印刷をスケジュール",editQueueItem:"キューアイテムを編集",adding:"追加中...",clearQueue:"キューをクリア",clearHistory:"履歴をクリア",emptyQueue:"キューは空です",position:"順番",scheduledTime:"予定時刻",moveUp:"上に移動",moveDown:"下に移動",startNow:"今すぐ開始",printingInProgress:"印刷中...",viewArchive:"アーカイブを表示",viewInFileManager:"ファイルマネージャーで表示",itemCount:"{{count}}件",dragToReorder:"ドラッグして並べ替え(ASAPのみ)",addedBy:"{{username}}が追加",nextInQueue:"次のキュー",clearPlate:"プレートをクリアして次を開始",clearPlateSuccess:"プレートをクリアしました — 次の印刷の準備完了",plateReady:"プレートをクリアしました — 次の印刷の準備完了",plateNumber:"プレート {{index}}",sections:{currentlyPrinting:"印刷中",queued:"キュー中",history:"履歴"},status:{pending:"待機中",waiting:"待機中",printing:"印刷中",paused:"一時停止",completed:"完了",failed:"失敗",skipped:"スキップ",cancelled:"キャンセル済み"},summary:{printing:"印刷中",queued:"キュー中",history:"履歴",totalTime:"キュー合計時間",totalWeight:"キュー合計重量"},filter:{allPrinters:"すべてのプリンター",unassigned:"未割当",allStatus:"すべてのステータス",allLocations:"すべてのロケーション",any:"すべて"},sort:{byPosition:"順番で並べ替え",byName:"名前で並べ替え",byPrinter:"プリンターで並べ替え",bySchedule:"スケジュールで並べ替え",byDate:"日付で並べ替え",ascendingOldest:"昇順(古い順)",descendingNewest:"降順(新しい順)"},badges:{staged:"ステージ済み",autoPowerOff:"自動電源オフ",requiresPrevious:"前の成功が必要"},empty:{title:"スケジュールされた印刷はありません",description:"アーカイブページのコンテキストメニューから「スケジュール」オプションを使用するか、ファイルをドラッグ&ドロップして始めましょう。"},time:{asap:"即時",overdue:"期限超過",now:"今すぐ",inMinutes:"{{count}}分後",inHours:"{{count}}時間後",lessThanMinute:"1分以内"},actions:{stopPrint:"印刷を停止",startPrint:"印刷を開始",requeue:"再キュー"},bulkEdit:{title:"{{count}}件のアイテムを編集",description:"変更した設定のみが選択されたアイテムに適用されます。",printer:"プリンター",noChange:"— 変更なし —",queueOptions:"キューオプション",staged:"ステージ済み",autoPowerOff:"印刷後に自動電源オフ",printOptions:"印刷オプション",bedLevelling:"ベッドレベリング",flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",timelapse:"タイムラプス",useAms:"AMS使用",applyChanges:"変更を適用",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",editSelected:"選択を編集",cancelSelected:"選択をキャンセル",title_plural:"{{count}}件のアイテムを編集",requirePrevious:"前の成功を必要とする",layerInspection:"第一層検査"},confirm:{cancelTitle:"スケジュール済み印刷をキャンセル",cancelMessage:"「{{name}}」をキャンセルしますか?",stopTitle:"印刷を停止",stopMessage:"現在の印刷「{{name}}」を停止しますか?プリンター上の印刷ジョブがキャンセルされます。",removeTitle:"履歴から削除",removeMessage:"「{{name}}」をキュー履歴から削除しますか?",clearHistoryMessage:"{{count}}件の履歴をすべて削除しますか?",cancelButton:"印刷をキャンセル",stopButton:"印刷を停止",thisPrint:"この印刷",thisItem:"このアイテム",clearHistoryTitle:"履歴をクリア"},toast:{cancelled:"キャンセル済み",removeFailed:"プロジェクトからのアーカイブ削除に失敗しました",cancelFailed:"アイテムのキャンセルに失敗しました",removed:"キューアイテムを削除しました",stopped:"印刷を停止しました",stopFailed:"印刷の停止に失敗しました",released:"印刷をキューにリリースしました",startFailed:"印刷の開始に失敗しました",reorderFailed:"キューの並べ替えに失敗しました",historyCleared:"{{count}}件の履歴をクリアしました",clearHistoryFailed:"履歴のクリアに失敗しました",updateFailed:"アイテムの更新に失敗しました",bulkCancelled:"{{count}}件のアイテムをキャンセルしました",bulkCancelFailed:"アイテムのキャンセルに失敗しました"},subtitle:"印刷ジョブのスケジュールと管理",print:"印刷",reprint:"再印刷",printToPrinters:"{{count}}台のプリンターで印刷",queueToPrinters:"{{count}}台のプリンターでキュー追加",sending:"送信中...",sendingProgress:"送信中 {{current}}/{{total}}...",addingProgress:"追加中 {{current}}/{{total}}...",savingProgress:"保存中 {{current}}/{{total}}...",itemCount_plural:"{{count}}件のアイテム",reorderHint:"順番はASAPアイテムのみに影響します。スケジュール済みアイテムは設定時刻に実行されます。",permissions:{noStopPrint:"印刷を停止する権限がありません",noStartPrint:"印刷を開始する権限がありません",noEdit:"このキューアイテムを編集する権限がありません",noCancel:"このキューアイテムをキャンセルする権限がありません",noRequeue:"アイテムを再キューする権限がありません",noRemove:"このキューアイテムを削除する権限がありません",noClearHistory:"すべての履歴をクリアする権限がありません",noEditItems:"キューアイテムを編集する権限がありません",noCancelItems:"キューアイテムをキャンセルする権限がありません"}},backgroundDispatch:{unknownFile:"不明なファイル",unknownPrinter:"不明なプリンター",startingPrints:"印刷開始中",progressSummary:"{{complete}}/{{total}} 完了 • 配信済み: {{dispatched}} • 処理中: {{processing}}",expandDetails:"配信詳細を展開",collapseDetails:"配信詳細を折りたたむ",dismissToast:"配信トーストを閉じる",cancelDispatchJob:"配信ジョブをキャンセル",cancel:"キャンセル",cancelling:"キャンセル中…",status:{dispatched:"配信済み",processing:"処理中",completed:"完了",failed:"失敗",cancelled:"キャンセル済み"},toast:{cancellingUpload:"アップロードをキャンセル中...",cancelled:"配信をキャンセルしました",cancelFailed:"配信のキャンセルに失敗しました",completeWithFailures:"バックグラウンド配信完了: {{completed}} 件成功、{{failed}} 件失敗",completeSuccess:"バックグラウンド配信完了: {{completed}} 件成功"}},stats:{title:"統計",overview:"概要",totalPrints:"総印刷数",successRate:"成功率",totalPrintTime:"総印刷時間",printTime:"印刷時間",totalFilament:"総フィラメント使用量",filamentUsed:"フィラメント使用量",filamentCost:"フィラメントコスト",totalCost:"総コスト",energyUsed:"エネルギー使用量",energyCost:"エネルギーコスト",averagePrintTime:"平均印刷時間",printsPerDay:"1日あたりの印刷数",byPrinter:"プリンター別",printsByPrinter:"プリンター別印刷数",byMaterial:"素材別",byMonth:"月別",last7Days:"過去7日間",last30Days:"過去30日間",last90Days:"過去90日間",allTime:"全期間",quickStats:"クイック統計",printActivity:"印刷アクティビティ",filamentTypes:"フィラメントタイプ",timeAccuracy:"時間精度",successful:"成功",failed:"失敗",perfectEstimate:"100% = 完全な推定",noTimeAccuracyData:"時間精度データがありません",noFilamentData:"フィラメントデータがありません",noPrinterData:"プリンターデータがありません",noPrintData:"印刷データがありません",noPrintDataLast30Days:"過去30日間の印刷データがありません",failureReasons:"失敗理由",topFailureReasons:"主な失敗理由",resetLayout:"レイアウトをリセット",recalculateCosts:"コストを再計算",exportStats:"統計をエクスポート",exportAsCsv:"CSVでエクスポート",exportAsExcel:"Excelでエクスポート",hiddenCount:"{{count}}件非表示",exportDownloaded:"エクスポートをダウンロードしました",exportFailed:"エクスポートに失敗しました",layoutReset:"レイアウトをリセットしました",recalculateFailed:"コストの再計算に失敗しました",noPermissionResetLayout:"レイアウトをリセットする権限がありません",noPermissionRecalculate:"コストを再計算する権限がありません",subtitle:"ウィジェットをドラッグして並べ替え。目のアイコンをクリックして非表示。",filamentTrends:"フィラメントトレンド",failureAnalysis:"失敗分析",failedPrintsCount:"{{failed}} / {{total}} 件の印刷が失敗",lastWeekRate:"先週: {{rate}}%",recalculateCostsHint:"現在のフィラメント価格ですべてのアーカイブコストを再計算",recalculatedCosts:"{{count}}件のアーカイブのコストを再計算しました",loadingStats:"統計を読み込み中..."},maintenance:{title:"メンテナンス",overview:"概要",allOk:"すべてのメンテナンスは最新です",dueCount:"{{count}}件の期限到来",dueCount_plural:"{{count}}件の期限到来",warningCount:"{{count}}件の警告",warningCount_plural:"{{count}}件の警告",totalPrintTime:"総印刷時間",nextMaintenance:"次回メンテナンス",nothingDue:"予定なし",tasks:"タスク",lastPerformed:"前回実施日",interval:"間隔",hoursRemaining:"残り{{hours}}時間",hoursOverdue:"{{hours}}時間超過",markDone:"完了にする",performMaintenance:"メンテナンスを実施",history:"履歴",noHistory:"メンテナンス履歴がありません",editPrintHours:"印刷時間を編集",currentHours:"現在の時間",dueSoon:"まもなく期限",allGood:"問題なし",days:"日",weeks:"{{count}}週間",months:"{{count}}ヶ月",maintenanceTypes:"メンテナンスタイプ",addCustomType:"カスタムタイプを追加",restoreDefaults:"デフォルトタスクを復元",intervalType:"インターバルタイプ",icon:"アイコン",documentationLink:"ドキュメントリンク(任意)",assignToPrinters:"プリンターに割り当て",selectAtLeastOnePrinter:"プリンターを1台以上選択してください",addType:"タイプを追加",custom:"カスタム",printHours:"印刷時間",calendarDays:"カレンダー日数",viewDocumentation:"ドキュメントを表示",timeBasedInterval:"時間ベースのインターバル",intervalOverrides:"インターバルのオーバーライド",assignedToPrinters:"割り当て済みプリンター:",noPrintersAssigned:"プリンター未割り当て",removeFromPrinter:"このプリンターから削除",types:{lubricateCarbonRods:"カーボンロッドの潤滑",lubricateRails:"リニアレールの潤滑",cleanNozzle:"ノズル/ホットエンドの清掃",checkBelts:"ベルト張力の確認",cleanBuildPlate:"ビルドプレートの清掃",checkExtruder:"エクストルーダーギアの確認",checkCooling:"冷却ファンの確認",generalInspection:"総合点検",cleanCarbonRods:"カーボンロッドの清掃",cleanLinearRails:"リニアレールの清掃",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},typeUpdated:"メンテナンスタイプを更新しました",typeDeleted:"メンテナンスタイプを削除しました",defaultsRestored:"デフォルトタスクを{{count}}件復元しました",printerAssigned:"プリンターを割り当てました",printerRemoved:"プリンターを削除しました",deleteTypeConfirm:"「{{name}}」を削除しますか?",deleteSystemTypeTitle:"デフォルトのメンテナンスタスクを削除しますか?",deleteSystemTypeMessage:"デフォルトのメンテナンスタスク「{{name}}」を削除してもよろしいですか?",noPermissionUpdate:"メンテナンス記録を更新する権限がありません",noPermissionPerform:"メンテナンスを実行する権限がありません",noPermissionEditTypes:"メンテナンスタイプを編集する権限がありません",noPermissionDeleteTypes:"メンテナンスタイプを削除する権限がありません",noPermissionEditHours:"メンテナンス時間を編集する権限がありません",noPermissionEditIntervals:"メンテナンス間隔を編集する権限がありません",statusTab:"ステータス",settingsTab:"設定",overdueCount:"{{count}}件超過",dueSoonCount:"{{count}}件まもなく期限",overdueBy:"{{duration}}超過",dueIn:"あと{{duration}}",timeLeft:"残り{{duration}}",day:"1日",week:"1週間",month:"1ヶ月",year:"1年",maintenanceTypesDescription:"システムタイプとカスタムメンテナンスタスク",intervalValue:"間隔 ({{type}})",exampleName:"例: HEPAフィルター交換",intervalOverridesDescription:"特定のプリンターの間隔をカスタマイズ",addPrinterShort:"追加:",printersAssignedClick:"{{count}}台のプリンターを割り当て済み - クリックして管理",maintenanceComplete:"メンテナンスを完了としてマークしました",printHoursUpdated:"印刷時間を更新しました",noPermissionRemovePrinter:"プリンターの割り当てを解除する権限がありません",noPermissionAssignPrinter:"プリンターを割り当てる権限がありません",configureSettings:"メンテナンスタイプと間隔を設定"},settings:{title:"設定",general:"一般",tabs:{general:"一般",smartPlugs:"スマートプラグ",notifications:"通知",apiKeys:"APIキー",users:"認証",backup:"バックアップ",filament:"フィラメント",network:"ネットワーク",virtualPrinter:"仮想プリンター",emailAuth:"メール認証"},appearance:"外観",notifications:"通知",smartPlugs:"スマートプラグ",updates:"アップデート",language:"言語",languageDescription:"表示言語を選択してください",theme:"テーマ",themeLight:"ライト",themeDark:"ダーク",themeSystem:"システム設定に従う",defaultView:"デフォルト画面",defaultViewDescription:"アプリ起動時に表示するページ",checkForUpdates:"アップデートを確認",autoUpdate:"自動アップデート",currentVersion:"現在のバージョン",latestVersion:"最新バージョン",upToDate:"最新です",updateAvailable:"アップデートあり",notificationLanguage:"通知の言語",notificationLanguageDescription:"プッシュ通知の言語",bedCooledThreshold:"ベッド冷却しきい値",bedCooledThresholdDescription:"印刷後にベッドが冷却されたと見なす温度",notificationProviders:"通知プロバイダー",addProvider:"プロバイダーを追加",editProvider:"プロバイダーを編集",providerType:"プロバイダーの種類",testNotification:"テスト通知",testSuccess:"テスト通知を送信しました",testFailed:"テスト通知の送信に失敗しました",quietHours:"おやすみ時間",quietHoursDescription:"この時間帯は通知を送信しません",quietHoursStart:"開始",quietHoursEnd:"終了",events:{title:"通知イベント",printStart:"印刷開始",printComplete:"印刷完了",printFailed:"印刷失敗",printStopped:"印刷中止",printProgress:"進捗マイルストーン",printProgressDescription:"25%, 50%, 75%で通知",printerOffline:"プリンターオフライン",printerError:"プリンターエラー",filamentLow:"フィラメント残量低下",maintenanceDue:"メンテナンス期限",maintenanceDueDescription:"メンテナンスが必要なときに通知"},smartPlug:{title:"スマートプラグ",add:"スマートプラグを追加",edit:"スマートプラグを編集",name:"名前",ipAddress:"IPアドレス",linkedPrinter:"連携プリンター",autoOn:"自動電源オン",autoOnDescription:"印刷開始時に電源を入れる",autoOff:"自動電源オフ",autoOffDescription:"印刷完了後に電源を切る",offDelay:"オフ遅延",offDelayMinutes:"印刷後の待機時間(分)",offDelayTemp:"ノズル温度が下回ったとき",currentState:"現在の状態",turnOn:"電源オン",turnOff:"電源オフ"},email:{smtpSettings:"SMTP設定",smtpHost:"SMTPサーバー",smtpPort:"SMTPポート",security:"セキュリティ",authentication:"認証",username:"ユーザー名",password:"パスワード",fromEmail:"送信元メールアドレス",fromName:"送信者名",testConnection:"SMTP接続テスト",testRecipient:"テスト受信者メール",sendTest:"テストメール送信",sending:"送信中...",save:"設定を保存",saving:"保存中...",advancedAuth:"高度な認証",advancedAuthEnabled:"高度な認証が有効です",advancedAuthEnabledDesc:"メールベースのユーザー管理機能が有効になっています。新規ユーザーには自動生成されたパスワードがメールで送信され、ユーザーはパスワード忘れ機能でパスワードをリセットできます。",advancedAuthDisabled:"高度な認証が無効です",advancedAuthDisabledDesc:"高度な認証を有効にして、ユーザー管理のメールベース機能を有効化してください。",enable:"有効にする",disable:"無効にする",feature1:"パスワードは自動生成され、新規ユーザーにメールで送信されます",feature2:"ユーザーはユーザー名またはメールでログインできます",feature3:"パスワード忘れ機能が利用可能です",feature4:"管理者はメールでユーザーパスワードをリセットできます",errors:{requiredFields:"すべての必須フィールドに入力してください",usernameRequired:"認証が有効な場合、ユーザー名は必須です",enterTestEmail:"テストメールアドレスを入力してください",smtpServerAndEmail:"テストする前にSMTPサーバーと送信元メールを入力してください",usernamePasswordRequired:"認証が有効な場合、ユーザー名とパスワードは必須です",configureSmtpFirst:"最初にSMTP設定を構成してテストしてください"},success:{settingsSaved:"SMTP設定を保存しました"},securityOptions:{starttls:"STARTTLS (ポート 587)",ssl:"SSL/TLS (ポート 465)",none:"なし (ポート 25)"},authOptions:{enabled:"有効",disabled:"無効"}},noDefaultPrinter:"デフォルトなし(毎回選択)",sidebarOrder:"サイドバーの順序",saveThumbnails:"サムネイルを保存",captureFinishPhoto:"完了写真を撮影",noPrintersConfigured:"プリンターが設定されていません",checkPrinterFirmware:"プリンターファームウェアの確認",includeBetaUpdates:"ベータ版を含める",includeBetaUpdatesDesc:"アップデート確認時にベータ版およびプレリリース版を通知する",enableRetry:"リトライを有効化",homeAssistantDescription:"Home Assistantに接続してHA REST APIでスマートプラグを制御します。switch、light、input_booleanエンティティに対応しています。",environmentManagedLabel:"(環境変数で管理)",autoEnabledViaEnv:"環境変数により自動的に有効化されました",urlFromEnvReadOnly:"HA_URL環境変数で設定された値(読み取り専用)",tokenFromEnvReadOnly:"HA_TOKEN環境変数で設定された値(読み取り専用)",noSmartPlugsDescription:"Tasmotaベースのスマートプラグを追加して、エネルギー消費を追跡し、電源制御を自動化します。",noProvidersDescription:"アラートを受信するにはプロバイダーを追加してください。",noUsersFound:"ユーザーが見つかりません",noGroupsFound:"グループが見つかりません",noGroupsAvailable:"利用可能なグループがありません",passwordsDoNotMatch:"パスワードが一致しません",authDisabledTitle:"認証が無効です",deleteUserConfirm:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。",actionCannotBeUndone:"この操作は元に戻せません",addFirstSmartPlug:"最初のスマートプラグを追加",providers:"プロバイダー",log:"ログ",testAll:"すべてテスト",testResults:"テスト結果",messageTemplates:"メッセージテンプレート",apiKeys:"APIキー",apiKeysDescription:"外部連携やWebhook用のAPIキーを作成します。",createKey:"キーを作成",apiKeyCreated:"APIキーを作成しました",apiKeyCopyWarning:"今すぐこのキーをコピーしてください - 再表示されません!",createNewApiKey:"新しいAPIキーを作成",keyName:"キー名",readStatus:"ステータスの読み取り",readStatusDescription:"プリンターのステータスとキューを表示",manageQueue:"キューの管理",manageQueueDescription:"印刷キューへのアイテムの追加と削除",controlPrinter:"プリンターの制御",controlPrinterDescription:"印刷の一時停止、再開、停止",unnamedKey:"名前なしキー",lastUsed:"最終使用:",createFirstKey:"最初のキーを作成",webhookEndpoints:"Webhookエンドポイント",webhookApiKeyHint:"X-API-KeyヘッダーでAPIキーを使用してください。",webhook:{pausePrint:"印刷を一時停止",resumePrint:"印刷を再開",getAllStatus:"全プリンターステータスを取得",getSpecificStatus:"特定のプリンターステータスを取得",addToQueue:"印刷キューに追加",stopPrint:"印刷を停止"},apiBrowser:"APIブラウザ",apiBrowserDescription:"すべての利用可能なAPIエンドポイントを探索してテストします。",apiKeyForTesting:"テスト用APIキー",apiKeyPlaceholder:"CallMeBot APIキー",deleteApiKeyTitle:"APIキーを削除",deleteApiKeyMessage:"このAPIキーを削除してもよろしいですか?このキーを使用しているすべての連携が動作しなくなります。",deleteKey:"キーを削除",amsThresholdsDescription:"AMS湿度と温度インジケーターの色しきい値を設定します。",humidity:"湿度",goodGreen:"良好(緑)≤",fairOrange:"普通(オレンジ)≤",aboveFairBad:"普通のしきい値以上は赤(悪い)で表示",temperature:"温度",goodBlue:"良好(青)≤",aboveFairHot:"普通のしきい値以上は赤(高温)で表示",historyRetention:"履歴の保持",historyRetentionDescription:"古い湿度と温度データは自動的に削除されます",printModal:"印刷ダイアログ",authentication:"認証",authDisabledDescription:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",enableAuthentication:"認証を有効にする",currentUser:"現在のユーザー",changePassword:"パスワードを変更",admin:"管理者",users:"ユーザー",addUser:"ユーザーを追加",groups:"グループ",addGroup:"グループを追加",noDescription:"説明なし",createUser:"ユーザーを作成",username:"ユーザー名",enterUsername:"ユーザー名を入力",password:"パスワード",enterPassword:"パスワードを入力(6文字以上)",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",turnAllPlugsOn:"すべてのプラグをオン",turnAllPlugsOff:"すべてのプラグをオフ",clearLogsMessage:"30日以上前のすべての通知ログを完全に削除します。この操作は元に戻せません。",clearLogs:"通知ログを削除",resetPreferences:"設定をリセット",deleteGroup:"グループを削除",systemDefault:"システムデフォルト",archiveSettings:"アーカイブ設定",costTracking:"コスト追跡",dataManagement:"データ管理",storageUsage:"ストレージ使用量",storageUsageDescription:"カテゴリ別のデータ使用量の内訳",storageUsageTotal:"合計",storageUsageErrors:"エラー",storageUsageOtherBreakdown:"その他(静的アセット、スクリプト、設定ファイルを含む)",storageUsageSystem:"システム",storageUsageData:"データ",storageUsageUnavailable:"ストレージ使用量情報は利用できません",enableMqtt:"MQTTを有効化",useTls:"TLSを使用",enableMetricsEndpoint:"メトリクスエンドポイントを有効化",availableMetrics:"利用可能なメトリクス",editUser:"ユーザーを編集",groupName:"グループ名",enterNewPassword:"新しいパスワードを入力",confirmNewPassword:"新しいパスワードを確認",enterGroupName:"グループ名を入力",enterCurrentPassword:"現在のパスワードを入力",enterNewPasswordMin6:"新しいパスワードを入力(6文字以上)",toast:{keyCopied:"キーをクリップボードにコピーしました",keyAddedToBrowser:"キーをAPIブラウザに追加しました",clearLogsFailed:"ログの削除に失敗しました",apiKeyCreated:"APIキーを作成しました",apiKeyDeleted:"APIキーを削除しました",userCreated:"ユーザーが正常に作成されました",userUpdated:"ユーザーが正常に更新されました",userDeleted:"ユーザーが正常に削除されました",fillRequiredFields:"必須項目をすべて入力してください",passwordsDoNotMatch:"パスワードが一致しません",enterGroupName:"グループ名を入力",settingsSaved:"設定を保存しました",passwordChanged:"パスワードが正常に変更されました",connectionFailed:"接続失敗",testFailed:"テスト通知の送信に失敗しました",uiPreferencesReset:"UI設定をリセットしました。更新中...",authDisabled:"認証を無効にしました",authDisableFailed:"認証の無効化に失敗しました",groupCreated:"グループを作成しました",groupUpdated:"グループを更新しました",groupDeleted:"グループを削除しました",passwordTooShort:"パスワードは6文字以上必要です",cameraConnected:"カメラ接続{{resolution}}",copyFailed:"キーのコピーに失敗しました",cameraSettingsSaved:"カメラ設定を保存しました",enterCameraUrl:"カメラURLを入力してください"},testConnection:"接続テスト",spoolman:"Spoolman",archiveMode:{always:"常にアーカイブを作成",never:"アーカイブを作成しない",ask:"毎回確認"},checkForUpdatesLabel:"アップデートを確認",mqttConnectedTo:"接続先:",prometheusDescription:"プリンターデータをPrometheus形式で公開",noSmartPlugsTitle:"スマートプラグが設定されていません",noProvidersTitle:"プロバイダーが設定されていません",noTemplatesAvailable:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを生成してください。",apiPermissionView:"プリンターステータスとキューを表示",apiPermissionEdit:"印刷キューにアイテムを追加・削除",apiKeysEmptyTitle:"APIキーがありません",apiKeysEmptyDescription:"外部サービスと連携するためのAPIキーを作成してください。",systemGroupWarning:"システムグループ名は変更できません",authDisabledFeature1:"システムへのアクセスにログインを要求",authDisabledFeature2:"グループベースの権限で複数ユーザーを作成",authDisabledFeature3:"50以上のきめ細かな権限でアクセスを制御",userHasCreated:"このユーザーは以下を作成しています:",userItemsQuestion:"これらのアイテムをどうしますか?",testPassedCount:"{{count}}件成功",testFailedCount:"{{count}}件失敗",messageTemplatesDescription:"各イベントの通知メッセージをカスタマイズ。",useInApiBrowser:"APIブラウザーで使用",keyNamePlaceholder:"例: Home Assistant, OctoPrint",read:"読み取り",control:"制御",apiKeyHint:"このキーはX-API-Keyヘッダーとしてリクエストに送信されます。",amsDisplayThresholds:"AMS表示しきい値",keepSensorHistory:"センサー履歴の保持期間",expandCustomMapping:"カスタムマッピングをデフォルトで展開",expandCustomMappingDescription:"複数プリンターに印刷する際、プリンターごとのAMSマッピングを展開表示",authEnabledDescription:"ユーザー認証でインスタンスが保護されています",authDisabledMessage:"認証を有効にして、ユーザーアカウントの作成、権限の管理、Bambuddyインスタンスのセキュリティを確保しましょう。",system:"システム",userCount:"{{count}}人のユーザー",permissionCount:"{{count}}件の権限",viewReleaseOnGitHub:"GitHubでリリースを表示",clearNotificationLogs:"通知ログをクリア",resetUiPreferences:"UI設定をリセット",resetUiPreferencesMessage:"すべてのUI設定をデフォルトにリセットします:サイドバー順序、テーマ、ダッシュボードレイアウト、表示モード、ソート設定。プリンター、アーカイブ、サーバー設定は影響を受けません。クリア後にページがリロードされます。",deleteGroupTitle:"グループを削除",deleteGroupMessage:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。",disableAuthenticationTitle:"認証を無効化",disableAuthenticationMessage:"認証を無効にしますか?Bambuddyインスタンスにログインなしでアクセスできるようになります。ユーザーはデータベースに残りますが、認証は無効になります。",disableAuthentication:"認証を無効化",configureBambuddy:"Bambuddyを設定",newWindow:"新しいウィンドウ",embeddedOverlay:"埋め込みオーバーレイ",preferredSlicer:"優先スライサー",preferredSlicerDescription:"ファイルを開くスライサーアプリケーションを選択",externalCameras:"外部カメラ",printsOnly:"印刷のみ",totalConsumption:"総消費量",clearNotificationLogsDescription:"30日以上前の通知ログを削除",resetUiPreferencesDescription:"サイドバー順序、テーマ、表示モード、レイアウト設定をリセット。プリンター、アーカイブ、設定は影響を受けません。",enableHomeAssistant:"Home Assistantを有効化",deleteUserTitle:"ユーザーを削除",leaveEmptyForAnonymous:"匿名の場合は空のまま",leaveEmptyForNoAuth:"認証なしの場合は空のまま",enterDescriptionOptional:"説明を入力(任意)",filamentTracking:"フィラメント追跡",filamentTrackingDesc:"フィラメントスプールの追跡方法を選択してください。内蔵インベントリまたは外部Spoolmanサーバーを使用できます。",trackingModeBuiltIn:"内蔵インベントリ",trackingModeBuiltInDesc:"RFID自動検出と使用量追跡を含む",trackingModeSpoolmanDesc:"外部フィラメント管理サーバー",builtInFeatureRfid:"AMS内のBambu Lab RFIDスプールを自動検出",builtInFeatureUsage:"プリントごとのフィラメント消費量を追跡",builtInFeatureCatalog:"スプール、カラー、K値プロファイルを管理",builtInFeatureThirdParty:"サードパーティ製スプールをインベントリスプールに割り当て可能",amsSyncButton:"AMSから重量を同期",amsSyncTitle:"AMSからスプール重量を同期",amsSyncMessage:"接続されたプリンターの現在のAMS残量値で、すべてのインベントリスプール重量を上書きします。破損した重量データの復旧に使用してください。プリンターがオンラインである必要があります。",amsSyncing:"同期中...",amsSyncSuccess:"{{synced}}個のスプールを同期、{{skipped}}個をスキップ",amsSyncError:"AMSからの重量同期に失敗しました",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"Spoolmanサーバーのurl(例:http://localhost:7912)",spoolmanConnected:"接続中",spoolmanDisconnected:"未接続",status:"ステータス",connect:"接続",disconnect:"切断",howSyncWorks:"同期の仕組み",syncInfoRfidOnly:"RFIDを搭載した公式Bambu Labスプールのみ同期されます",syncInfoAutoCreate:"新しいスプールは初回同期時にSpoolmanに自動作成されます",syncInfoThirdPartySkipped:"Bambu Lab以外のスプール(サードパーティ、リフィル)はスキップされます",linkingExistingSpools:"既存スプールのリンク",linkingExistingSpoolsDesc:"既存のSpoolmanスプールをAMSにリンクするには、AMSスロットにカーソルを合わせて「Spoolmanにリンク」をクリックしてください。",syncMode:"同期モード",syncModeAuto:"自動",syncModeManual:"手動のみ",syncModeAutoDesc:"変更が検出されるとAMSデータが自動的に同期されます",syncModeManualDesc:"手動でトリガーした場合のみ同期",syncAmsData:"AMSデータを同期",syncAmsDataDesc:"プリンターのAMSデータをSpoolmanに手動同期",allPrinters:"全プリンター",catalog:{spoolCatalog:"スプールカタログ",spoolCatalogDescription:"ブランド/タイプ別の空スプール重量。スプール追加時の自動重量検索に使用されます。",searchCatalog:"カタログを検索...",addNewEntry:"新しいエントリを追加",namePlaceholder:"名前(例:Bambu Lab - プラスチック)",weight:"重量",type:"タイプ",default:"デフォルト",custom:"カスタム",noMatch:"検索に一致するエントリがありません",empty:"カタログにエントリがありません",deleteEntry:"エントリを削除",deleteConfirm:"「{{name}}」を削除してもよろしいですか?",resetCatalog:"カタログをリセット",resetConfirm:"カタログをデフォルトにリセットしますか?カスタムエントリはすべて削除されます。",loadFailed:"スプールカタログの読み込みに失敗しました",nameWeightRequired:"名前と重量は必須です",entryAdded:"エントリを追加しました",addFailed:"エントリの追加に失敗しました",entryUpdated:"エントリを更新しました",updateFailed:"エントリの更新に失敗しました",entryDeleted:"エントリを削除しました",deleteFailed:"エントリの削除に失敗しました",resetSuccess:"カタログをデフォルトにリセットしました",resetFailed:"カタログのリセットに失敗しました",exported:"{{count}}件のエントリをエクスポートしました",imported:"{{added}}件のエントリをインポートしました({{skipped}}件スキップ)",importFailed:"インポートに失敗しました:無効なJSON形式",exportTooltip:"カタログをJSONにエクスポート",importTooltip:"JSONからカタログをインポート",resetTooltip:"デフォルトにリセット"},colorCatalog:{title:"カラーカタログ",description:"メーカー/素材別のフィラメントカラー。スプール追加時の自動カラー検索に使用されます。",searchColors:"カラーを検索...",allManufacturers:"すべてのメーカー",addNewColor:"新しいカラーを追加",manufacturer:"メーカー",colorName:"カラー名",hex:"Hex",materialOptional:"素材(任意)",showing:"{{total}}件中{{filtered}}件を表示",noMatch:"検索に一致するカラーがありません",empty:"カタログにカラーがありません",deleteColor:"カラーを削除",deleteConfirm:"「{{name}}」を削除してもよろしいですか?",resetCatalog:"カラーカタログをリセット",resetConfirm:"カタログをデフォルトにリセットしますか?カスタムカラーはすべて削除されます。",sync:"同期",starting:"開始中...",syncTooltip:"FilamentColors.xyzから同期(2000+カラー)",loadFailed:"カラーカタログの読み込みに失敗しました",fieldsRequired:"メーカー、カラー名、Hexカラーは必須です",colorAdded:"カラーを追加しました",addFailed:"カラーの追加に失敗しました",colorUpdated:"カラーを更新しました",updateFailed:"カラーの更新に失敗しました",colorDeleted:"カラーを削除しました",deleteFailed:"カラーの削除に失敗しました",resetSuccess:"カラーカタログをデフォルトにリセットしました",resetFailed:"カタログのリセットに失敗しました",syncUpToDate:"最新の状態です({{count}}件のカラーを確認)",syncComplete:"{{added}}件の新しいカラーを追加しました({{skipped}}件は既に存在)",syncError:"同期エラー",syncFailed:"FilamentColors.xyzからの同期に失敗しました",exported:"{{count}}件のカラーをエクスポートしました",imported:"{{added}}件のカラーをインポートしました({{skipped}}件スキップ)",importFailed:"インポートに失敗しました:無効なJSON形式"}},notification:{printStarted:{title:"印刷開始",body:"{{printer}}: {{filename}} の印刷を開始しました"},printCompleted:{title:"印刷完了",body:"{{printer}}: {{filename}} が正常に完了しました"},printFailed:{title:"印刷失敗",body:"{{printer}}: {{filename}} が失敗しました"},printStopped:{title:"印刷中止",body:"{{printer}}: {{filename}} が中止されました"},printProgress:{title:"印刷進捗",body:"{{printer}}: {{filename}} は {{percent}}% 完了"},printerOffline:{title:"プリンターオフライン",body:"{{printer}} がオフラインです"},printerError:{title:"プリンターエラー",body:"{{printer}}: {{error}}"},filamentLow:{title:"フィラメント残量低下",body:"{{printer}}: フィラメントが残りわずかです"},maintenanceDue:{title:"メンテナンス期限",body:"{{printer}}: {{items}} の対応が必要です"}},errors:{generic:"問題が発生しました",networkError:"ネットワークエラーです。接続を確認してください。",notFound:"見つかりません",unauthorized:"認証エラー",serverError:"サーバーエラー",validationError:"入力内容を確認してください",printerConnectionFailed:"プリンターへの接続に失敗しました",saveFailed:"保存に失敗しました",deleteFailed:"削除に失敗しました",loadFailed:"データの読み込みに失敗しました"},mqttDebug:{title:"MQTTデバッグログ",searchPlaceholder:"トピックまたはペイロードで検索...",noMessages:"まだメッセージが記録されていません",incoming:"受信",outgoing:"送信",loggingStopped:"ログ記録停止",loggingActive:"ログ記録中 - メッセージは自動更新されます",startLogging:"ログ記録を開始",topic:"トピック",startLoggingHint:"「ログ開始」をクリックしてMQTTメッセージのキャプチャを開始",noMessagesMatch:"フィルターに一致するメッセージがありません",adjustFilterHint:"検索条件やフィルター条件を調整してみてください",stopLogging:"ログ停止",clearLog:"ログをクリア",timestamp:"タイムスタンプ",direction:"方向",all:"すべて"},printerFiles:{filterPlaceholder:"ファイルを検索...",deleteFileConfirm:"このファイルを削除しますか?",noFiles:"このディレクトリにファイルがありません",loadingFiles:"ファイルを読み込み中...",failedToLoad:"ファイルの読み込みに失敗しました",title:"ファイル管理",storageUsed:"使用中:",storageFree:"空き:",deleteButton:"削除",deleteFiles:"{{count}}件のファイルを削除",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?元に戻せません。",toast:{filesDeleted:"{{count}}件のファイルを削除しました",deleteFailed:"削除に失敗: {{error}}"}},confirm:{delete:"削除しますか?",unsavedChanges:"保存されていない変更があります。このページを離れますか?",clearQueue:"キューをクリアしますか?"},login:{title:"Bambuddy ログイン",subtitle:"アカウントにサインイン",username:"ユーザー名",usernamePlaceholder:"ユーザー名を入力",password:"パスワード",passwordPlaceholder:"パスワードを入力",signIn:"サインイン",enterCredentials:"ユーザー名とパスワードを入力してください",signingIn:"ログイン中...",forgotPassword:"パスワードをお忘れですか?",loginSuccess:"ログインしました",loginFailed:"ログインに失敗しました",forgotPasswordTitle:"パスワードを忘れた場合",forgotPasswordMessage:"パスワードを忘れた場合は、システム管理者に連絡してリセットしてもらってください。",howToReset:"パスワードのリセット方法:",resetStep1:"Bambuddy管理者に連絡",resetStep2:"ユーザー管理でパスワードリセットを依頼",resetStep3:"管理者が新しい仮パスワードを設定",resetStep4:"新しいパスワードでログインし、設定で変更",gotIt:"了解",usernameOrEmail:"ユーザー名またはメール",usernameOrEmailPlaceholder:"ユーザー名または @ メール",forgotPasswordEmailMessage:"メールアドレスを入力すると、新しいパスワードを送信します。",emailAddress:"メールアドレス",emailPlaceholder:"your.email@example.com",cancel:"キャンセル",sending:"送信中...",sendResetEmail:"リセットメールを送信"},setup:{title:"Bambuddy セットアップ",adminAccount:"管理者アカウント",adminUsername:"管理者ユーザー名",adminPassword:"管理者パスワード",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",settingUp:"セットアップ中...",completeSetup:"セットアップを完了",toast:{authEnabledAdminCreated:"認証が有効になり、管理者ユーザーが作成されました",authEnabledExistingAdmins:"既存の管理者ユーザーを使用して認証が有効になりました",setupCompleted:"セットアップが完了しました",passwordsDoNotMatch:"パスワードが一致しません",enterBothCredentials:"管理者のユーザー名とパスワードの両方を入力するか、既存の管理者を使用する場合は両方を空にしてください",passwordTooShort:"パスワードは6文字以上必要です"},adminAccountDesc:"既に管理者ユーザーが存在する場合、既存の管理者アカウントを使用して認証が有効化されます。既存の管理者を使用する場合は下のフィールドを空のままにするか、新しい認証情報を入力して新しい管理者ユーザーを作成してください。",optionalIfAdminExists:"(管理者ユーザーが存在する場合は任意)",adminUsernamePlaceholder:"管理者ユーザー名を入力(任意)",adminPasswordPlaceholder:"管理者パスワードを入力(任意)",subtitle:"Bambuddyインスタンスの認証を設定",enableAuth:"認証を有効化"},changePassword:{currentPassword:"現在のパスワード",newPassword:"新しいパスワード",confirmPasswordPlaceholder:"パスワードを確認",title:"パスワードを変更",currentPasswordPlaceholder:"現在のパスワードを入力",newPasswordPlaceholder:"新しいパスワードを入力(6文字以上)",confirmPassword:"新しいパスワード確認",passwordsDoNotMatch:"パスワードが一致しません",passwordTooShort:"パスワードは6文字以上必要です",changing:"変更中...",success:"パスワードを変更しました",failed:"パスワードの変更に失敗しました"},camera:{invalidPrinterId:"無効なプリンターID",live:"ライブ",snapshot:"スナップショット",restartStream:"ストリームを再開",refreshSnapshot:"スナップショットを更新",fullscreen:"フルスクリーン",exitFullscreen:"フルスクリーンを終了",connectingToCamera:"カメラに接続中...",capturingSnapshot:"スナップショットを撮影中...",connectionLost:"接続が切断されました",reconnectNow:"今すぐ再接続",cameraUnavailable:"カメラが利用できません",retry:"再試行",cameraStream:"カメラストリーム",zoomOut:"ズームアウト",zoomIn:"ズームイン",resetZoom:"ズームをリセット",chamberLight:"チャンバーライト切替",title:"カメラビュー",connectionFailed:"カメラ接続に失敗しました",reconnecting:"{{countdown}}秒後に再接続... (試行 {{attempt}}/{{max}})",cameraUnavailableDesc:"プリンターの電源がオンで接続されていることを確認してください。",noCamera:"カメラがありません",recording:"録画中",startRecording:"録画開始",stopRecording:"録画停止"},groups:{backToSettings:"設定に戻る",createGroup:"グループを作成",noPermission:"このページにアクセスする権限がありません。",noDescription:"説明なし",usersCount:"{{count}}人のユーザー",permissionsCount:"{{count}}個の権限",toast:{deleted:"アーカイブを削除しました",enterGroupName:"グループ名を入力",created:"グループを作成しました",updated:"グループを更新しました"},modal:{editGroup:"グループを編集",createGroup:"グループを作成",cancel:"キャンセル",saving:"保存中...",creating:"作成中...",saveChanges:"変更を保存"},form:{groupName:"グループ名",permissions:"権限",groupNamePlaceholder:"グループ名を入力",systemGroupWarning:"システムグループ名は変更できません",description:"説明",descriptionPlaceholder:"説明を入力(任意)"},deleteModal:{confirm:"確認",title:"グループを削除",message:"このグループを削除しますか?このグループのユーザーはこれらの権限を失います。"},editor:{title:"グループを編集",createTitle:"グループを作成",search:"権限を検索...",selectAll:"すべて選択",clearAll:"すべて解除",permissionsSelected:"{{count}}件選択",noResults:"検索に一致する権限がありません"},title:"グループ管理",subtitle:"アクセス制御の権限グループを管理",system:"システム",edit:"編集",delete:"削除"},users:{title:"ユーザー管理",backToSettings:"設定に戻る",createUser:"ユーザーを作成",noPermission:"このページにアクセスする権限がありません。",admin:"管理者",noGroups:"グループなし",inactive:"非アクティブ",edit:"編集",delete:"削除",system:"システム",noGroupsAvailable:"利用可能なグループがありません",table:{username:"ユーザー名",groups:"グループ",status:"ステータス",actions:"アクション"},toast:{deleted:"アーカイブを削除しました",passwordsDoNotMatch:"パスワードが一致しません",created:"ユーザーを作成しました",updated:"ユーザーを更新しました",fillRequired:"必須項目をすべて入力してください",passwordTooShort:"パスワードは6文字以上必要です"},modal:{createUser:"ユーザーを作成",editUser:"ユーザーを編集",cancel:"キャンセル",creating:"作成中...",saving:"保存中...",saveChanges:"変更を保存",advancedAuthSubtitle:"高度な認証を使用"},form:{username:"ユーザー名",password:"パスワード",confirmPassword:"パスワードの確認",confirmPasswordPlaceholder:"パスワードを確認",confirmNewPasswordPlaceholder:"新しいパスワードを確認",leaveBlankToKeep:"(現在のパスワードを維持する場合は空白)",groups:"グループ",usernamePlaceholder:"ユーザー名を入力",passwordPlaceholder:"パスワードを入力",newPasswordPlaceholder:"新しいパスワードを入力",email:"メール",emailPlaceholder:"user@example.com",optional:"オプション",autoGeneratedPassword:"安全なパスワードが自動的に生成され、ユーザーにメールで送信されます。",passwordManagedByAdvancedAuth:"パスワードは高度な認証によって管理されています。「パスワードのリセット」を使用して、メールで新しいパスワードをユーザーに送信してください。",resetPassword:"パスワードのリセット",resettingPassword:"パスワードをリセット中..."},deleteModal:{title:"ユーザーを削除",confirm:"ユーザーを削除",message:"このユーザーを削除してもよろしいですか?この操作は元に戻せません。"},subtitle:"ユーザーとBambuddyインスタンスへのアクセスを管理",active:"アクティブ"},streamOverlay:{invalidPrinterId:"無効なプリンターID",cameraStream:"カメラストリーム",eta:"予想時間 {{minutes}} 分",status:{printing:"印刷中",paused:"一時停止",finished:"完了",failed:"失敗",idle:"待機中",unknown:"不明"},title:"ストリームオーバーレイ",progress:"進捗",printerIdle:"プリンター待機中",printerOffline:"プリンターオフライン"},profiles:{title:"フィラメントプロファイル",connectedAs:"接続中:",logout:"ログアウト",failedToLoad:"ファイルの読み込みに失敗しました",time:{justNow:"たった今",hoursAgo:"{{count}}時間前",daysAgo:"{{count}}日前",minsAgo:"{{count}}分前"},toast:{loggedOut:"ログアウトしました"},login:{title:"Bambuddy ログイン",subtitle:"アカウントにサインイン",email:"メールアドレス",password:"パスワード",region:"リージョン",regionGlobal:"グローバル",regionChina:"中国",verificationCode:"認証コード",totpCode:"認証アプリコード",checkEmail:"メール ({{email}}) に届いた6桁のコードを入力してください",enterTotpHint:"認証アプリの6桁のコードを入力してください",accessToken:"アクセストークン",accessTokenHint:"Bambu Labのアクセストークンを貼り付け(Bambu Studioから取得)",back:"戻る",toast:{loggedIn:"ログインしました",enterTotp:"認証アプリのコードを入力してください",tokenSet:"トークンを設定しました",codeSent:"メールに認証コードを送信しました"},loginButton:"ログイン",verifyButton:"認証",setTokenButton:"トークンを設定",useToken:"アクセストークンを使用",useEmail:"メールでログイン"},presets:{duplicate:"複製",editable:"編集可能",failedToLoadDetails:"プリセットの詳細を読み込めませんでした",deleteConfirm:"このプロファイルを削除しますか?",noDeletePermission:"プロジェクトを削除する権限がありません",types:{filament:"フィラメント",printer:"プリンター",process:"プロセス"},toast:{deleted:"アーカイブを削除しました",fieldAdded:'フィールド "{{key}}" を追加しました',created:"プリセットを作成しました",updated:"プリセットを更新しました",duplicated:"プリセットを複製しました",exported:"プリセットをエクスポートしました"},newPreset:"新規プリセット",editPreset:"プリセットを編集",duplicatePreset:"プリセットを複製",createNewPreset:"新しいプリセットを作成",customizeSettings:"新しいプリセットの設定をカスタマイズ",compareWithBase:"ベースプリセットと比較",compare:"比較",basePreset:"ベースプリセット",selectBasePreset:"ベースプリセットを選択...",presetName:"プリセット名",inheritsFrom:"継承元:",dropJsonToImport:"JSONファイルをドロップしてインポート",availableFields:"利用可能なフィールド",noMatchingFields:"一致するフィールドがありません",allFieldsAdded:"すべてのフィールドが追加済みです",addCustomField:"カスタムフィールドを追加",yourOverrides:"オーバーライド一覧",noOverridesYet:"オーバーライドはまだありません",clickFieldsToAdd:"左のフィールドをクリックして追加",saveAsTemplate:"テンプレートとして保存",myPreset:"マイプリセット(編集可能)",deleteWarning:"「{{name}}」をBambu Cloudから完全に削除します。元に戻せません。",noDuplicatePermission:"プリセットを複製する権限がありません",noEditPermission:"プリセットを編集する権限がありません",baseLabel:"ベース: {{name}}",currentLabel:"現在: {{name}}",myCustomPreset:"カスタムプリセット",tabs:{common:"一般",allFields:"すべてのフィールド"},searchFieldsPlaceholder:"フィールドを検索...",jsonTip:"ヒント: .jsonファイルをこのモーダルにドラッグ&ドロップして設定をインポート"},cloudView:{templates:"テンプレート",refresh:"更新",newPreset:"新規プリセット",clearFilters:"フィルターをクリア",compareMode:"比較モード",selectAnotherPreset:"同じタイプ({{type}})の別のプリセットを選択",clickTwoPresets:"同じタイプのプリセットを2つクリックして比較",selectFirst:"1. 最初を選択",selectSecond:"2. 2番目を選択",compareNow:"比較を実行",lastSynced:"最終同期:",showingCount:"{{total}}件中{{shown}}件を表示",noPresetsFound:"プリセットが見つかりません",columns:{filament:"フィラメント",process:"プロセス",printer:"プリンター"},noFilamentPresets:"フィラメントプリセットなし",noProcessPresets:"プロセスプリセットなし",noPrinterPresets:"プリンタープリセットなし",filters:{type:"種類",owner:"所有者",printer:"プリンター",nozzle:"ノズル",filament:"フィラメント",layer:"レイヤー",myPresets:"マイプリセット",builtIn:"ビルトイン",process:"プロセス",all:"すべて"},noCreatePermission:"プロジェクトを作成する権限がありません",searchPlaceholder:"プリセットを検索...",noTemplatesPermission:"テンプレートを管理する権限がありません",noRefreshPermission:"プロファイルを更新する権限がありません"},templates:{title:"フィラメントプロファイル",noTemplates:"テンプレートがありません。バックエンドを再起動してデフォルトテンプレートを作成してください。",typeFilter:"タイプ:",deleteConfirm:"このプロファイルを削除しますか?",settingsJson:"設定 (JSON)",fieldsCount:"{{count}}フィールド",shownInModals:"モーダルに表示",hiddenInModals:"モーダルで非表示",apply:"適用",toast:{deleted:"アーカイブを削除しました",updated:"テンプレートを更新しました",created:"テンプレートを作成しました",applied:"テンプレートを適用しました"},createFirst:"プリセットエディタからテンプレートを作成",deleteTitle:"テンプレートを削除",deleteWarning:"この操作は元に戻せません",namePlaceholder:"テンプレート名",descriptionPlaceholder:"説明"},subtitle:"スライサープリセットと圧力キャリブレーションの管理",tabs:{cloud:"クラウドプロファイル",local:"ローカルプロファイル",kprofiles:"Kプロファイル"},localProfiles:{title:"ローカルプロファイル",subtitle:"OrcaSlicerからスライサープリセットをインポート・管理",import:"プロファイルをインポート",importDesc:".bbscfg、.bbsflmt、.orca_filament、.zip、.jsonファイルをここにドロップ",importing:"インポート中...",search:"ローカルプリセットを検索...",noPresets:"ローカルプリセットがまだありません",badge:"ローカル",edit:"編集",delete:"削除",cancel:"キャンセル",deleteConfirmTitle:"プリセットを削除",deleteConfirm:"このプリセットを削除してもよろしいですか?元に戻せません。",source:"ソース",inheritsFrom:"継承元",filamentType:"タイプ",vendor:"メーカー",compatiblePrinters:"プリンター",nozzleTemp:"ノズル温度",cost:"コスト",density:"密度",pressureAdvance:"プレッシャーアドバンス",filament:"フィラメント",process:"プロセス",printer:"プリンター",toast:{importSuccess:"{{count}}件のプリセットをインポートしました",importSkipped:"{{count}}件のプリセットをスキップしました(重複)",importError:"インポート中に{{count}}件のエラーが発生しました",deleted:"プリセットを削除しました",updated:"プリセットを更新しました"}},noLogoutPermission:"ログアウトする権限がありません",retry:"リトライ"},fileManager:{uploadFiles:"ファイルをアップロード",newFolder:"新しいフォルダ",folderName:"フォルダ名",folderNamePlaceholder:"例: 機能パーツ",renameFile:"ファイル名を変更",renameFolder:"フォルダ名を変更",rootNoFolder:"ルート(フォルダなし)",current:"(現在)",linkFolder:"フォルダをリンク",linkFolderDescription:"「{{name}}」をプロジェクトまたはアーカイブにリンクしてすばやくアクセス。",noProjectsFound:"プロジェクトが見つかりません",noArchivesFound:"アーカイブが見つかりません",unlink:"リンク解除",link:"リンク",dropFilesHere:"ここにファイルをドロップ",orClickToBrowse:"またはクリックして選択",zipFilesDetected:"ZIPファイルを検出",preserveZipStructure:"ZIPのフォルダ構造を保持",willBeExtracted:"• 展開予定",filesExtracted:"• {{count}}個のファイルを展開済み",uploadComplete:"アップロード完了: {{count}}個成功",uploadFailed:"アップロード失敗",uploading:"アップロード中...",changeLink:"リンクを変更...",linkTo:"リンク先...",linkToProjectOrArchive:"プロジェクトまたはアーカイブにリンク",addToQueue:"キューに追加",schedulePrint:"印刷をスケジュール",gridView:"グリッド表示",listView:"リスト表示",lowDiskSpaceWarning:"ディスク容量不足の警告",folders:"フォルダ",size:"サイズ",free:"空き:",allFiles:"すべてのファイル",searchFiles:"ファイルを検索...",allTypes:"すべての種類",prints:"印刷回数",ascending:"昇順",descending:"降順",selectAll:"すべて選択",deselectAll:"すべて選択解除",selected:"{{count}}件選択中",adding:"追加中...",loadingFiles:"ファイルを読み込み中...",noFilesYet:"ファイルはまだありません",noMatchingFiles:"一致するファイルがありません",noMatchingFilesDescription:"現在の検索またはフィルター条件に一致するファイルがありません。",clearFilters:"フィルターをクリア",printedCount:"{{count}}回印刷済み",deleteFolder:"フォルダを削除",deleteFile:"ファイルを削除",deleteFolderConfirm:"このフォルダを削除しますか?中のファイルもすべて削除されます。",deleteFileConfirm:"このファイルを削除しますか?",deleting:"削除中...",toast:{folderCreated:"フォルダを作成しました",folderDeleted:"フォルダを削除しました",fileDeleted:"ファイルを削除しました",filesMoved:"ファイルを移動しました",folderLinked:"フォルダをリンクしました",folderUnlinked:"フォルダのリンクを解除しました",addedToQueue:"{{count}}個のファイルをキューに追加しました",fileRenamed:"ファイル名を変更しました",folderRenamed:"フォルダ名を変更しました",filesDeleted:"{{count}}件のファイルを削除しました",addedToQueuePartial:"{{added}}件追加、{{failed}}件失敗",failedToAddToQueue:"ファイルの追加に失敗: {{error}}",thumbnailsGenerated:"{{count}}件のサムネイルを生成しました",thumbnailsGeneratedPartial:"{{succeeded}}件生成、{{failed}}件失敗",noStlMissingThumbnails:"サムネイルのないSTLファイルはありません",failedToGenerateThumbnails:"サムネイルの生成に失敗: {{error}}",thumbnailGenerated:"サムネイルを生成しました",failedToGenerateThumbnail:"サムネイルの生成に失敗: {{error}}"},title:"ファイル管理",subtitle:"印刷ファイルの整理と管理",moveFiles:"{{count}}件のファイルを移動",project:"プロジェクト",archive:"アーカイブ",dragDropFiles:"ファイルをここにドラッグ&ドロップ",allFileTypesSupported:"すべてのファイルタイプに対応。ZIPファイルは展開されます。",zipExtractOptions:"ZIPファイルは展開されます。フォルダー構造の処理方法を選択:",createFolderFromZip:"ZIPファイル名からフォルダーを作成",stlThumbnailGeneration:"STLサムネイル生成",zipMayContainStl:"ZIPファイルにSTLファイルが含まれている場合があります。展開時にサムネイルを生成できます。",thumbnailsCanBeGenerated:"STLファイルのサムネイルを生成できます。大きなモデルは処理に時間がかかる場合があります。",generateThumbnailsForStl:"STLファイルのサムネイルを生成",threemfDetected:"3MFファイルを検出",threemfExtractionInfo:"プリンターモデル、素材、色、印刷設定は3MFファイルから自動的に抽出されます。",generateThumbnail:"サムネイルを生成",generateThumbnails:"サムネイルを生成",generateThumbnailsForMissing:"サムネイルのないSTLファイルのサムネイルを生成",lowDiskSpaceDetails:"{{total}}中{{free}}の空き容量のみ。しきい値は設定で{{threshold}}GBに設定されています。",files:"ファイル",wrap:"折り返し",enableTextWrapping:"テキスト折り返しを有効化",disableTextWrapping:"テキスト折り返しを無効化",dragToResizeTooltip:"ドラッグしてリサイズ、ダブルクリックでリセット",resultsCount:"{{total}}件中{{showing}}件",folderIsEmpty:"フォルダーは空です",folderEmptyDescription:"ファイルをアップロードするか、このフォルダーにファイルを移動して開始しましょう。",noFilesDescription:"印刷関連ファイルの整理を始めるにはファイルをアップロードしてください。",uploadedBy:"アップロード者",deleteFilesCount:"{{count}}件のファイルを削除",deleteFilesConfirm:"選択した{{count}}件のファイルを削除しますか?この操作は元に戻せません。",noPermissionRenameFolder:"フォルダー名を変更する権限がありません",noPermissionLinkFolder:"フォルダーをリンクする権限がありません",noPermissionDeleteFolder:"フォルダーを削除する権限がありません",noPermissionPrint:"印刷する権限がありません",noPermissionAddToQueue:"キューに追加する権限がありません",noPermissionDownload:"ファイルをダウンロードする権限がありません",noPermissionRenameFile:"このファイル名を変更する権限がありません",noPermissionGenerateThumbnail:"サムネイルを生成する権限がありません",noPermissionDeleteFile:"このファイルを削除する権限がありません",noPermissionCreateFolder:"フォルダーを作成する権限がありません",noPermissionUpload:"ファイルをアップロードする権限がありません",noPermissionMoveFiles:"ファイルを移動する権限がありません",noPermissionDeleteFiles:"ファイルを削除する権限がありません"},projects:{title:"プロジェクト",subtitle:"印刷プロジェクトを管理",newProject:"新規プロジェクト",editProject:"プロジェクトを編集",deleteProject:"プロジェクトを削除",projectName:"プロジェクト: {{name}}",create:"作成",plates:"プレート",parts:"パーツ",viewDetails:"詳細を表示",namePlaceholder:"プロジェクト名",descriptionPlaceholder:"プロジェクトの説明(任意)",color:"色",targetPlates:"目標プレート数",targetPlatesPlaceholder:"例: 10",targetParts:"目標パーツ数",targetPartsPlaceholder:"例: 50",tagsPlaceholder:"カンマ区切りのタグ",dueDate:"期限",priorityLow:"低",priorityNormal:"通常",priorityHigh:"高",priorityUrgent:"緊急",statusArchived:"アーカイブ済み",done:"完了",completed:"完了",failed:"失敗",inQueue:"キュー内",noPrintsYet:"印刷履歴なし",printJobs:"印刷ジョブ",partsPrinted:"印刷済みパーツ",failedParts:"失敗パーツ",import:"インポート",importProject:"プロジェクトをインポート",loading:"プロジェクトを読み込み中...",noEditPermission:"プロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",noCreatePermission:"プロジェクトを作成する権限がありません",noImportPermission:"プロジェクトをインポートする権限がありません",noExportPermission:"プロジェクトをエクスポートする権限がありません",toast:{deleted:"アーカイブを削除しました",importFailed:"インポートに失敗しました",created:"プロジェクトを作成しました",updated:"プロジェクトを更新しました",imported:"プロジェクトをインポートしました",multipleImported:"{{count}}件のプロジェクトをインポートしました",exported:"プロジェクトをエクスポートしました(メタデータのみ)"},description:"説明",noProjects:"プロジェクトはまだありません",noProjectsFiltered:"{{status}}のプロジェクトはありません",noProjectsFilteredHelp:"{{status}}のプロジェクトがありません。ステータスが変更されるとここに表示されます。",createFirst:"最初のプロジェクトを作成して、関連する印刷の整理、進捗管理、ビルドの管理を始めましょう。",createFirstButton:"最初のプロジェクトを作成",files:"ファイル",prints:"印刷",lastModified:"最終更新日",deleteConfirm:"このプロジェクトを削除しますか?アーカイブとキューアイテムはリンク解除されますが、削除されません。",addFiles:"ファイルを追加",removeFile:"ファイルを削除",targetPlatesHelp:"印刷ジョブの数",targetPartsHelp:"必要なオブジェクトの総数",tagsLabel:"タグ(カンマ区切り)",priority:"優先度",statusActive:"進行中",statusCompleted:"完了",export:"エクスポート",exportAll:"すべてのプロジェクトをエクスポート"},projectDetail:{notFound:"見つかりません",backToProjects:"プロジェクト一覧に戻る",exportProject:"プロジェクトをエクスポート",noExportPermission:"プロジェクトをエクスポートする権限がありません",noEditPermission:"このプロジェクトを編集する権限がありません",partOf:"所属先",priorityLabel:"優先度",status:{active:"進行中",completed:"完了",archived:"アーカイブ済み"},priority:{low:"低",normal:"通常",high:"高",urgent:"緊急"},dueDate:{overdue:"期限超過",daysLeft:"残り{{count}}日",today:"今日が期限"},progress:{platesProgress:"プレート進捗",partsProgress:"パーツ進捗",printJobs:"印刷ジョブ",parts:"パーツ",percentComplete:"% 完了",remaining:"残り"},stats:{printJobs:"印刷ジョブ",total:"合計",failed:"失敗",partsPrinted:"印刷済みパーツ",printTime:"印刷時間",filamentUsed:"フィラメント使用量"},cost:{filamentCost:"フィラメント",energy:"エネルギー",budget:"予算",remaining:"残り",title:"コスト追跡"},notes:{noEditPermission:"このプロジェクトを編集する権限がありません",empty:"<空>",title:"メモ",placeholder:"このプロジェクトについてメモを追加..."},files:{fileCount:"{{count}}ファイル",empty:"<空>",title:"ファイル",linkFolders:"ファイルマネージャーからフォルダーをリンク",forQuickAccess:"してクイックアクセスできるようにします。"},bom:{showAll:"すべて表示",hideDone:"完了を非表示",addPart:"パーツを追加",partNamePlaceholder:"パーツ名",qty:"数量",sourcingUrlPlaceholder:"URL(任意)",remarksPlaceholder:"備考",deletePart:"パーツを削除",noEditPermission:"このプロジェクトを編集する権限がありません",noDeletePermission:"プロジェクトを削除する権限がありません",totalCost:"合計コスト",empty:"<空>",title:"部品表",acquired:"{{completed}}/{{total}} 取得済み",noAddPermission:"パーツを追加する権限がありません",partName:"パーツ名",price:"価格 ({{currency}})",deleteConfirm:"「{{name}}」を削除しますか?",noUpdatePermission:"パーツを更新する権限がありません"},timeline:{empty:"<空>",title:"アクティビティタイムライン"},template:{saveAsTemplate:"テンプレートとして保存",noCreatePermission:"プロジェクトを作成する権限がありません"},queue:{title:"印刷キュー",viewAll:"すべて表示",printing:"印刷中",queued:"キューに追加"},toast:{projectUpdated:"プロジェクトを更新しました",partAdded:"パーツを追加しました",partRemoved:"パーツを削除しました",exportFailed:"エクスポートに失敗しました",projectExported:"プロジェクトがエクスポートされました",templateCreated:"プロジェクトからテンプレートを作成しました"},export:"エクスポート",noPrints:"このプロジェクトにはまだ印刷がありません",subProjects:{title:"サブプロジェクト ({{count}})"},prints:{title:"印刷 ({{count}})"}},system:{clearLogs:"通知ログを削除",title:"システム情報",version:"バージョン",uptime:"稼働時間",cpuUsage:"CPU使用率",memoryUsage:"メモリ使用量",diskUsage:"ディスク使用量",networkInfo:"ネットワーク情報",logs:"ログ",debugMode:"デバッグモード",enableDebug:"デバッグログを有効化",disableDebug:"デバッグログを無効化",downloadLogs:"ログをダウンロード",dockerInfo:"Docker情報",containerName:"コンテナ名",imageName:"イメージ名",platform:"プラットフォーム",architecture:"アーキテクチャ"},library:{material:"素材",temperature:"温度",title:"フィラメントライブラリ",addFilament:"フィラメントを追加",editFilament:"フィラメントを編集",deleteFilament:"フィラメントを削除",vendor:"メーカー",color:"色",kFactor:"K値",noFilaments:"ライブラリにフィラメントがありません",deleteConfirm:"このフィラメントを削除しますか?",importFromPrinter:"プリンターからインポート",exportToFile:"ファイルにエクスポート"},spoolman:{title:"Spoolman連携",url:"Spoolman URL",connected:"接続中",disconnected:"未接続",sync:"同期",linkToSpoolman:"Spoolmanに連携",noUnlinkedSpools:"Spoolmanに未連携のスプールが見つかりません。",fillSourceLabel:"(Spoolman)",remaining:"残り",disableWeightSync:"AMS推定重量同期を無効化",disableWeightSyncDesc:"AMS推定値から残量を更新しません。AMSの割合ベースの推定よりもSpoolmanの使用量追跡を優先する場合に使用してください。新しいスプールは引き続きAMS推定値を初期重量として使用します。",reportPartialUsage:"失敗した印刷の部分使用量を報告",reportPartialUsageDesc:"印刷が失敗またはキャンセルされた場合、レイヤー進捗に基づいてその時点までの推定フィラメント使用量を報告します。",testConnection:"接続テスト",syncing:"同期中...",lastSync:"最終同期",unlinkSpool:"スプールのリンクを解除",weight:"重量",enabled:"Spoolman有効",openInSpoolman:"Spoolmanで開く",selectSpool:"スプールを選択",linkSuccess:"スプールをSpoolmanにリンクしました",linkFailed:"スプールのリンクに失敗しました",spoolId:"スプールID"},inventory:{title:"スプール在庫管理",addSpool:"スプールを追加",editSpool:"スプールを編集",material:"素材",selectMaterial:"素材を選択...",subtype:"サブタイプ",brand:"ブランド",searchBrand:"ブランドを検索...",useCustomBrand:"「{{brand}}」を使用",useCustomMaterial:"カスタム素材を使用: {{material}}",colorName:"色名",colorNamePlaceholder:"Jade White, Fire Red...",color:"色",hexColor:"HEXカラー",pickColor:"カスタムカラーを選択",labelWeight:"表示重量",coreWeight:"空スプール重量",searchSpoolWeight:"スプール重量を検索...",weightUsed:"使用量",currentWeight:"残量",measuredWeight:"計測重量",costPerKg:"kgあたりのコスト",measuredWeightError:"計測重量は{{min}}gから{{max}}gの間で入力してください。",slicerFilament:"スライサーフィラメント",slicerFilamentName:"スライサープリセット名",slicerPreset:"スライサープリセット",searchPresets:"フィラメントプリセットを検索...",selectedPreset:"選択済み",noPresetsFound:"プリセットが見つかりません",tempOverrides:"温度オーバーライド",note:"メモ",notePlaceholder:"このスプールに関する追加メモ...",archive:"アーカイブ",restore:"復元",noSpools:"スプールがありません。最初のスプールを追加してください。",noManualSpools:"手動で追加されたスプールがありません。先にインベントリにスプールを追加してください。",kProfiles:"Kプロファイル",addKProfile:"Kプロファイルを追加",assignSpool:"スプールを割り当て",unassignSpool:"割り当て解除",assignSuccess:"スプールを割り当て、AMSスロットを設定しました",assignFailed:"スプールの割り当てに失敗しました",selectSpool:"このスロットに割り当てるスプールを選択",assigned:"割り当て済み",assigning:"割り当て中...",searchSpools:"スプールを検索...",allMaterials:"すべての素材",filterByBrand:"ブランドで絞り込み...",showArchived:"アーカイブ済みを表示",quickAdd:"クイック追加(在庫)",quantity:"数量",stock:"在庫",configured:"設定済み",spoolsCreated:"{{count}}本のスプールを作成しました",spoolCreated:"スプールを作成しました",spoolUpdated:"スプールを更新しました",spoolDeleted:"スプールを削除しました",spoolArchived:"スプールをアーカイブしました",spoolRestored:"スプールを復元しました",deleteConfirm:"このスプールを削除しますか?この操作は元に戻せません。",archiveConfirm:"このスプールをアーカイブしますか?",advancedSettings:"詳細設定",filamentInfoTab:"フィラメント情報",paProfileTab:"PAプロファイル",filamentInfo:"フィラメント",additional:"追加情報",loadingPresets:"クラウドプリセットを読み込み中...",cloudConnected:"クラウド接続済み",cloudNotConnected:"クラウド未接続(デフォルト使用)",recentColors:"最近",searchColors:"色を検索...",searchResults:"検索結果",allColors:"すべての色",commonColors:"一般的な色",showLess:"少なく表示",showAll:"すべて表示",noColorsFound:"一致する色がありません",noResults:"結果なし",selectMaterialFirst:"フィラメント情報タブで素材を選択してください。",noPrintersConfigured:"プリンターが設定されていません。プリンターを追加してください。",matchingFilter:"フィルター",anyBrand:"すべてのブランド",anyVariant:"すべてのバリアント",autoSelect:"自動選択",matches:"件一致",match:"件一致",noMatches:"一致なし",connected:"接続済み",offline:"オフライン",printerOffline:"プリンターがオフラインです。接続してキャリブレーションプロファイルを表示してください。",noKProfilesMatch:"選択したフィラメントに一致するKプロファイルがありません。",leftNozzle:"左ノズル",rightNozzle:"右ノズル",profilesSelected:"キャリブレーションプロファイル選択済み",totalInventory:"在庫合計",totalConsumed:"総消費量",byMaterial:"素材別",inPrinter:"プリンター内",lowStock:"残量少",sinceTracking:"追跡開始以降",loadedInAms:"AMS/Extに装填中",remaining:"残り",lowStockThreshold:"残り20%未満",search:"スプールを検索...",showing:"表示",to:"〜",of:"/",show:"表示",spools:"スプール",spool:"スプール",page:"ページ",noSpoolsMatch:"結果なし",noSpoolsMatchDesc:"検索やフィルターを調整してみてください。",active:"アクティブ",archived:"アーカイブ済み",all:"すべて",used:"使用済み",new:"新規",clearFilters:"フィルターをクリア",table:"テーブル",cards:"カード",net:"正味",groupSimilar:"グループ化",groupedSpools:"{{count}}本の同一スプール",groupedRows:"行",columns:"列",configureColumns:"列の設定",configureColumnsDesc:"ドラッグして並べ替えるか、矢印を使用してください。目のアイコンで表示/非表示を切り替えます。",visible:"表示中",reset:"リセット",cancel:"キャンセル",applyChanges:"変更を適用",moveUp:"上へ移動",moveDown:"下へ移動",hideColumn:"列を非表示",showColumn:"列を表示",linkToSpool:"スプールにリンク",tagLinked:"タグがスプールにリンクされました",tagLinkFailed:"タグのリンクに失敗しました",tagAlreadyLinked:"タグは既に別のスプールにリンクされています",unknownTag:"不明なRFIDタグが検出されました",usageHistory:"使用履歴",noUsageHistory:"まだ使用記録がありません",printName:"プリント名",weightConsumed:"消費重量",clearHistory:"クリア",historyCleared:"使用履歴がクリアされました",fillSourceLabel:"(Inv)"},timelapse:{download:"ダウンロード",preview:"プレビュー",processing:"バックアップファイルを処理中...",title:"タイムラプス",create:"タイムラプスを作成",delete:"削除",frameRate:"フレームレート",quality:"品質",noTimelapses:"利用可能なタイムラプスがありません"},ams:{empty:"<空>",humidity:"湿度",temperature:"温度",remaining:"残り",noHistory:"メンテナンス履歴がありません",configureSlot:"フィラメントプロファイルとK値でスロットを設定",externalSpool:"外部スプール",title:"AMS",slot:"スロット",emptySlot:"空のスロット",unknown:"不明",filamentType:"フィラメントタイプ",filamentColor:"色",history:"AMS履歴",profile:"プロファイル",kFactor:"K値",fill:"充填率",configure:"設定",used:"使用済み",remainingUnit:"残り"},printModal:{flowCalibration:"フローキャリブレーション",vibrationCalibration:"振動キャリブレーション",startPrint:"印刷を開始",noPrintersAvailable:"利用可能なプリンターがありません",title:"印刷を開始",selectPrinter:"プリンターを選択",selectPlate:"プレートを選択",filamentMapping:"フィラメントマッピング",totalCost:"合計コスト:",printSettings:"印刷設定",bedLeveling:"ベッドレベリング",layerInspection:"第一層検査",timelapse:"タイムラプス",addToQueue:"キューに追加",printerBusy:"プリンターは使用中です",printerOffline:"プリンターはオフラインです",cancel:"キャンセル",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"左ノズル",rightNozzleTooltip:"右ノズル",filamentOverride:"フィラメントオーバーライド",filamentOverrideHint:"モデルベースの割り当てに使用するフィラメントをオプションで上書きします。スケジューラは元の3MF値ではなく、選択したフィラメントに基づいてマッチングします。",originalFilament:"オリジナル",overrideWith:"変更先",resetToOriginal:"オリジナルに戻す"},backup:{restoreBackup:"バックアップの復元",restoreDescription:"バックアップファイルからすべてのデータを置き換える",lastBackup:"最終バックアップ",autoBackup:"自動バックアップ",backupNow:"今すぐバックアップ",backupFailed:"バックアップに失敗しました: {{error}}",restoreNote:"復元中、仮想プリンターは停止されます",downloadBackup:"バックアップをダウンロード",uploadBackup:"バックアップをアップロード",restoreWarning:"警告: バックアップの復元は現在のすべてのデータを上書きします。",includeArchives:"アーカイブを含む",includeSettings:"設定を含む",includeProfiles:"プロファイルを含む",backupSuccess:"バックアップを作成しました",restoreSuccess:"バックアップを復元しました",restoreFailed:"復元に失敗しました",title:"バックアップと復元",createBackup:"バックアップを作成"},uploadModal:{title:"3MFファイルのアップロード",dragDrop:".3mfファイルをここにドラッグ&ドロップ",or:"または",browseFiles:"ファイルを参照",uploaded:"アップロード済み",failed:"アップロードに失敗しました",uploading:"アップロード中...",upload:"アップロード",uploadFailed:"アップロード失敗",extractionInfo:"プリンターモデルは3MFファイルのメタデータから自動的に抽出されます。"},editArchive:{title:"アーカイブを編集",name:"名前",printer:"プリンター",noPrinter:"プリンターなし",project:"プロジェクト",noProject:"プロジェクトなし",itemsPrinted:"印刷数",notes:"メモ",notesPlaceholder:"この印刷についてメモを追加...",externalLink:"外部リンク",externalLinkPlaceholder:"https://...",tags:"タグ",addMoreTags:"タグをさらに追加...",status:"ステータス",failureReason:"失敗理由",selectReason:"理由を選択...",photos:"印刷結果の写真",printResult:"印刷結果",saving:"保存中...",failureReasons:{adhesionFailure:"定着不良",spaghettiDetached:"スパゲッティ / 剥離",layerShift:"レイヤーシフト",cloggedNozzle:"ノズル詰まり",filamentRunout:"フィラメント切れ",warping:"反り",stringing:"糸引き",underExtrusion:"押出不足",powerFailure:"電源障害",userCancelled:"ユーザーによるキャンセル",other:"その他"},itemsPrintedHelp:"この印刷ジョブで製造したアイテム数",externalLinkHelp:"Printables、Thingiverse、その他のソースへのリンク",matchingTags:'"{{query}}" に一致',existingTags:"既存のタグ",clickToAdd:"(クリックして追加)",photosHelp:"+ をクリックして印刷結果の写真を追加",namePlaceholder:"印刷名",tagsPlaceholder:"タグを追加...",statuses:{completed:"完了",failed:"失敗",aborted:"キャンセル",printing:"印刷中"}},kProfiles:{noPrintersConfigured:"プリンターが設定されていません",noActivePrinters:"アクティブなプリンターがありません",loadingProfiles:"Kプロファイルを読み込み中...",printerOffline:"プリンターオフライン",noMatchingProfiles:"一致するプロファイルなし",noKProfiles:"Kプロファイルなし",createFirstProfile:"最初のプロファイルを作成",nozzle:"ノズル",refresh:"更新",addProfile:"K-プロファイルを追加",import:"インポート",select:"選択",selectAll:"すべて選択",searchPlaceholder:"名前またはフィラメントで検索...",allExtruders:"すべてのエクストルーダー",leftOnly:"左のみ",rightOnly:"右のみ",allFlow:"すべてのフロー",hfOnly:"HFのみ",sOnly:"Sのみ",sortName:"ソート: 名前",sortKValue:"ソート: K値",sortFilament:"ソート: フィラメント",leftExtruder:"左エクストルーダー",rightExtruder:"右エクストルーダー",modal:{profileName:"プロファイル名",profileNamePlaceholder:"マイPLAプロファイル",kValue:"K値",filament:"フィラメント",selectFilament:"フィラメントを選択...",flowType:"フロータイプ",highFlow:"ハイフロー",standard:"スタンダード",nozzleSize:"ノズルサイズ",extruder:"エクストルーダー",extruders:"エクストルーダー",left:"左",right:"右",notesPlaceholder:"このプロファイルのメモを追加...",pleaseWait:"お待ちください",addTitle:"Kプロファイルを追加",editTitle:"Kプロファイルを編集",kValuePlaceholder:"0.020",kValueHelp:"一般的な範囲: PLA 0.01〜0.06、PETG 0.02〜0.10",noFilamentsHelp:"フィラメントが見つかりません。Bambu Studioでまずプロファイルを作成してください。",notes:"メモ(ローカル保存)",notesHelp:"メモはBambuddyに保存され、プリンターには保存されません",syncing:"プリンターと同期中...",savingExtruder:"エクストルーダーに保存中 {{current}}/{{total}}..."},toast:{profileSaved:"Kプロファイルを保存しました",profileDeleted:"Kプロファイルを削除しました",exportedProfiles:"{{count}}件のプロファイルをエクスポートしました",importedProfiles:"{{total}}件中{{imported}}件のプロファイルをインポートしました",noProfilesToExport:"エクスポートするプロファイルがありません",invalidFileFormat:"無効なファイル形式",failedToParseImport:"インポートファイルの解析に失敗しました",failedToSaveNote:"メモの保存に失敗しました",profilesSaved:"Kプロファイルを{{count}}台のエクストルーダーに保存しました",selectAtLeastOneExtruder:"エクストルーダーを1つ以上選択してください",profilesDeleted:"{{count}}件のプロファイルを削除しました",failedToSaveBatch:"Kプロファイルの保存に失敗しました",noteSaved:"メモを保存しました"},title:"Kプロファイル",addPrinterInSettings:"Kプロファイルを管理するには設定でプリンターを追加してください",enablePrinterConnection:"Kプロファイルを表示するにはプリンター接続を有効にしてください",printerOfflineDesc:"選択したプリンターは接続されていません。電源を入れてKプロファイルを表示してください。",noMatchingProfilesDesc:"検索条件に一致するプロファイルがありません",noKProfilesDesc:"{{diameter}}mmノズル用の圧力キャリブレーションプロファイルが見つかりません",printer:"プリンター",export:"エクスポート",delete:"削除",deleteConfirm:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"「{{name}}」をプリンターから削除しますか?"},bulkDelete:{title:"プロファイルを削除",cannotUndo:"元に戻せません",message:"選択した{{count}}件のプロファイルをプリンターから削除しますか?"},permission:{noRead:"プロファイルを更新する権限がありません",noCreate:"プロファイルを追加する権限がありません",noUpdate:"Kプロファイルを更新する権限がありません",noDelete:"Kプロファイルを削除する権限がありません",noExport:"プロファイルをエクスポートする権限がありません",noImport:"プロファイルをインポートする権限がありません"}},virtualPrinter:{running:"稼働中",enable:{visibleInSlicer:"スライサーの検出リストに「Bambuddy」として表示",proxyingTo:"{{name}}にプロキシ中",notActive:"非アクティブ",title:"仮想プリンターを有効化"},remoteInterface:{optional:"オプション — 自動検出IPが間違っている場合に使用(複数NIC、Docker、VPNなど)",title:"ネットワークインターフェース上書き",configured:"インターフェース上書き有効",placeholder:"自動検出(デフォルト)...",hint:"SSDPで広告され、TLS証明書に使用されるIPアドレスを上書きします。Bambuddyに複数のネットワークインターフェースがある場合に便利です。"},howItWorks:{title:"仕組み",step1:"同じLAN上では、仮想プリンターはスライサー(Bambu Studio / OrcaSlicer)に自動的に表示されます。他のネットワークからは、IPアドレスとアクセスコードで手動で追加してください。",step2:"アーカイブ、レビュー、キューモードでは、スライサーの「送信」ボタンを使用して3MFファイルをBambuddyにアップロードします。スライサーは「印刷成功」と表示しますが、ファイルは保存され、印刷はされません。",step3:"プロキシモードでは、仮想プリンターはすべてのトラフィックを実際のプリンターに転送します。直接接続されているかのように印刷がすぐに開始されます。"},status:{mode:"モード",pendingFiles:"保留中のファイル",ftpPort:"FTPポート",mqttPort:"MQTTポート",ftpConnections:"FTP接続数",mqttConnections:"MQTT接続数",title:"ステータス詳細",printerName:"プリンター名",model:"モデル",serialNumber:"シリアル番号",targetPrinter:"ターゲットプリンター"},toast:{accessCodeRequired:"先にアクセスコードを設定してください",targetPrinterRequired:"先にターゲットプリンターを選択してください",bindIpRequired:"先にバインドIPを設定してください",accessCodeEmpty:"アクセスコードは空にできません",accessCodeLength:"アクセスコードは8文字である必要があります",updated:"仮想プリンター設定を更新しました",failedToUpdate:"設定の更新に失敗しました",created:"仮想プリンターを作成しました",failedToCreate:"仮想プリンターの作成に失敗しました",deleted:"仮想プリンターを削除しました",failedToDelete:"仮想プリンターの削除に失敗しました"},list:{title:"仮想プリンター",add:"追加",addFirst:"仮想プリンターを追加",empty:"仮想プリンターが設定されていません。追加して始めましょう。"},bindIp:{title:"バインドインターフェース",placeholder:"インターフェースを選択...",hint:"この仮想プリンターがバインドするネットワークインターフェース。プリンターごとに一意である必要があります。"},proxy:{accessCodeHint:"プロキシモードでは、スライサーにターゲットプリンターのアクセスコードを使用してください。接続は実際のプリンターに透過的に転送されます。"},addDialog:{title:"仮想プリンターを追加",name:"名前",hint:"アクセスコード、ターゲットプリンター、その他の設定は作成後に設定できます。",create:"作成"},deleteConfirm:{title:"仮想プリンターを削除",message:"「{{name}}」を削除してもよろしいですか?このプリンターのすべてのサービスが停止されます。"},title:"仮想プリンター",stopped:"停止",description:{default:"Bambu StudioとOrcaSlicerに表示される仮想プリンターを有効化。このプリンターに送信されたファイルは印刷せずに直接アーカイブされます。",proxy:"スライサーのトラフィックを実際のプリンターに転送するプロキシを有効化。任意のネットワーク経由でリモート印刷が可能です。"},model:{title:"プリンターモデル",description:"エミュレートするプリンターモデルを選択。",restartWarning:"モデルを変更すると仮想プリンターが再起動されます"},accessCode:{title:"アクセスコード",isSet:"アクセスコードが設定されています",notSet:"アクセスコード未設定 - 有効化に必要です",placeholder:"8文字のコードを入力",placeholderChange:"新しいコードを入力して変更",hint:"正確に8文字必要です。スライサーの認証に使用されます。",charCount:"({{count}}/8)"},targetPrinter:{title:"ターゲットプリンター",configured:"プロキシターゲット設定済み",notConfigured:"ターゲットプリンター未選択 - プロキシモードに必要です",placeholder:"プリンターを選択...",hint:"スライサートラフィックの転送先プリンターを選択。プリンターはLANモードである必要があります。",noPrinters:"プリンターが設定されていません。プロキシモードを使用するにはまずプリンターを追加してください。"},mode:{title:"モード",archive:"アーカイブ",archiveDesc:"ファイルを即座にアーカイブ",review:"レビュー",reviewDesc:"アーカイブ前にレビュー",queue:"キュー",queueDesc:"アーカイブしてキューに追加",proxy:"プロキシ",proxyDesc:"実際のプリンターに転送"},setupRequired:{title:"セットアップが必要です",description:"仮想プリンター機能を使用するには追加のシステム設定が必要です。ポートフォワーディング、ファイアウォールルール、プラットフォーム固有の設定が含まれます。",readGuide:"有効にする前にセットアップガイドをお読みください"}},modelViewer:{openInSlicer:"スライサーで開く",tabs:{model:"3Dモデル",gcode:"G-codeプレビュー"},notAvailable:"利用不可",notSliced:"未スライス",plates:"プレート",allPlates:"全プレート",plateNumber:"プレート {{number}}",plateCount:"{{count}} プレート",plateCount_other:"{{count}} プレート",objectCount:"{{count}} オブジェクト",objectCount_other:"{{count}} オブジェクト",filamentCount:"{{count}} フィラメント",filamentCount_other:"{{count}} フィラメント",eta:"予想時間 {{minutes}} 分",noPreview:"このファイルのプレビューは利用できません",pagination:{pageOf:"ページ {{current}} / {{total}}",prev:"前へ",next:"次へ"},errors:{failedToLoad:"ファイルの読み込みに失敗しました",noMeshes:"3MFファイルにメッシュが見つかりません",unsupportedFormat:"サポートされていないファイル形式です"}},maintenanceDescriptions:{lubricateCarbonRods:"カーボンロッドに潤滑剤を塗布してスムーズな動きを確保",lubricateRails:"リニアレールの潤滑",cleanNozzle:"ノズル/ホットエンドの清掃",checkBelts:"ベルト張力の確認",cleanBuildPlate:"ビルドプレートの清掃",checkExtruder:"エクストルーダーギアの確認",checkCooling:"冷却ファンの確認",generalInspection:"総合点検",cleanCarbonRods:"カーボンロッドの清掃",cleanLinearRails:"リニアレールを拭いてほこりや汚れを除去",checkPtfeTube:"PTFEチューブの確認",replaceHepaFilter:"HEPAフィルター交換",replaceCarbonFilter:"カーボンフィルター交換",lubricateLeftNozzleRail:"左ノズルレールの潤滑"},hmsErrors:{title:"エラー - {{name}}",noErrors:"エラーなし",viewOnWiki:"Bambu Lab Wikiで表示",clearInstructions:"プリンターでエラーをクリアするとここからも消えます。",clearErrors:"エラーをクリア",clearSuccess:"HMSエラーをクリアしました",clearFailed:"HMSエラーのクリアに失敗しました"},plateAlert:{title:"印刷が一時停止されました!",message:"ビルドプレート上にオブジェクトが検出されました。印刷が自動的に一時停止されました。プレートをクリアして印刷を再開してください。",understand:"了解"},tags:{title:"タグ",addTag:"タグを追加",editTag:"タグを編集",deleteTag:"タグを削除",tagName:"タグ名",tagColor:"タグの色",noTags:"タグがありません",deleteConfirm:"このタグを削除しますか?",manageTags:"タグを管理"},support:{debugLoggingActive:"デバッグログが有効です",manageLogs:"管理",collectItem7:"プリンター接続状態とファームウェアバージョン",collectItem8:"連携状態(Spoolman、MQTT、HA)",collectItem9:"ネットワークインターフェース(サブネットのみ)",collectItem10:"Pythonパッケージバージョン",collectItem11:"データベース健全性チェック",collectItem12:"Docker環境の詳細"},configureAmsSlot:{title:"AMSスロットの設定",slotConfigured:"スロットを設定しました!",configuringSlot:"スロットを設定中:",slotLabel:"{{ams}} スロット {{slot}}",searchPresets:"プリセットを検索...",colorPlaceholder:"色名またはHex(例: 茶色、FF8800)",clearCustomColor:"カスタム色をクリア",noCloudPresets:"クラウドプリセットがありません。Bambu Cloudにログインして同期してください。",noPresetsAvailable:"プリセットがありません。Bambu Cloudにログインするか、ローカルプロファイルをインポートしてください。",noMatchingPresets:"一致するプリセットが見つかりません。",custom:"カスタム",builtin:"内蔵",settingsSentToPrinter:"設定をプリンターに送信しました",filamentProfile:"フィラメントプロファイル",kProfileLabel:"Kプロファイル(Pressure Advance)",filteringFor:"フィルター中: {{material}}",noKProfile:"Kプロファイルなし(デフォルト0.020を使用)",noMatchingKProfiles:"一致するKプロファイルが見つかりません。デフォルトK=0.020が使用されます。",selectFilamentFirst:"まずフィラメントプロファイルを選択してください",kFromCalibration:"K={{value}}(プリンターキャリブレーションから)",customColorLabel:"カスタム色(オプション)",presetColors:"{{name}}の色:",showLessColors:"色を減らす",showMoreColors:"色をもっと表示",clear:"クリア",hexLabel:"Hex: #{{hex}}",resetting:"リセット中...",resetSlot:"スロットをリセット",cancel:"キャンセル",configuring:"設定中...",configureSlot:"スロットを設定"},emailSettings:{placeholders:{fromName:"BamBuddy"}},smartPlugs:{offline:"オフライン",admin:"管理",openPlugAdminPage:"プラグ管理ページを開く",deleteSmartPlug:"スマートプラグを削除",turnOnSmartPlug:"スマートプラグをオンにする",turnOffSmartPlug:"スマートプラグをオフにする",turnOn:"オンにする",turnOff:"オフにする",addSmartPlug:{scanningNetwork:"ネットワークをスキャン中...",chooseEntity:"エンティティを選択...",connectionFailed:"接続失敗",searchEntities:"エンティティを検索...",searchPowerSensors:"電力センサーを検索...",searchEnergySensors:"エネルギーセンサーを検索...",placeholders:{plugName:"リビングルームプラグ",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"電力トピックと同じ、または異なる"}}},externalLinks:{noLinksConfigured:"外部リンクが設定されていません",deleteLink:"リンクを削除",removeCustomIcon:"カスタムアイコンを削除",openInNewTab:"新しいタブで開く",placeholders:{linkName:"マイリンク"}},keyboardShortcuts:{title:"キーボードショートカット",navigation:"ナビゲーション",archivesSection:"アーカイブ",kProfilesSection:"Kプロファイル",generalSection:"全般",shortcuts:{goToPrinters:"プリンターへ移動",goToArchives:"アーカイブへ移動",goToQueue:"キューへ移動",goToStats:"統計へ移動",goToProfiles:"クラウドプロファイルへ移動",goToSettings:"設定へ移動",focusSearch:"検索にフォーカス",openUploadModal:"アップロードモーダルを開く",clearSelection:"選択をクリア / 入力をぼかす",contextMenu:"カードのコンテキストメニュー",refreshProfiles:"プロファイルを更新",newProfile:"新しいプロファイル",exitSelectionMode:"選択モードを終了",showHelp:"このヘルプを表示"},footer:"Escキーを押すか外側をクリックして閉じます"},restoreBackup:{title:"バックアップを復元",restoring:"復元中...",restoreComplete:"復元完了",restoreFailed:"復元失敗",importSettings:"バックアップファイルから設定をインポート",pleaseWait:"データの復元中です。しばらくお待ちください",clickToSelect:"クリックしてバックアップファイルを選択(.jsonまたは.zip)",howDuplicateHandling:"重複の処理方法:",categories:{printers:"プリンター",smartPlugs:"スマートプラグ",notificationProviders:"通知プロバイダー",filaments:"フィラメント",archives:"アーカイブ",pendingUploads:"保留中のアップロード",settingsTemplates:"設定とテンプレート"},matchingInfo:{printers:"シリアル番号で照合",smartPlugs:"IPアドレスで照合",notificationProviders:"名前で照合",filaments:"名前+タイプ+ブランドで照合",archives:"コンテンツハッシュで照合",pendingUploads:"ファイル名で照合",settingsTemplates:"常に上書き"},replaceExisting:"既存データを置き換え",keepExisting:"既存データを保持",replaceDescription:"既に存在するアイテムをバックアップデータで上書き",keepDescription:"まだ存在しないアイテムのみを復元",caution:"注意:",cautionText:"上書きすると現在の構成がバックアップデータに置き換えられます。セキュリティ上の理由から、プリンターのアクセスコードは上書きされません。",itemsRestored:"復元されたアイテム",itemsSkipped:"スキップされたアイテム",restored:"復元済み",skipped:"スキップ(既に存在)",filesLabel:"ファイル(3MF、サムネイルなど)",newApiKeysGenerated:"新しいAPIキーが生成されました",newApiKeysWarning:"これらのキーは一度だけ表示されます。今すぐコピーしてください!",processingBackup:"バックアップファイルを処理中...",noDataFound:"バックアップファイルに復元するデータが見つかりませんでした。",failedToRestore:"バックアップの復元に失敗しました。ファイル形式を確認してください。"},backupExport:{title:"バックアップをエクスポート",selectData:"含めるデータを選択",selectAll:"すべて選択",selectNone:"なし",categoryDescriptions:{settings:"言語、テーマ、更新設定",notifications:"ntfy、Pushover、Discordなど",templates:"カスタムメッセージテンプレート",smartPlugs:"Tasmotaプラグ設定",externalLinks:"サイドバーの外部サービスへのリンク",printers:"プリンター情報(アクセスコード除外)",plateDetection:"空プレート参照画像",filaments:"フィラメントの種類とコスト",maintenance:"カスタムメンテナンススケジュール",archives:"すべての印刷データ+ファイル(3MF、サムネイル、写真)",projects:"プロジェクト、BOMアイテム、添付ファイル",pendingUploads:"仮想プリンターアップロード待機中",apiKeys:"Webhook APIキー(インポート時に新しいキーが生成されます)"},requiresPrinters:"プリンターを選択する必要があります",zipFileWarning:"ZIPファイルが作成されます。",zipFileDescription:"すべての3MFファイル、サムネイル、タイムラプス、写真が含まれます。これには時間がかかり、大きなファイルになる可能性があります。",includeAccessCodes:"アクセスコードを含める",includeAccessCodesDescription:"別のマシンへの転送用",includeAccessCodesWarning:"アクセスコードはプレーンテキストで含まれます。このバックアップファイルを安全に保管してください!",categoriesSelected:"{{selectedCount}}カテゴリー選択済み"},tagManagement:{searchTags:"タグを検索...",renameTag:"タグ名を変更",deleteTag:"タグを削除"},notificationTemplates:{placeholders:{title:"通知タイトル...",body:"通知本文..."}},batchTag:{placeholders:{newTag:"新しいタグを入力..."}},photoGallery:{deletePhoto:"写真を削除"},filamentHoverCard:{copySpoolUuid:"スプールUUIDをコピー"},kProfilesView:{hasNote:"メモあり",copyProfile:"プロファイルをコピー"},layout:{openMenu:"メニューを開く",noPermissionSystemInfo:"システム情報を表示する権限がありません"},notificationProviderCard:{deleteNotificationProvider:"通知プロバイダーを削除"},fileManagerModal:{closeFileManager:"ファイルマネージャーを閉じる",sortFiles:"ファイルを並べ替え",goToParentFolder:"親フォルダーへ移動",threeView:"3Dビュー"},embeddedCameraViewer:{refreshStream:"ストリームを更新",close:"閉じる",zoomOut:"ズームアウト",resetZoom:"ズームをリセット",zoomIn:"ズームイン",dragToResize:"ドラッグしてサイズ変更"},timelapseViewer:{skipBack5s:"5秒戻る",skipForward5s:"5秒進む"},notificationProviders:{descriptions:{email:"SMTP電子メール通知",telegram:"Telegramボット経由の通知",discord:"Webhookを介してDiscordチャンネルに送信",ntfy:"無料でセルフホスト可能なプッシュ通知",pushover:"シンプルで信頼性の高いプッシュ通知",callmebot:"CallMeBot経由の無料WhatsApp通知",webhook:"任意のURLへのジェネリックHTTP POST"}},switchbarPopover:{noSwitchesInSwitchbar:"スイッチバーにスイッチがありません"},projectPageModal:{placeholders:{title:"タイトル",designer:"デザイナー",license:"ライセンス",description:"説明を入力...",profileTitle:"プロファイルタイトル",profileDescription:"プロファイルの説明..."}},githubBackupSettings:{},spoolmanSettings:{},time:{unknown:"-",waiting:"待機中",justNow:"たった今",now:"今すぐ",minsAgo:"{{count}}分前",inMins:"あと{{count}}分",hoursAgo:"{{count}}時間前",inHours:"あと{{count}}時間",daysAgo:"{{count}}日前",inDays:"あと{{count}}日"},spoolbuddy:{nav:{dashboard:"ダッシュボード",ams:"AMS",inventory:"在庫",printers:"プリンター",settings:"設定"},status:{nfcReady:"準備完了",nfcOff:"オフ",offline:"デバイスオフライン"},dashboard:{idleMessage:"スプールを秤に置き、NFCタグをスキャンしてください"},weight:{noReading:"計測なし",stable:"安定",measuring:"計測中",tare:"風袋",calibrate:"校正",tareQueued:"風袋コマンドを送信しました"},spool:{remaining:"残量"},tag:{unknownTitle:"不明なタグ",linkExisting:"既存のスプールにリンク",createNew:"新しいスプールを作成"},actions:{assignAms:"AMS割り当て",updateWeight:"重量更新",editSpool:"スプール編集",viewHistory:"履歴表示",weightUpdated:"スプール重量を更新しました"},ams:{noData:"AMSデータがありません"},inventory:{search:"スプールを検索...",empty:"スプールが見つかりません"},printers:{noPrinters:"プリンターが設定されていません"},settings:{scaleCalibration:"秤の校正",currentWeight:"現在の重量",tareOffset:"風袋オフセット",knownWeight:"既知の重量",calibrated:"校正が更新されました",tareQueued:"風袋コマンドをキューに追加しました",nfcReader:"NFCリーダー",nfcConnected:"接続済み",nfcDisconnected:"未接続",deviceInfo:"デバイス情報",deviceId:"デバイスID",uptime:"稼働時間",firmware:"ファームウェア"}}},hce={nav:{printers:"Stampanti",archives:"Archivi",queue:"Coda",stats:"Statistiche",profiles:"Profili",maintenance:"Manutenzione",projects:"Progetti",files:"File",settings:"Impostazioni",system:"Sistema",collapseSidebar:"Comprimi barra laterale",expandSidebar:"Espandi barra laterale",update:"Aggiorna",updateAvailable:"Aggiornamento disponibile: v{{version}}",updateAvailableBanner:"Versione {{version}} disponibile!",viewUpdate:"Vedi aggiornamento",viewOnGithub:"Vedi su GitHub",keyboardShortcuts:"Scorciatoie da tastiera (?)",switchToLight:"Passa a tema chiaro",switchToDark:"Passa a tema scuro",smartSwitches:"Interruttori Smart",logout:"Esci"},common:{save:"Salva",saving:"Salvataggio...",cancel:"Annulla",delete:"Elimina",edit:"Modifica",add:"Aggiungi",close:"Chiudi",confirm:"Conferma",loading:"Caricamento...",error:"Errore",success:"Successo",warning:"Avviso",enabled:"Abilitato",disabled:"Disabilitato",yes:"Si",no:"No",on:"On",off:"Off",all:"Tutti",none:"Nessuno",search:"Cerca",filter:"Filtro",sort:"Ordina",refresh:"Aggiorna",download:"Scarica",upload:"Carica",actions:"Azioni",status:"Stato",name:"Nome",description:"Descrizione",date:"Data",time:"Ora",hours:"ore",minutes:"minuti",seconds:"secondi",days:"giorni",enable:"Abilita",disable:"Disabilita",permissions:"Permessi",noPrinters:"Nessuna stampante configurata",noData:"Nessun dato disponibile",linkNotFound:"Link non trovato",required:"Obbligatorio",optional:"Opzionale",dismiss:"Chiudi",apply:"Applica",reset:"Reimposta",clear:"Pulisci",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",noChange:"— Nessun cambio —",unchanged:"Invariato",unassigned:"Non assegnato",unknown:"Sconosciuto",unknownError:"Errore sconosciuto",today:"Oggi",tomorrow:"Domani",asap:"ASAP",overdue:"Scaduto",now:"Ora",collapse:"Comprimi",expand:"Espandi",viewArchive:"Vedi archivio",viewInFileManager:"Vedi nel Gestore file",addedBy:"Aggiunto da {{username}}",prints:"stampe",more:"+{{count}} altre",ascending:"Crescente",descending:"Decrescente",printer:"Stampante",remove:"Rimuovi",type:"Tipo",print:"Stampa",rename:"Rinomina",move:"Sposta",create:"Crea",duplicate:"Duplica",left:"Sinistra",right:"Destra"},printers:{title:"Stampanti",addPrinter:"Aggiungi Stampante",editPrinter:"Modifica Stampante",deletePrinter:"Elimina Stampante",printerName:"Nome Stampante",serialNumber:"Numero Seriale",ipAddress:"Indirizzo IP",accessCode:"Codice di Accesso",model:"Modello",nozzleCount:"Numero Ugelli",autoArchive:"Auto Archiviazione",status:{available:"Disponibile",idle:"Inattiva",printing:"In stampa",paused:"In pausa",offline:"Offline",error:"Errore",finished:"Finita",unknown:"Sconosciuto"},temperatures:{nozzle:"Ugello",bed:"Piatto",chamber:"Camera"},progress:"{{percent}}% completato",timeRemaining:"{{time}} rimanente",deleteConfirm:'Sei sicuro di eliminare "{{name}}"?',maintenanceOk:"Manutenzione OK",maintenanceWarning:"{{count}} avviso",maintenanceWarning_plural:"{{count}} avvisi",maintenanceDue:"{{count}} in scadenza",maintenanceDue_plural:"{{count}} in scadenza",sort:{name:"Nome",status:"Stato",model:"Modello",location:"Posizione",ascending:"Ordina crescente",descending:"Ordina decrescente"},cardSize:{small:"Schede piccole",medium:"Schede medie",large:"Schede grandi",extraLarge:"Schede extra grandi"},hideOffline:"Nascondi offline",nextAvailable:"Prossima disponibile",powerOn:"Accendi",offlinePrintersWithPlugs:"Stampanti offline con smart plug",noPrintersConfigured:"Nessuna stampante configurata",readyToPrint:"Pronta a stampare",external:"Esterna",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Elimina archivi stampa",noLabel:"Nessuna etichetta",printPreview:"Anteprima stampa",width:"Larghezza",height:"Altezza",noObjectsFound:"Nessun oggetto trovato",objectsLoadedOnPrintStart:"Gli oggetti sono caricati quando inizia una stampa",willBeSkipped:"Verra saltato",name:"Nome",serialCannotBeChanged:"Il numero seriale non può essere cambiato",locationHelp:"Usato per raggruppare stampanti e filtrare i lavori in coda",wifiSignal:{veryWeak:"Molto debole",weak:"Debole",fair:"Discreto",good:"Buono",excellent:"Eccellente"},maintenanceUpToDate:"Tutta la manutenzione aggiornata - Clicca per vedere",chamberLightOn:"Accendi luce camera",chamberLightOff:"Spegni luce camera",browseFiles:"Sfoglia file stampante",autoOffAfterPrint:"Spegnimento automatico dopo stampa",autoOffExecuted:"Spegnimento automatico eseguito - accendi la stampante per reimpostare",hmsErrors:"Errori HMS",viewHmsErrors:"Vedi {{count}} errore(i) HMS",resume:"Riprendi",pause:"Pausa",stop:"Ferma",camera:"Camera",skipObject:"Salta Oggetto",reconnect:"Riconnetti",mqttDebug:"Debug MQTT",activeNozzle:"Attivo: ugello {{nozzle}}",nozzleRack:"Rack Ugelli",nozzleDocked:"Agganciato",nozzleMounted:"Montato",nozzleWear:"Usura",nozzleMaxTemp:"Temp Max",nozzleSerial:"Seriale",nozzleHardenedSteel:"Acciaio Temprato",nozzleStainlessSteel:"Acciaio Inox",nozzleTungstenCarbide:"Carburo di Tungsteno",nozzleFlow:"Flusso",nozzleHighFlow:"Alto Flusso",nozzleStandardFlow:"Standard",firmwareUpdate:"Aggiornamento Firmware",firmwareInstructions:"Sul touchscreen della stampante, vai a",firmwareNav:"Vai a",settings:"Impostazioni",firmware:"Firmware",discoverPrinters:"Trova Stampanti",searching:"Ricerca...",manualEntry:"Inserimento manuale",addFromCloud:"Aggiungi da Cloud",toast:{printerDeleted:"Stampante eliminata",printerAdded:"Stampante aggiunta",printerUpdated:"Stampante aggiornata",failedToDelete:"Impossibile eliminare stampante",failedToAdd:"Impossibile aggiungere stampante",failedToUpdate:"Impossibile aggiornare stampante",commandSent:"Comando inviato",failedToSendCommand:"Impossibile inviare comando",turnedOn:"{{name}} accesa",failedToPowerOn:"Impossibile accendere {{name}}",scriptTriggered:"Script avviato",printStopped:"Stampa fermata",printPaused:"Stampa in pausa",printResumed:"Stampa ripresa",referenceDeleted:"Riferimento eliminato",detectionAreaSaved:"Area rilevamento salvata",failedToRunScript:"Impossibile eseguire script",failedToStopPrint:"Impossibile fermare stampa",failedToPausePrint:"Impossibile mettere in pausa stampa",failedToResumePrint:"Impossibile riprendere stampa",failedToControlChamberLight:"Impossibile controllare luce camera",failedToUpdateSetting:"Impossibile aggiornare impostazione",failedToSkipObjects:"Impossibile saltare oggetti",failedToRereadRfid:"Impossibile rileggere RFID",failedToCheckPlate:"Impossibile controllare piatto",failedToUpdateLabel:"Impossibile aggiornare etichetta",failedToDeleteReference:"Impossibile eliminare riferimento",failedToSaveDetectionArea:"Impossibile salvare area rilevamento",plateCheckEnabled:"Controllo piatto abilitato",plateCheckDisabled:"Controllo piatto disabilitato",calibrationSaved:"Calibrazione salvata!",calibrationFailed:"Calibrazione non riuscita",rfidRereadInitiated:"Rilettura RFID avviata"},connection:{connected:"Connesso",offline:"Offline"},queue:{inQueue:"{{count}} stampa in coda",inQueue_plural:"{{count}} stampe in coda"},controls:"Controlli",rfid:{reread:"Rileggi RFID"},permission:{noAdd:"Non hai il permesso di aggiungere stampanti",noEdit:"Non hai il permesso di modificare stampanti",noDelete:"Non hai il permesso di eliminare stampanti",noControl:"Non hai il permesso di controllare stampanti",noFiles:"Non hai il permesso di accedere ai file stampante",noAmsRfid:"Non hai il permesso di rileggere AMS RFID",noSmartPlugControl:"Non hai il permesso di controllare smart plug"},modal:{addTitle:"Aggiungi Stampante",editTitle:"Modifica Stampante",myPrinter:"La mia Stampante",selectModel:"Seleziona modello...",locationGroup:"Posizione / Gruppo (opzionale)",locationPlaceholder:"es. Officina, Ufficio, Cantina",autoArchiveLabel:"Archivia automaticamente stampe completate",fromPrinterSettings:"Dalle impostazioni della stampante",modelOptional:"Modello (opzionale)",saveChanges:"Salva modifiche"},skipObjects:{tooltip:"Salta oggetti",onlyWhilePrinting:"Salta oggetti (solo durante la stampa)",requiresMultiple:"Salta oggetti (richiede 2+ oggetti)",title:"Salta Oggetti",matchIdsInfo:"Abbina gli ID con il display della stampante",printerShowsIds:"Lo schermo mostra gli ID oggetto sul piatto",skipSelected:"Salta selezionati",skipping:"Saltando...",noObjectsSelected:"Nessun oggetto selezionato",selectObjectsToSkip:"Seleziona gli oggetti da saltare nella stampa corrente",skipped:"saltato",objectsSkipped:"Oggetti saltati",activeCount:"{{count}} attivi",waitForLayer:"Attendi il layer 2+ per saltare oggetti (attualmente layer {{layer}})",skip:"Salta",confirmTitle:"Saltare oggetto?",confirmMessage:'Sei sicuro di voler saltare "{{name}}"? Questa azione non può essere annullata.'},confirm:{deleteTitle:"Elimina Stampante",deleteMessage:'Sei sicuro di eliminare "{{name}}"? Questo rimuoverà tutte le impostazioni di connessione.',deleteArchivesNote:"Tutta la cronologia di stampa sarà eliminata definitivamente.",keepArchivesNote:"La cronologia sarà mantenuta ma non più associata a questa stampante.",stopTitle:"Ferma Stampa",stopMessage:'Sei sicuro di fermare la stampa corrente su "{{name}}"? Questo annullerà il lavoro di stampa.',stopButton:"Ferma Stampa",pauseTitle:"Pausa Stampa",pauseMessage:'Sei sicuro di mettere in pausa la stampa corrente su "{{name}}"?',pauseButton:"Pausa Stampa",resumeTitle:"Riprendi Stampa",resumeMessage:'Sei sicuro di riprendere la stampa su "{{name}}"?',resumeButton:"Riprendi Stampa",powerOnTitle:"Accendi Stampante",powerOnMessage:'Sei sicuro di accendere "{{name}}"?',powerOnButton:"Accendi",powerOffTitle:"Spegni Stampante",powerOffMessage:'Sei sicuro di spegnere "{{name}}"?',powerOffWarning:'AVVISO: "{{name}}" sta stampando! Sei sicuro di spegnere? Questo interromperà la stampa e potrebbe danneggiare la stampante.',powerOffButton:"Spegni"},discovery:{title:"Trova Stampanti",searching:"Ricerca...",scanning:"Scansione...",scanProgress:"Scansione... {{scanned}}/{{total}}",foundPrinters:"Trovate {{count}} stampante(i)",noPrintersFound:"Nessuna stampante trovata",noPrintersFoundSubnet:"Nessuna stampante trovata nella sottorete specificata.",noPrintersFoundNetwork:"Nessuna stampante trovata sulla rete.",allConfigured:"Tutte le stampanti trovate sono già configurate.",alreadyAdded:"Già aggiunta",select:"Seleziona",manualEntry:"Inserimento manuale",addFromCloud:"Aggiungi da Cloud",subnetToScan:"Sottorete da scansionare",dockerNote:"Docker rilevato. Inserisci la sottorete della stampante in notazione CIDR. Richiede network_mode: host in docker-compose.yml.",scanSubnet:"Scansiona sottorete per stampanti",discoverNetwork:"Trova stampanti in rete",scanningSubnet:"Scansione sottorete per stampanti Bambu...",scanningNetwork:"Scansione rete...",serialRequired:"Seriale richiesto",unknown:"Sconosciuto",failedToStart:"Avvio ricerca non riuscito"},filaments:"Filamenti",openCameraOverlay:"Apri overlay camera",openCameraWindow:"Apri camera in nuova finestra",firmwareUpdateAvailable:"Aggiornamento firmware disponibile: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Aggiornato",firmwareUpdateButton:"Aggiorna",plateDetection:{noPermission:"Non hai il permesso di aggiornare le stampanti",enabledClick:"Controllo piatto abilitato - Clicca per disabilitare",disabledClick:"Controllo piatto disabilitato - Clicca per abilitare",manageCalibration:"Gestisci calibrazione rilevamento piatto",calibrationRequired:"Calibrazione richiesta",calibrationInstructions:"Assicurati che il piatto sia <strong>completamente vuoto</strong>, poi clicca Calibra.",calibrationDescription:"La calibrazione salva un'immagine di riferimento del piatto vuoto. I controlli futuri confronteranno con questo riferimento per rilevare oggetti.",calibrationTip:"<strong>Suggerimento:</strong> Puoi salvare fino a 5 calibrazioni per piatti diversi. Il sistema usa automaticamente la migliore corrispondenza durante il controllo.",plateEmpty:"Il piatto sembra vuoto",objectsDetected:"Oggetti rilevati sul piatto",confidence:"Confidenza",difference:"Differenza",analysisPreview:"Anteprima analisi:",analysisLegend:"Riquadro verde = area rilevamento, overlay rosso = differenze dalla calibrazione",savedReferences:"Riferimenti salvati ({{count}}/{{max}})",deleteReference:"Elimina riferimento",labelPlaceholder:"Etichetta...",clickToEdit:"{{label}} - Clicca per modificare",clickToAddLabel:"Clicca per aggiungere etichetta"},fans:{partCooling:"Ventola raffreddamento parte",auxiliary:"Ventola ausiliaria",chamber:"Ventola camera"},clickToViewHmsErrors:"Clicca per vedere errori HMS",estimatedCompletion:"Tempo completamento stimato",slotOptions:"Opzioni slot",firmwareModal:{title:"Aggiornamento Firmware",titleUpToDate:"Info Firmware",currentVersion:"Corrente:",latestVersion:"Ultima:",releaseNotes:"Note di rilascio",checkingPrereqs:"Controllo prerequisiti...",sdCardReady:"SD pronta. Clicca sotto per caricare firmware.",uploadedSuccess:"Firmware caricato su SD!",applyInstructions:"Per applicare l'aggiornamento sulla stampante:",step1:"Sul touchscreen della stampante, vai a <strong>Impostazioni</strong>",step2:"Vai a <strong>Firmware</strong>",step3:"Seleziona <strong>Aggiorna da SD</strong>",step4:"L'aggiornamento richiede 10-20 minuti",done:"Fatto",starting:"Avvio...",uploadFirmware:"Carica Firmware",uploadFailed:"Avvio caricamento fallito: {{error}}",uploadedToast:"Firmware caricato! Avvia aggiornamento dal display."},accessCodePlaceholder:"Lascia vuoto per mantenere quello attuale",roi:{title:"Area di rilevamento (ROI)",xStart:"X Inizio",yStart:"Y Inizio",width:"Larghezza",height:"Altezza",instruction:"Regola l'area di rilevamento per focalizzare il piatto. Il riquadro verde mostra l'area corrente."},developerModeWarning:"La modalità sviluppatore LAN non è attivata su: {{names}}. Alcune funzionalità potrebbero non funzionare.",howToEnable:"Come attivare"},archives:{title:"Archivi di stampa",searchPlaceholder:"Cerca archivi...",filterByPrinter:"Filtra per stampante",filterByStatus:"Filtra per stato",sortBy:"Ordina per",sortNewest:"Più recenti",sortOldest:"Meno recenti",sortName:"Nome",sortDuration:"Durata",sortLargest:"Più grandi",sortSmallest:"Più piccoli",sortSize:"Dimensione",noArchives:"Nessun archivio trovato",noArchivesSearch:"Nessun archivio corrisponde alla ricerca",noArchivesYet:"Nessun archivio ancora",loadingArchives:"Caricamento archivi...",releaseToUpload:"Rilascia per caricare",showAll:"Mostra tutti",showFavoritesOnly:"Solo preferiti",gridView:"Vista griglia",listView:"Vista elenco",calendarView:"Vista calendario",logView:"Registro stampe",manageTags:"Gestisci tag",showFailedPrints:"Mostra stampe fallite",hideFailedPrints:"Nascondi stampe fallite",printTime:"Tempo di stampa",filamentUsed:"Filamento usato",cost:"Costo",reprint:"Ristampa",preview:"Anteprima",deleteArchive:"Elimina archivio",deleteConfirm:"Sei sicuro di eliminare questo archivio?",favorite:"Preferito",unfavorite:"Rimuovi dai preferiti",viewDetails:"Vedi dettagli",status:{completed:"Completato",failed:"Fallito",stopped:"Fermato"},toast:{source3mfAttached:"Sorgente 3MF allegata: {{filename}}",failedUploadSource3mf:"Caricamento sorgente 3MF non riuscito",source3mfRemoved:"Sorgente 3MF rimossa",failedRemoveSource3mf:"Rimozione sorgente 3MF non riuscita",f3dAttached:"F3D allegato: {{filename}}",failedUploadF3d:"Caricamento F3D non riuscito",f3dRemoved:"F3D rimosso",failedRemoveF3d:"Rimozione F3D non riuscita",timelapseAttached:"Timelapse allegato: {{filename}}",timelapseAlreadyAttached:"Timelapse già allegato",noMatchingTimelapse:"Nessun timelapse corrispondente",failedScanTimelapse:"Scansione timelapse non riuscita",failedAttachTimelapse:"Allegato timelapse non riuscito",archiveDeleted:"Archivio eliminato",failedDeleteArchive:"Eliminazione archivio non riuscita",addedToFavorites:"Aggiunto ai preferiti",removedFromFavorites:"Rimosso dai preferiti",projectUpdated:"Progetto aggiornato",failedUpdateProject:"Aggiornamento progetto non riuscito",linkCopied:"Link copiato negli appunti",failedCopyLink:"Copia link non riuscita",photoDeleted:"Foto eliminata",failedDeletePhoto:"Eliminazione foto non riuscita",failedDeleteArchives:"Eliminazione archivi non riuscita",failedUpdateFavorites:"Aggiornamento preferiti non riuscito",exportDownloaded:"Export scaricato",exportFailed:"Export non riuscito"},menu:{print:"Stampa",schedule:"Programma",openInBambuStudio:"Apri nello slicer",slice:"Slice",externalLink:"Link esterno",viewOnMakerWorld:"Vedi su MakerWorld",preview3d:"Anteprima 3D",viewTimelapse:"Vedi Timelapse",scanForTimelapse:"Cerca Timelapse",downloadSource3mf:"Scarica Sorgente 3MF",uploadSource3mf:"Carica Sorgente 3MF",replaceSource3mf:"Sostituisci Sorgente 3MF",removeSource3mf:"Rimuovi Sorgente 3MF",uploadF3d:"Carica F3D",replaceF3d:"Sostituisci F3D",downloadF3d:"Scarica F3D",removeF3d:"Rimuovi F3D",download:"Scarica",copyDownloadLink:"Copia link download",qrCode:"QR Code",viewPhotos:"Vedi foto",viewPhotosCount:"Vedi foto ({{count}})",projectPage:"Pagina progetto",addToFavorites:"Aggiungi ai preferiti",removeFromFavorites:"Rimuovi dai preferiti",edit:"Modifica",goToProject:"Vai al progetto: {{name}}",addToProject:"Aggiungi al progetto",removeFromProject:"Rimuovi dal progetto",loading:"Caricamento...",noProjectsAvailable:"Nessun progetto disponibile",select:"Seleziona",deselect:"Deseleziona",delete:"Elimina"},permission:{noReprint:"Non hai il permesso di ristampare questo archivio",noAddToQueue:"Non hai il permesso di aggiungere alla coda",noUpdateArchives:"Non hai il permesso di aggiornare archivi",noUploadFiles:"Non hai il permesso di caricare file",noDownload:"Non hai il permesso di scaricare archivi",noCopyLink:"Non hai il permesso di copiare link download",noDelete:"Non hai il permesso di eliminare questo archivio",noCreate:"Non hai il permesso di creare archivi"},card:{previousPlate:"Piatto precedente",nextPlate:"Piatto successivo",plateNumber:"Piatto {{index}}",moreOptions:"Clic destro per altre opzioni",addToFavorites:"Aggiungi ai preferiti",removeFromFavorites:"Rimuovi dai preferiti",cancelled:"annullato",failed:"fallito",duplicate:"duplicato",duplicateTitle:"Questo modello è stato stampato prima",openSource3mf:"Apri sorgente 3MF in Bambu Studio (clic destro per altre opzioni)",downloadF3d:"Scarica file design Fusion 360",viewTimelapse:"Vedi timelapse",viewPhoto:"Vedi 1 foto",viewPhotos:"Vedi {{count}} foto",openFolder:"Apri cartella: {{name}}",slicedFile:"File slice - pronto a stampare",sourceFile:"Solo file sorgente - nessuna mappatura AMS disponibile",gcode:"GCODE",source:"SOURCE",project:"Progetto: {{name}}",estimated:"Stimato: {{time}}",actual:"Reale: {{time}}",accuracy:"Accuratezza: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} strato",layers:"{{count}} strati",object:"{{count}} oggetto",objects:"{{count}} oggetti",slicedFor:"Sliced per {{model}}",uploadedBy:"Caricato da",noPermissionReprint:"Non hai il permesso di ristampare",noFileForReprint:"Nessun file 3MF disponibile — il file non è stato scaricato dalla stampante durante la registrazione",noPermissionEdit:"Non hai il permesso di modificare archivi",noPermissionDelete:"Non hai il permesso di eliminare archivi",reprint:"Ristampa",schedulePrint:"Programma Stampa",schedule:"Programma",openInBambuStudio:"Apri nello slicer",openInBambuStudioToSlice:"Apri nello slicer per slicing",slice:"Slice",externalLink:"Link esterno",makerWorld:"MakerWorld: {{designer}}",viewProject:"Vedi progetto",noExternalLink:"Nessun link esterno",preview3d:"Anteprima 3D",download:"Scarica",edit:"Modifica",delete:"Elimina"},modal:{deleteArchive:"Elimina Archivio",deleteConfirm:'Sei sicuro di eliminare "{{name}}"? Questa azione non può essere annullata.',deleteButton:"Elimina",removeSource3mf:"Rimuovi Sorgente 3MF",removeSource3mfConfirm:'Sei sicuro di rimuovere il file sorgente 3MF da "{{name}}"? Questo eliminerà il progetto slicer originale.',removeButton:"Rimuovi",removeF3d:"Rimuovi F3D",removeF3dConfirm:'Sei sicuro di rimuovere il file Fusion 360 da "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Seleziona Timelapse",selectTimelapseDesc:"Nessun abbinamento automatico trovato. Seleziona il timelapse per questa stampa:",deleteArchives:"Elimina Archivi",deleteArchivesConfirm:"Sei sicuro di eliminare {{count}} archivio(i)? Questa azione non può essere annullata.",deleteCount:"Elimina {{count}}"},page:{title:"Archivi",printsCount:"{{filtered}} di {{total}} stampe",dropFilesHere:"Rilascia file .3mf qui",releaseToUpload:"Rilascia per caricare",only3mfSupported:"Solo file .3mf supportati",close:"Chiudi",selected:"{{count}} selezionati",selectAll:"Seleziona tutto",tags:"Tag",project:"Progetto",favorite:"Preferito",delete:"Elimina",toggledFavorites:"Preferiti aggiornati per {{count}} archivio(i)",failedUpdateFavorites:"Aggiornamento preferiti non riuscito",archivesDeleted:"{{count}} archivio(i) eliminati",failedDeleteArchives:"Eliminazione archivi non riuscita",photoDeleted:"Foto eliminata",failedDeletePhoto:"Eliminazione foto non riuscita"},list:{name:"Nome",printer:"Stampante",date:"Data",size:"Dimensione",actions:"Azioni",hasTimelapse:"Ha timelapse"},log:{date:"Data",printName:"Nome stampa",printer:"Stampante",user:"Utente",status:"Stato",duration:"Durata",filament:"Filamento",allPrinters:"Tutte le stampanti",allUsers:"Tutti gli utenti",allStatuses:"Tutti gli stati",cancelled:"Annullato",skipped:"Saltato",dateFrom:"Dal",dateTo:"Al",noEntries:"Nessuna voce di registro trovata",showing:"{{count}} di {{total}} voci",rowsPerPage:"Righe",page:"Pagina",prev:"Prec.",next:"Succ.",clearLog:"Cancella registro",clearLogTitle:"Cancella registro stampe",clearLogConfirm:"Tutte le voci del registro di stampa verranno eliminate permanentemente. Gli archivi e gli elementi della coda non sono interessati. Questa azione non può essere annullata. Sei sicuro?",clearLogButton:"Cancella tutto",cleared:"{{count}} voci di registro cancellate",clearFailed:"Impossibile cancellare il registro stampe"}},queue:{title:"Coda di stampa",subtitle:"Programma e gestisci i tuoi lavori di stampa",addToQueue:"Aggiungi alla coda",print:"Stampa",reprint:"Ristampa",schedulePrint:"Programma Stampa",editQueueItem:"Modifica elemento coda",printToPrinters:"Stampa su {{count}} Stampanti",queueToPrinters:"Metti in coda su {{count}} Stampanti",sending:"Invio...",sendingProgress:"Invio {{current}}/{{total}}...",adding:"Aggiunta...",addingProgress:"Aggiunta {{current}}/{{total}}...",savingProgress:"Salvataggio {{current}}/{{total}}...",clearQueue:"Svuota coda",clearHistory:"Svuota cronologia",emptyQueue:"La coda è vuota",position:"Posizione",scheduledTime:"Ora programmata",moveUp:"Sposta su",moveDown:"Sposta giù",startNow:"Avvia ora",printingInProgress:"Stampa in corso...",viewArchive:"Vedi archivio",viewInFileManager:"Vedi nel Gestore file",itemCount:"{{count}} elemento",itemCount_plural:"{{count}} elementi",dragToReorder:"Trascina per riordinare (solo ASAP)",reorderHint:"La posizione influisce solo sugli elementi ASAP. Quelli programmati partono all'orario.",addedBy:"Aggiunto da {{name}}",plateNumber:"Piatto {{index}}",sections:{currentlyPrinting:"In stampa",queued:"In coda",history:"Cronologia"},status:{pending:"In attesa",waiting:"In attesa",printing:"In stampa",paused:"In pausa",completed:"Completato",failed:"Fallito",skipped:"Saltato",cancelled:"Annullato"},summary:{printing:"In stampa",queued:"In coda",totalTime:"Tempo totale coda",totalWeight:"Peso totale della coda",history:"Cronologia"},filter:{allPrinters:"Tutte le stampanti",unassigned:"Non assegnato",allStatus:"Tutti gli stati",allLocations:"Tutte le posizioni",any:"Qualsiasi"},sort:{byPosition:"Ordina per posizione",byName:"Ordina per nome",byPrinter:"Ordina per stampante",bySchedule:"Ordina per programma",byDate:"Ordina per data",ascendingOldest:"Crescente (più vecchi)",descendingNewest:"Decrescente (più recenti)"},badges:{staged:"In staging",requiresPrevious:"Richiede successo precedente",autoPowerOff:"Spegnimento automatico"},empty:{title:"Nessuna stampa programmata",description:`Programma una stampa dalla pagina Archivi usando l'opzione "Programma" nel menu contestuale, o trascina i file per iniziare.`},time:{asap:"ASAP",overdue:"Scaduto",now:"Ora",lessThanMinute:"Tra meno di un minuto",inMinutes:"Tra {{count}} min",inHours:"Tra {{count}} ore"},actions:{stopPrint:"Ferma Stampa",startPrint:"Avvia Stampa",requeue:"Rimetti in coda"},bulkEdit:{title:"Modifica {{count}} elemento",title_plural:"Modifica {{count}} elementi",description:"Solo le impostazioni modificate saranno applicate agli elementi selezionati.",printer:"Stampante",noChange:"— Nessun cambio —",queueOptions:"Opzioni coda",staged:"In staging (avvio manuale)",autoPowerOff:"Spegnimento automatico dopo stampa",requirePrevious:"Richiede successo precedente",printOptions:"Opzioni stampa",bedLevelling:"Livellamento piatto",flowCalibration:"Calibrazione flusso",vibrationCalibration:"Calibrazione vibrazioni",layerInspection:"Controllo primo layer",timelapse:"Timelapse",useAms:"Usa AMS",applyChanges:"Applica modifiche",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",selected:"{{count}} selezionati",editSelected:"Modifica selezionati",cancelSelected:"Annulla selezionati"},confirm:{cancelTitle:"Annulla stampa programmata",cancelMessage:'Sei sicuro di annullare "{{name}}"?',stopTitle:"Ferma Stampa",stopMessage:'Sei sicuro di fermare la stampa corrente "{{name}}"? Questo annullerà il lavoro sulla stampante.',removeTitle:"Rimuovi dalla cronologia",removeMessage:'Sei sicuro di rimuovere "{{name}}" dalla cronologia coda?',clearHistoryTitle:"Svuota cronologia",clearHistoryMessage:"Sei sicuro di rimuovere {{count}} elemento(i) dalla cronologia?",cancelButton:"Annulla Stampa",stopButton:"Ferma Stampa",thisPrint:"questa stampa",thisItem:"questo elemento"},toast:{cancelled:"Elemento coda annullato",cancelFailed:"Annullamento non riuscito",removed:"Elemento coda rimosso",removeFailed:"Rimozione non riuscita",stopped:"Stampa fermata",stopFailed:"Impossibile fermare stampa",released:"Stampa rilasciata in coda",startFailed:"Avvio stampa non riuscito",reorderFailed:"Riordino coda non riuscito",historyCleared:"Cancellati {{count}} elementi cronologia",clearHistoryFailed:"Svuotamento cronologia non riuscito",updateFailed:"Aggiornamento elementi non riuscito",bulkCancelled:"Annullati {{count}} elementi",bulkCancelFailed:"Annullamento elementi non riuscito"},permissions:{noStopPrint:"Non hai il permesso di fermare stampe",noStartPrint:"Non hai il permesso di avviare stampe",noEdit:"Non hai il permesso di modificare questo elemento coda",noCancel:"Non hai il permesso di annullare questo elemento coda",noRequeue:"Non hai il permesso di rimettere in coda elementi",noRemove:"Non hai il permesso di rimuovere questo elemento coda",noClearHistory:"Non hai il permesso di svuotare tutta la cronologia",noEditItems:"Non hai il permesso di modificare elementi coda",noCancelItems:"Non hai il permesso di annullare elementi coda"}},backgroundDispatch:{unknownFile:"File sconosciuto",unknownPrinter:"Stampante sconosciuta",startingPrints:"Avvio stampe",progressSummary:"{{complete}}/{{total}} completati • Inviati: {{dispatched}} • In elaborazione: {{processing}}",expandDetails:"Espandi dettagli dispatch",collapseDetails:"Comprimi dettagli dispatch",dismissToast:"Chiudi notifica dispatch",cancelDispatchJob:"Annulla job dispatch",cancel:"Annulla",cancelling:"Annullamento…",status:{dispatched:"Inviato",processing:"In elaborazione",completed:"Completato",failed:"Fallito",cancelled:"Annullato"},toast:{cancellingUpload:"Annullamento upload...",cancelled:"Dispatch annullato",cancelFailed:"Impossibile annullare il dispatch",completeWithFailures:"Dispatch in background completato: {{completed}} riusciti, {{failed}} falliti",completeSuccess:"Dispatch in background completato: {{completed}} riusciti"}},stats:{title:"Dashboard",subtitle:"Trascina i widget per riordinare. Clicca l'icona occhio per nascondere.",overview:"Panoramica",totalPrints:"Stampe totali",successRate:"Tasso di successo",totalPrintTime:"Tempo totale di stampa",printTime:"Tempo di stampa",totalFilament:"Filamento totale usato",filamentUsed:"Filamento usato",filamentCost:"Costo filamento",totalCost:"Costo totale",energyUsed:"Energia usata",energyCost:"Costo energia",averagePrintTime:"Tempo medio di stampa",printsPerDay:"Stampe al giorno",byPrinter:"Per stampante",printsByPrinter:"Stampe per stampante",byMaterial:"Per materiale",byMonth:"Per mese",last7Days:"Ultimi 7 giorni",last30Days:"Ultimi 30 giorni",last90Days:"Ultimi 90 giorni",allTime:"Sempre",quickStats:"Statistiche rapide",printActivity:"Attivita di stampa",filamentTypes:"Tipi di filamento",filamentTrends:"Trend filamento",failureAnalysis:"Analisi guasti",timeAccuracy:"Accuratezza tempo",successful:"Riuscite:",failed:"Fallite:",perfectEstimate:"100% = stima perfetta",noTimeAccuracyData:"Nessun dato accuratezza tempo",noFilamentData:"Nessun dato filamento",noPrinterData:"Nessun dato stampante",noPrintData:"Nessun dato stampa",noPrintDataLast30Days:"Nessun dato stampa negli ultimi 30 giorni",failureReasons:"Cause guasto",topFailureReasons:"Cause principali",failedPrintsCount:"{{failed}} / {{total}} stampe fallite",lastWeekRate:"Settimana scorsa: {{rate}}%",resetLayout:"Reimposta layout",recalculateCosts:"Ricalcola costi",recalculateCostsHint:"Ricalcola tutti i costi archivi usando i prezzi filamento correnti",exportStats:"Esporta statistiche",exportAsCsv:"Esporta come CSV",exportAsExcel:"Esporta come Excel",hiddenCount:"{{count}} Nascosti",exportDownloaded:"Export scaricato",exportFailed:"Export non riuscito",layoutReset:"Layout reimpostato",recalculatedCosts:"Costi ricalcolati per {{count}} archivi",recalculateFailed:"Ricalcolo costi non riuscito",loadingStats:"Caricamento statistiche...",noPermissionResetLayout:"Non hai il permesso di reimpostare il layout",noPermissionRecalculate:"Non hai il permesso di ricalcolare i costi"},maintenance:{title:"Manutenzione",overview:"Panoramica",allOk:"Tutta la manutenzione aggiornata",dueCount:"{{count}} elemento in scadenza",dueCount_plural:"{{count}} elementi in scadenza",warningCount:"{{count}} avviso",warningCount_plural:"{{count}} avvisi",totalPrintTime:"Tempo totale di stampa",nextMaintenance:"Prossima manutenzione",nothingDue:"Niente in scadenza",tasks:"Attivita",lastPerformed:"Ultima esecuzione",interval:"Intervallo",hoursRemaining:"{{hours}}h rimanenti",hoursOverdue:"{{hours}}h in ritardo",markDone:"Segna come fatto",performMaintenance:"Esegui manutenzione",history:"Cronologia",noHistory:"Nessuna cronologia manutenzione",editPrintHours:"Modifica ore stampa",currentHours:"Ore attuali",statusTab:"Stato",settingsTab:"Impostazioni",overdueCount:"{{count}} in ritardo",dueSoonCount:"{{count}} in scadenza",dueSoon:"In scadenza",allGood:"Tutto ok",overdueBy:"In ritardo di {{duration}}",dueIn:"Scade tra {{duration}}",timeLeft:"{{duration}} rimanenti",day:"1 giorno",days:"{{count}} giorni",week:"1 settimana",weeks:"{{count}} settimane",month:"1 mese",months:"{{count}} mesi",year:"1 anno",maintenanceTypes:"Tipi di manutenzione",maintenanceTypesDescription:"Tipi di sistema e tue attivita personalizzate",addCustomType:"Aggiungi tipo personalizzato",restoreDefaults:"Ripristina attivita predefinite",intervalType:"Tipo intervallo",intervalValue:"Intervallo ({{type}})",icon:"Icona",documentationLink:"Link documentazione (opzionale)",assignToPrinters:"Assegna alle stampanti",selectAtLeastOnePrinter:"Seleziona almeno una stampante",addType:"Aggiungi tipo",custom:"Personalizzato",printHours:"Ore di stampa",calendarDays:"Giorni calendario",exampleName:"es. Sostituisci filtro HEPA",viewDocumentation:"Vedi documentazione",timeBasedInterval:"Intervallo basato sul tempo",intervalOverrides:"Override intervallo",intervalOverridesDescription:"Personalizza intervalli per stampanti specifiche",assignedToPrinters:"Assegnato alle stampanti:",noPrintersAssigned:"Nessuna stampante assegnata",addPrinterShort:"Aggiungi:",printersAssignedClick:"{{count}} stampante(i) assegnata - clicca per gestire",removeFromPrinter:"Rimuovi da questa stampante",types:{lubricateCarbonRods:"Lubrifica aste in carbonio",lubricateRails:"Lubrifica guide lineari",cleanNozzle:"Pulisci ugello/Hotend",checkBelts:"Controlla tensione cinghie",cleanBuildPlate:"Pulisci piatto",checkExtruder:"Controlla ingranaggi estrusore",checkCooling:"Controlla ventole raffreddamento",generalInspection:"Ispezione generale",cleanCarbonRods:"Pulisci aste in carbonio",cleanLinearRails:"Pulisci guide lineari",checkPtfeTube:"Controlla tubo PTFE",replaceHepaFilter:"Sostituisci filtro HEPA",replaceCarbonFilter:"Sostituisci filtro carbone",lubricateLeftNozzleRail:"Lubrifica guida ugello sinistro"},maintenanceComplete:"Manutenzione segnata come completata",typeUpdated:"Tipo manutenzione aggiornato",typeDeleted:"Tipo manutenzione eliminato",defaultsRestored:"Ripristinate {{count}} attivita predefinite",printHoursUpdated:"Ore di stampa aggiornate",printerAssigned:"Stampante assegnata",printerRemoved:"Stampante rimossa",deleteTypeConfirm:'Eliminare "{{name}}"?',deleteSystemTypeTitle:"Eliminare attività di manutenzione predefinita?",deleteSystemTypeMessage:`Sei sicuro di voler eliminare l'attività di manutenzione predefinita "{{name}}"?`,noPermissionUpdate:"Non hai il permesso di aggiornare elementi manutenzione",noPermissionPerform:"Non hai il permesso di eseguire manutenzione",noPermissionEditTypes:"Non hai il permesso di modificare tipi manutenzione",noPermissionDeleteTypes:"Non hai il permesso di eliminare tipi manutenzione",noPermissionEditHours:"Non hai il permesso di modificare ore stampa",noPermissionRemovePrinter:"Non hai il permesso di rimuovere assegnazioni stampanti",noPermissionAssignPrinter:"Non hai il permesso di assegnare stampanti",noPermissionEditIntervals:"Non hai il permesso di modificare intervalli",configureSettings:"Configura tipi e intervalli manutenzione"},settings:{title:"Impostazioni",general:"Generale",tabs:{general:"Generale",smartPlugs:"Prese smart",notifications:"Notifiche",filament:"Filamento",network:"Rete",apiKeys:"Chiavi API",virtualPrinter:"Stampante virtuale",users:"Utenti",backup:"Backup"},appearance:"Aspetto",notifications:"Notifiche",smartPlugs:"Prese smart",spoolman:"Spoolman",updates:"Aggiornamenti",language:"Lingua",languageDescription:"Seleziona la lingua preferita",theme:"Tema",themeLight:"Chiaro",themeDark:"Scuro",themeSystem:"Sistema",defaultView:"Vista predefinita",defaultViewDescription:"Pagina da mostrare all'apertura dell'app",checkForUpdates:"Controlla aggiornamenti",autoUpdate:"Aggiornamento automatico",currentVersion:"Versione attuale",latestVersion:"Ultima versione",upToDate:"Sei aggiornato",updateAvailable:"Aggiornamento disponibile",notificationLanguage:"Lingua notifiche",notificationLanguageDescription:"Lingua per notifiche push",bedCooledThreshold:"Soglia raffreddamento piatto",bedCooledThresholdDescription:"Temperatura sotto la quale il piatto è considerato raffreddato dopo una stampa",notificationProviders:"Provider notifiche",addProvider:"Aggiungi provider",editProvider:"Modifica provider",providerType:"Tipo provider",testNotification:"Notifica di test",testSuccess:"Notifica di test inviata",testFailed:"Invio notifica di test fallito",quietHours:"Ore silenziose",quietHoursDescription:"Non disturbare in queste ore",quietHoursStart:"Inizio",quietHoursEnd:"Fine",events:{title:"Eventi notifica",printStart:"Stampa avviata",printComplete:"Stampa completata",printFailed:"Stampa fallita",printStopped:"Stampa interrotta",printProgress:"Avanzamento",printProgressDescription:"Notifica al 25%, 50%, 75%",printerOffline:"Stampante offline",printerError:"Errore stampante",filamentLow:"Filamento in esaurimento",maintenanceDue:"Manutenzione dovuta",maintenanceDueDescription:"Notifica quando serve manutenzione"},smartPlug:{title:"Prese smart",add:"Aggiungi presa smart",edit:"Modifica presa smart",name:"Nome",ipAddress:"Indirizzo IP",linkedPrinter:"Stampante collegata",autoOn:"Accensione automatica",autoOnDescription:"Accendi all'avvio stampa",autoOff:"Spegnimento automatico",autoOffDescription:"Spegni dopo il completamento",offDelay:"Ritardo spegnimento",offDelayMinutes:"Minuti dopo la stampa",offDelayTemp:"Quando ugello sotto temperatura",currentState:"Stato attuale",turnOn:"Accendi",turnOff:"Spegni"},spoolmanEnabled:"Abilita integrazione Spoolman",spoolmanUrl:"URL Spoolman",spoolmanConnected:"Connesso",spoolmanDisconnected:"Disconnesso",noDefaultPrinter:"Nessuna predefinita (chiedi ogni volta)",sidebarOrder:"Ordine barra laterale",saveThumbnails:"Salva miniature",captureFinishPhoto:"Acquisisci foto finale",noPrintersConfigured:"Nessuna stampante configurata",archiveMode:{always:"Crea sempre voce archivio",never:"Non creare mai voce archivio",ask:"Chiedi ogni volta"},checkForUpdatesLabel:"Controlla aggiornamenti",checkPrinterFirmware:"Controlla firmware stampante",includeBetaUpdates:"Includi versioni beta",includeBetaUpdatesDesc:"Notifica versioni beta e prerelease durante il controllo aggiornamenti",enableRetry:"Abilita retry",homeAssistantDescription:"Controlla prese smart tramite Home Assistant",environmentManagedLabel:"(Gestito dall'ambiente)",autoEnabledViaEnv:"Abilitato automaticamente tramite variabili d'ambiente",urlFromEnvReadOnly:"Valore impostato dalla variabile d'ambiente HA_URL (sola lettura)",tokenFromEnvReadOnly:"Valore impostato dalla variabile d'ambiente HA_TOKEN (sola lettura)",mqttConnectedTo:"Connesso a",prometheusDescription:"Esponi dati stampante in formato Prometheus",noSmartPlugsTitle:"Nessuna presa smart configurata",noSmartPlugsDescription:"Aggiungi una presa smart Tasmota per monitorare energia e automatizzare il controllo.",noProvidersTitle:"Nessun provider configurato",noProvidersDescription:"Aggiungi un provider per ricevere avvisi.",noTemplatesAvailable:"Nessun template disponibile. Riavvia il backend per generare i template predefiniti.",apiPermissionView:"Visualizza stato stampante e coda",apiPermissionEdit:"Aggiungi e rimuovi elementi dalla coda di stampa",apiKeysEmptyTitle:"Nessuna chiave API",apiKeysEmptyDescription:"Crea una chiave API per integrare servizi esterni.",noUsersFound:"Nessun utente trovato",noGroupsFound:"Nessun gruppo trovato",noGroupsAvailable:"Nessun gruppo disponibile",passwordsDoNotMatch:"Le password non coincidono",systemGroupWarning:"I nomi dei gruppi di sistema non possono essere modificati",authDisabledTitle:"Autenticazione disabilitata",authDisabledFeature1:"Richiedi accesso per usare il sistema",authDisabledFeature2:"Crea più utenti con permessi basati sui gruppi",authDisabledFeature3:"Controlla accesso con 50+ permessi granulari",userHasCreated:"Questo utente ha creato:",userItemsQuestion:"Cosa vuoi fare con questi elementi?",deleteUserConfirm:"Sei sicuro di voler eliminare questo utente?",actionCannotBeUndone:"Questa azione non può essere annullata.",addFirstSmartPlug:"Aggiungi la tua prima presa smart",providers:"Provider",log:"Log",testAll:"Testa tutto",testResults:"Risultati test",testPassedCount:"{{count}} riusciti",testFailedCount:"{{count}} falliti",messageTemplates:"Template messaggi",messageTemplatesDescription:"Personalizza i messaggi per ogni evento.",apiKeys:"Chiavi API",apiKeysDescription:"Crea chiavi API per integrazioni esterne e webhook.",createKey:"Crea chiave",apiKeyCreated:"Chiave API creata con successo",apiKeyCopyWarning:"Copia questa chiave ora - non verra mostrata di nuovo!",useInApiBrowser:"Usa nel Browser API",createNewApiKey:"Crea nuova chiave API",keyName:"Nome chiave",keyNamePlaceholder:"es., Home Assistant, OctoPrint",readStatus:"Leggi stato",readStatusDescription:"Visualizza stato stampante e coda",manageQueue:"Gestisci coda",manageQueueDescription:"Aggiungi e rimuovi elementi dalla coda di stampa",controlPrinter:"Controlla stampante",controlPrinterDescription:"Metti in pausa, riprendi e ferma stampe",unnamedKey:"Chiave senza nome",lastUsed:"Ultimo uso",read:"Lettura",control:"Controllo",createFirstKey:"Crea la tua prima chiave",webhookEndpoints:"Endpoint webhook",webhookApiKeyHint:"Usa la tua chiave API nell'header X-API-Key.",webhook:{getAllStatus:"Ottieni stato di tutte le stampanti",getSpecificStatus:"Ottieni stato di una stampante",addToQueue:"Aggiungi alla coda di stampa",pausePrint:"Metti in pausa stampa",resumePrint:"Riprendi stampa",stopPrint:"Ferma stampa"},apiBrowser:"Browser API",apiBrowserDescription:"Esplora e testa tutti gli endpoint API disponibili.",apiKeyForTesting:"Chiave API per test",apiKeyPlaceholder:"Incolla qui la tua chiave API per testare gli endpoint autenticati...",apiKeyHint:"Questa chiave verra inviata come header X-API-Key.",deleteApiKeyTitle:"Elimina chiave API",deleteApiKeyMessage:"Sei sicuro di voler eliminare questa chiave API? Le integrazioni che la usano non funzioneranno più.",deleteKey:"Elimina chiave",amsDisplayThresholds:"Soglie visualizzazione AMS",amsThresholdsDescription:"Configura soglie colore per umidità e temperatura AMS.",humidity:"Umidità",goodGreen:"Buono (verde)",fairOrange:"Discreto (arancione)",aboveFairBad:"Sopra soglia discreta mostra rosso (scarso)",temperature:"Temperatura",goodBlue:"Buono (blu)",aboveFairHot:"Sopra soglia discreta mostra rosso (caldo)",historyRetention:"Conservazione cronologia",keepSensorHistory:"Mantieni cronologia sensori per",historyRetentionDescription:"I dati più vecchi saranno eliminati automaticamente",printModal:"Modale stampa",expandCustomMapping:"Espandi mapping personalizzato di default",expandCustomMappingDescription:"Quando stampi su più stampanti, mostra mapping AMS per stampante espanso",authentication:"Autenticazione",authEnabledDescription:"La tua istanza è protetta con autenticazione",authDisabledDescription:"Abilita per richiedere accesso e gestire utenti",authDisabledMessage:"Abilita autenticazione per creare account, gestire permessi e proteggere la tua istanza Bambuddy.",enableAuthentication:"Abilita autenticazione",currentUser:"Utente corrente",changePassword:"Cambia password",admin:"Admin",users:"Utenti",addUser:"Aggiungi utente",groups:"Gruppi",addGroup:"Aggiungi gruppo",system:"Sistema",noDescription:"Nessuna descrizione",userCount:"{{count}} utenti",permissionCount:"{{count}} permessi",createUser:"Crea utente",username:"Nome utente",enterUsername:"Inserisci nome utente",password:"Password",enterPassword:"Inserisci password (min 6 caratteri)",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password",viewReleaseOnGitHub:"Vedi release su GitHub",turnAllPlugsOn:"Accendi tutte le prese",turnAllPlugsOff:"Spegni tutte le prese",clearNotificationLogs:"Cancella log notifiche",clearLogsMessage:"Questo eliminerà definitivamente tutti i log notifiche più vecchi di 30 giorni. Questa azione non può essere annullata.",clearLogs:"Cancella log",resetUiPreferences:"Reimposta preferenze UI",resetUiPreferencesMessage:"Questo reimposterà le preferenze UI ai valori predefiniti: ordine barra laterale, tema, layout dashboard, modalità vista e preferenze ordinamento. Stampanti, archivi e impostazioni server NON saranno modificati. La pagina si ricaricherà dopo la cancellazione.",resetPreferences:"Reimposta preferenze",deleteGroupTitle:"Elimina gruppo",deleteGroupMessage:"Sei sicuro di voler eliminare questo gruppo? Gli utenti in questo gruppo perderanno questi permessi.",deleteGroup:"Elimina gruppo",disableAuthenticationTitle:"Disabilita autenticazione",disableAuthenticationMessage:"Sei sicuro di voler disabilitare l'autenticazione? Questo renderà la tua istanza Bambuddy accessibile senza login. Tutti gli utenti resteranno nel database ma l'autenticazione sarà disabilitata.",disableAuthentication:"Disabilita autenticazione",configureBambuddy:"Configura Bambuddy",systemDefault:"Predefinito di sistema",archiveSettings:"Impostazioni archivio",newWindow:"Nuova finestra",embeddedOverlay:"Overlay incorporato",preferredSlicer:"Slicer preferito",preferredSlicerDescription:"Scegli quale applicazione slicer usare per aprire i file",externalCameras:"Camere esterne",costTracking:"Tracciamento costi",printsOnly:"Solo stampe",totalConsumption:"Consumo totale",dataManagement:"Gestione dati",storageUsage:"Memoria utilizzata",storageUsageDescription:"Ripartizione della memoria per categoria",storageUsageTotal:"Totale",storageUsageErrors:"Errori",storageUsageOtherBreakdown:"Altro (include risorse statiche, script e file di configurazione)",storageUsageSystem:"Sistema",storageUsageData:"Dati",storageUsageUnavailable:"Informazioni sull'utilizzo della memoria non disponibili",clearNotificationLogsDescription:"Elimina log notifiche più vecchi di 30 giorni",resetUiPreferencesDescription:"Reimposta ordine barra laterale, tema, modalità vista e preferenze layout. Stampanti, archivi e impostazioni non vengono modificati.",enableHomeAssistant:"Abilita Home Assistant",enableMqtt:"Abilita MQTT",useTls:"Usa TLS",enableMetricsEndpoint:"Abilita endpoint metriche",availableMetrics:"Metriche disponibili",editUser:"Modifica utente",deleteUserTitle:"Elimina utente",groupName:"Nome gruppo",leaveEmptyForAnonymous:"Lascia vuoto per anonimo",leaveEmptyForNoAuth:"Lascia vuoto per nessuna autenticazione",enterNewPassword:"Inserisci nuova password",confirmNewPassword:"Conferma nuova password",enterGroupName:"Inserisci nome gruppo",enterDescriptionOptional:"Inserisci descrizione (opzionale)",enterCurrentPassword:"Inserisci password attuale",enterNewPasswordMin6:"Inserisci nuova password (min 6 caratteri)",toast:{keyCopied:"Chiave copiata negli appunti",copyFailed:"Copia chiave fallita",keyAddedToBrowser:"Chiave aggiunta al Browser API",clearLogsFailed:"Eliminazione log fallita",uiPreferencesReset:"Preferenze UI reimpostate. Aggiornamento...",authDisabled:"Autenticazione disabilitata con successo",authDisableFailed:"Disabilitazione autenticazione fallita",apiKeyCreated:"Chiave API creata",apiKeyDeleted:"Chiave API eliminata",userCreated:"Utente creato con successo",userUpdated:"Utente aggiornato con successo",userDeleted:"Utente eliminato con successo",groupCreated:"Gruppo creato con successo",groupUpdated:"Gruppo aggiornato con successo",groupDeleted:"Gruppo eliminato con successo",fillRequiredFields:"Compila tutti i campi obbligatori",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri",enterGroupName:"Inserisci un nome gruppo",settingsSaved:"Impostazioni salvate",cameraSettingsSaved:"Impostazioni camera salvate",enterCameraUrl:"Inserisci un URL camera",passwordChanged:"Password cambiata con successo",connectionFailed:"Connessione fallita",testFailed:"Test fallito",cameraConnected:"Camera connessa{{resolution}}"},testConnection:"Testa connessione"},notification:{printStarted:{title:"Stampa avviata",body:"{{printer}}: {{filename}} ha iniziato a stampare"},printCompleted:{title:"Stampa completata",body:"{{printer}}: {{filename}} completata con successo"},printFailed:{title:"Stampa fallita",body:"{{printer}}: {{filename}} fallita"},printStopped:{title:"Stampa interrotta",body:"{{printer}}: {{filename}} interrotta"},printProgress:{title:"Avanzamento stampa",body:"{{printer}}: {{filename}} al {{percent}}% completamento"},printerOffline:{title:"Stampante offline",body:"{{printer}} e offline"},printerError:{title:"Errore stampante",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filamento in esaurimento",body:"{{printer}}: Filamento in esaurimento"},maintenanceDue:{title:"Manutenzione dovuta",body:"{{printer}}: {{items}} richiedono attenzione"}},errors:{generic:"Qualcosa e andato storto",networkError:"Errore di rete. Controlla la connessione.",notFound:"Non trovato",unauthorized:"Non autorizzato",serverError:"Errore server",validationError:"Controlla i dati inseriti",printerConnectionFailed:"Connessione alla stampante fallita",saveFailed:"Salvataggio modifiche fallito",deleteFailed:"Eliminazione fallita",loadFailed:"Caricamento dati fallito"},hmsErrors:{title:"Errori - {{name}}",noErrors:"Nessun errore",viewOnWiki:"Vedi su Bambu Lab Wiki",clearInstructions:"Cancella gli errori sulla stampante per rimuoverli qui.",clearErrors:"Cancella errori",clearSuccess:"Errori HMS cancellati",clearFailed:"Impossibile cancellare gli errori HMS"},mqttDebug:{title:"Log debug MQTT",searchPlaceholder:"Cerca topic o payload...",noMessages:"Nessun messaggio registrato",startLoggingHint:'Clicca "Avvia logging" per iniziare a catturare messaggi MQTT',noMessagesMatch:"Nessun messaggio corrisponde al filtro",adjustFilterHint:"Prova a modificare la ricerca o i filtri",incoming:"In ingresso",outgoing:"In uscita",loggingStopped:"Logging fermato",loggingActive:"Logging attivo - i messaggi si aggiornano automaticamente",startLogging:"Avvia logging",stopLogging:"Ferma logging",clearLog:"Pulisci log",topic:"Topic",timestamp:"Timestamp",direction:"Direzione",all:"Tutti"},printerFiles:{title:"Gestore file",storageUsed:"Usato:",storageFree:"Libero:",filterPlaceholder:"Filtra file...",deleteButton:"Elimina",deleteFiles:"Elimina {{count}} file",deleteFileConfirm:'Eliminare "{{name}}"? Questa azione non può essere annullata.',deleteFilesConfirm:"Eliminare {{count}} file selezionati? Questa azione non può essere annullata.",noFiles:"Nessun file sulla stampante",loadingFiles:"Caricamento file...",failedToLoad:"Caricamento file fallito",toast:{filesDeleted:"Eliminati {{count}} file",deleteFailed:"Eliminazione fallita: {{error}}"}},confirm:{delete:"Sei sicuro di voler eliminare questo?",unsavedChanges:"Hai modifiche non salvate. Sei sicuro di voler uscire?",clearQueue:"Sei sicuro di voler svuotare la coda?"},login:{title:"Login Bambuddy",subtitle:"Accedi al tuo account",username:"Nome utente",usernamePlaceholder:"Inserisci il nome utente",password:"Password",passwordPlaceholder:"Inserisci la password",signIn:"Accedi",signingIn:"Accesso in corso...",forgotPassword:"Hai dimenticato la password?",loginSuccess:"Accesso riuscito",loginFailed:"Accesso fallito",enterCredentials:"Inserisci nome utente e password",forgotPasswordTitle:"Password dimenticata",forgotPasswordMessage:"Se hai dimenticato la password, contatta il tuo amministratore di sistema per reimpostarla.",howToReset:"Come reimpostare la password:",resetStep1:"Contatta il tuo amministratore Bambuddy",resetStep2:"Chiedi di reimpostare la password in Gestione utenti",resetStep3:"Possono impostare una nuova password temporanea",resetStep4:"Accedi con la nuova password e cambiala in Impostazioni",gotIt:"Capito"},setup:{title:"Configurazione Bambuddy",subtitle:"Configura autenticazione per la tua istanza Bambuddy",enableAuth:"Abilita autenticazione",adminAccount:"Account admin",adminAccountDesc:"Se esistono già admin, l'autenticazione verrà abilitata usando gli account esistenti. Lascia i campi sotto vuoti per usare gli admin esistenti, oppure inserisci nuove credenziali per creare un nuovo utente admin.",adminUsername:"Nome utente admin",adminPassword:"Password admin",optionalIfAdminExists:"(opzionale se esistono admin)",adminUsernamePlaceholder:"Inserisci nome utente admin (opzionale)",adminPasswordPlaceholder:"Inserisci password admin (opzionale)",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password admin",settingUp:"Configurazione...",completeSetup:"Completa configurazione",toast:{authEnabledAdminCreated:"Autenticazione abilitata e utente admin creato",authEnabledExistingAdmins:"Autenticazione abilitata usando admin esistenti",setupCompleted:"Configurazione completata",enterBothCredentials:"Inserisci nome utente e password admin, oppure lascia entrambi vuoti per usare admin esistenti",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri"}},changePassword:{title:"Cambia password",currentPassword:"Password attuale",currentPasswordPlaceholder:"Inserisci password attuale",newPassword:"Nuova password",newPasswordPlaceholder:"Inserisci nuova password (min 6 caratteri)",confirmPassword:"Conferma nuova password",confirmPasswordPlaceholder:"Conferma nuova password",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri",changing:"Modifica in corso...",success:"Password cambiata con successo",failed:"Modifica password fallita"},plateAlert:{title:"Stampa in pausa!",message:"Oggetti rilevati sul piatto. La stampa è stata messa automaticamente in pausa. Svuota il piatto e riprendi la stampa.",understand:"Ho capito"},camera:{title:"Vista camera",invalidPrinterId:"ID stampante non valido",live:"Live",snapshot:"Snapshot",restartStream:"Riavvia stream",refreshSnapshot:"Aggiorna snapshot",fullscreen:"Schermo intero",exitFullscreen:"Esci da schermo intero",connectingToCamera:"Connessione alla camera...",capturingSnapshot:"Acquisizione snapshot...",connectionLost:"Connessione persa",connectionFailed:"Connessione camera fallita",reconnecting:"Riconnessione tra {{countdown}}s... (tentativo {{attempt}}/{{max}})",reconnectNow:"Riconnetti ora",cameraUnavailable:"Camera non disponibile",cameraUnavailableDesc:"Assicurati che la stampante sia accesa e connessa.",noCamera:"Nessuna camera disponibile",retry:"Riprova",cameraStream:"Stream camera",zoomOut:"Zoom indietro",zoomIn:"Zoom avanti",resetZoom:"Reset zoom",recording:"Registrazione",startRecording:"Avvia registrazione",stopRecording:"Ferma registrazione",chamberLight:"Accendi/Spegni luce camera"},groups:{title:"Gestione gruppi",subtitle:"Gestisci gruppi permessi per controllo accesso",backToSettings:"Torna a Impostazioni",createGroup:"Crea gruppo",noPermission:"Non hai il permesso di accedere a questa pagina.",system:"Sistema",noDescription:"Nessuna descrizione",usersCount:"{{count}} utenti",permissionsCount:"{{count}} permessi",edit:"Modifica",delete:"Elimina",toast:{created:"Gruppo creato con successo",updated:"Gruppo aggiornato con successo",deleted:"Gruppo eliminato con successo",enterGroupName:"Inserisci un nome gruppo"},modal:{editGroup:"Modifica gruppo",createGroup:"Crea gruppo",cancel:"Annulla",saving:"Salvataggio...",creating:"Creazione...",saveChanges:"Salva modifiche"},form:{groupName:"Nome gruppo",groupNamePlaceholder:"Inserisci nome gruppo",systemGroupWarning:"I nomi dei gruppi di sistema non possono essere modificati",description:"Descrizione",descriptionPlaceholder:"Inserisci descrizione (opzionale)",permissions:"Permessi ({{count}} selezionati)"},deleteModal:{title:"Elimina gruppo",message:"Sei sicuro di voler eliminare questo gruppo? Gli utenti in questo gruppo perderanno questi permessi.",confirm:"Elimina gruppo"},editor:{title:"Modifica gruppo",createTitle:"Crea gruppo",search:"Cerca permessi...",selectAll:"Seleziona tutto",clearAll:"Deseleziona tutto",permissionsSelected:"{{count}} selezionati",noResults:"Nessun permesso corrisponde alla ricerca"}},users:{title:"Gestione utenti",subtitle:"Gestisci utenti e accesso alla tua istanza Bambuddy",backToSettings:"Torna a Impostazioni",createUser:"Crea utente",noPermission:"Non hai il permesso di accedere a questa pagina.",admin:"Admin",noGroups:"Nessun gruppo",active:"Attivo",inactive:"Inattivo",edit:"Modifica",delete:"Elimina",system:"Sistema",noGroupsAvailable:"Nessun gruppo disponibile",table:{username:"Nome utente",groups:"Gruppi",status:"Stato",actions:"Azioni"},toast:{created:"Utente creato con successo",updated:"Utente aggiornato con successo",deleted:"Utente eliminato con successo",fillRequired:"Compila tutti i campi obbligatori",passwordsDoNotMatch:"Le password non coincidono",passwordTooShort:"La password deve essere di almeno 6 caratteri"},modal:{createUser:"Crea utente",editUser:"Modifica utente",cancel:"Annulla",creating:"Creazione...",saving:"Salvataggio...",saveChanges:"Salva modifiche"},form:{username:"Nome utente",usernamePlaceholder:"Inserisci nome utente",password:"Password",passwordPlaceholder:"Inserisci password",confirmPassword:"Conferma password",confirmPasswordPlaceholder:"Conferma password",newPasswordPlaceholder:"Inserisci nuova password",confirmNewPasswordPlaceholder:"Conferma nuova password",leaveBlankToKeep:"lascia vuoto per mantenere attuale",groups:"Gruppi"},deleteModal:{title:"Elimina utente",message:"Sei sicuro di voler eliminare questo utente? Questa azione non può essere annullata.",confirm:"Elimina utente"}},streamOverlay:{title:"Overlay stream",invalidPrinterId:"ID stampante non valido",cameraStream:"Stream camera",progress:"Avanzamento",eta:"ETA",printerIdle:"Stampante inattiva",printerOffline:"Stampante offline",status:{printing:"In stampa",paused:"In pausa",finished:"Completata",failed:"Fallita",idle:"Inattiva",unknown:"Sconosciuto"}},profiles:{title:"Profili",subtitle:"Gestisci preset slicer e calibrazioni pressure advance",tabs:{cloud:"Profili cloud",local:"Profili locali",kprofiles:"K-Profiles"},localProfiles:{title:"Profili locali",subtitle:"Importa e gestisci preset slicer da OrcaSlicer",import:"Importa profili",importDesc:"Trascina file .bbscfg, .bbsflmt, .orca_filament, .zip o .json qui",importing:"Importazione...",search:"Cerca preset locali...",noPresets:"Nessun preset locale ancora",badge:"Locale",edit:"Modifica",delete:"Elimina",cancel:"Annulla",deleteConfirmTitle:"Elimina preset",deleteConfirm:"Sei sicuro di voler eliminare questo preset? Questa azione non può essere annullata.",source:"Fonte",inheritsFrom:"Eredita da",filamentType:"Tipo",vendor:"Produttore",compatiblePrinters:"Stampanti",nozzleTemp:"Temp. ugello",cost:"Costo",density:"Densità",pressureAdvance:"Pressure Advance",filament:"Filamento",process:"Processo",printer:"Stampante",toast:{importSuccess:"{{count}} preset importati",importSkipped:"{{count}} preset saltati (duplicati)",importError:"{{count}} errori durante l'importazione",deleted:"Preset eliminato",updated:"Preset aggiornato"}},connectedAs:"Connesso come",logout:"Esci",noLogoutPermission:"Non hai il permesso di disconnetterti",failedToLoad:"Caricamento profili fallito",retry:"Riprova",time:{justNow:"Proprio ora",minsAgo:"{{count}}m fa",hoursAgo:"{{count}}h fa",daysAgo:"{{count}}g fa"},toast:{loggedOut:"Disconnesso"},login:{title:"Connetti a Bambu Cloud",subtitle:"Sincronizza i preset del slicer tra dispositivi",email:"Email",password:"Password",region:"Regione",regionGlobal:"Globale",regionChina:"Cina",verificationCode:"Codice di verifica",totpCode:"Codice autenticatore",checkEmail:"Controlla la tua email ({{email}}) per un codice a 6 cifre",enterTotpHint:"Inserisci il codice a 6 cifre dalla tua app autenticatore",accessToken:"Access Token",accessTokenHint:"Incolla il tuo access token Bambu Lab (da Bambu Studio)",back:"Indietro",loginButton:"Accedi",verifyButton:"Verifica",setTokenButton:"Imposta token",useToken:"Usa access token invece",useEmail:"Accedi con email invece",toast:{loggedIn:"Accesso riuscito",codeSent:"Codice di verifica inviato via email",enterTotp:"Inserisci il codice dalla tua app autenticatore",tokenSet:"Token impostato con successo"}},presets:{myPreset:"Il mio preset (modificabile)",duplicate:"Duplica",editable:"Modificabile",failedToLoadDetails:"Caricamento dettagli preset fallito",deleteConfirm:"Eliminare questo preset?",deleteWarning:'Questo eliminerà definitivamente "{{name}}" da Bambu Cloud. Questa azione non può essere annullata.',noDuplicatePermission:"Non hai il permesso di duplicare preset",noEditPermission:"Non hai il permesso di modificare preset",noDeletePermission:"Non hai il permesso di eliminare preset",types:{filament:"Preset filamento",printer:"Preset stampante",process:"Preset processo"},toast:{deleted:"Preset eliminato",created:"Preset creato",updated:"Preset aggiornato",duplicated:"Preset duplicato",fieldAdded:'Campo "{{key}}" aggiunto',exported:"Preset esportato"},baseLabel:"Base: {{name}}",currentLabel:"Corrente: {{name}}",newPreset:"Nuovo preset",editPreset:"Modifica preset",duplicatePreset:"Duplica preset",createNewPreset:"Crea nuovo preset",customizeSettings:"Personalizza le impostazioni per il nuovo preset",compareWithBase:"Confronta con base",compare:"Confronta",basePreset:"Preset base",selectBasePreset:"Seleziona preset base...",presetName:"Nome preset",myCustomPreset:"Il mio preset personalizzato",inheritsFrom:"Deriva da",dropJsonToImport:"Rilascia JSON per importare",tabs:{common:"Comune",allFields:"Tutti i campi"},availableFields:"Campi disponibili",searchFieldsPlaceholder:"Cerca campi...",noMatchingFields:"Nessun campo corrispondente",allFieldsAdded:"Tutti i campi aggiunti",addCustomField:"Aggiungi campo personalizzato",yourOverrides:"Le tue override",noOverridesYet:"Nessun override ancora",clickFieldsToAdd:"Clicca i campi a sinistra per aggiungerli",saveAsTemplate:"Salva come template",jsonTip:"Suggerimento: trascina e rilascia un file .json ovunque in questa modale per importare impostazioni"},cloudView:{searchPlaceholder:"Cerca preset...",templates:"Template",refresh:"Aggiorna",newPreset:"Nuovo preset",clearFilters:"Pulisci filtri",compareMode:"Modalita confronto",selectAnotherPreset:"Seleziona un altro preset {{type}}",clickTwoPresets:"Clicca due preset dello stesso tipo per confrontare",selectFirst:"1. Seleziona il primo",selectSecond:"2. Seleziona il secondo",compareNow:"Confronta ora",lastSynced:"Ultima sincronizzazione:",showingCount:"Mostrati {{showing}} di {{total}} preset",noPresetsFound:"Nessun preset trovato",columns:{filament:"Filamento",process:"Processo",printer:"Stampante"},noFilamentPresets:"Nessun preset filamento",noProcessPresets:"Nessun preset processo",noPrinterPresets:"Nessun preset stampante",filters:{type:"Tipo",owner:"Proprietario",printer:"Stampante",nozzle:"Ugello",filament:"Filamento",layer:"Layer",all:"Tutti",myPresets:"I miei preset",builtIn:"Integrati",process:"Processo"},noTemplatesPermission:"Non hai il permesso di gestire i template",noRefreshPermission:"Non hai il permesso di aggiornare i profili",noCreatePermission:"Non hai il permesso di creare preset"},templates:{title:"Template rapidi",noTemplates:"Nessun template ancora",createFirst:"Crea template dall'editor preset",typeFilter:"Tipo:",deleteTitle:"Elimina template",deleteWarning:"Questa azione non può essere annullata",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',namePlaceholder:"Nome template",descriptionPlaceholder:"Descrizione",settingsJson:"Impostazioni (JSON)",fieldsCount:"{{count}} campi",shownInModals:"Mostrati nelle modali",hiddenInModals:"Nascosti nelle modali",apply:"Applica",toast:{deleted:"Template eliminato",updated:"Template aggiornato",created:"Template creato",applied:"Template applicato"}}},support:{debugLoggingActive:"Log debug attivo",manageLogs:"Gestisci",collectItem7:"Connettività stampante e versioni firmware",collectItem8:"Stato integrazioni (Spoolman, MQTT, HA)",collectItem9:"Interfacce di rete (solo subnet)",collectItem10:"Versioni dei pacchetti Python",collectItem11:"Controlli di integrità del database",collectItem12:"Dettagli dell'ambiente Docker"},fileManager:{title:"Gestore file",subtitle:"Organizza e gestisci i tuoi file di stampa",uploadFiles:"Carica file",newFolder:"Nuova cartella",folderName:"Nome cartella",folderNamePlaceholder:"es., Parti funzionali",renameFile:"Rinomina file",renameFolder:"Rinomina cartella",moveFiles:"Sposta {{count}} file",rootNoFolder:"Root (nessuna cartella)",current:"corrente",linkFolder:"Collega cartella",linkFolderDescription:'Collega "{{name}}" a un progetto o archivio per accesso rapido.',project:"Progetto",archive:"Archivio",noProjectsFound:"Nessun progetto trovato",noArchivesFound:"Nessun archivio trovato",unlink:"Scollega",link:"Collega",dragDropFiles:"Trascina e rilascia file qui",dropFilesHere:"Rilascia file qui",orClickToBrowse:"oppure clicca per sfogliare",allFileTypesSupported:"Tutti i tipi di file supportati. I file ZIP saranno estratti.",zipFilesDetected:"File ZIP rilevati",zipExtractOptions:"I file ZIP saranno estratti. Scegli come gestire la struttura cartelle:",preserveZipStructure:"Mantieni struttura cartelle dal ZIP",createFolderFromZip:"Crea cartella dal nome ZIP",stlThumbnailGeneration:"Generazione miniature STL",zipMayContainStl:"I file ZIP possono contenere STL. Le miniature possono essere generate durante l'estrazione.",thumbnailsCanBeGenerated:"Le miniature possono essere generate per file STL. I modelli grandi possono richiedere più tempo.",generateThumbnailsForStl:"Genera miniature per file STL",threemfDetected:"File 3MF rilevati",threemfExtractionInfo:"Modello stampante, materiale, colore e impostazioni stampa saranno estratti automaticamente dai file 3MF.",willBeExtracted:"Sara estratto",filesExtracted:"{{count}} file estratti",uploadComplete:"Caricamento completato: {{succeeded}} riusciti",uploadFailed:"{{count}} falliti",uploading:"Caricamento...",changeLink:"Cambia collegamento...",linkTo:"Collega a...",linkToProjectOrArchive:"Collega a progetto o archivio",addToQueue:"Aggiungi alla coda",schedulePrint:"Pianifica",generateThumbnail:"Genera miniatura",generateThumbnails:"Genera miniature",generateThumbnailsForMissing:"Genera miniature per STL senza miniatura",gridView:"Vista griglia",listView:"Vista elenco",lowDiskSpaceWarning:"Avviso spazio disco basso",lowDiskSpaceDetails:"Solo {{free}} liberi su {{total}} totali. La soglia e {{threshold}} GB nelle impostazioni.",files:"File",folders:"Cartelle",size:"Dimensione",free:"Libero",allFiles:"Tutti i file",wrap:"A capo",enableTextWrapping:"Abilita a capo testo",disableTextWrapping:"Disabilita a capo testo",dragToResizeTooltip:"Trascina per ridimensionare, doppio clic per reset",searchFiles:"Cerca file...",allTypes:"Tutti i tipi",prints:"Stampe",ascending:"Crescente",descending:"Decrescente",resultsCount:"{{showing}} di {{total}} file",selectAll:"Seleziona tutto",deselectAll:"Deseleziona tutto",selected:"{{count}} selezionati",adding:"Aggiunta...",loadingFiles:"Caricamento file...",folderIsEmpty:"La cartella e vuota",noFilesYet:"Nessun file ancora",folderEmptyDescription:"Carica file o sposta file in questa cartella per iniziare.",noFilesDescription:"Carica file per iniziare a organizzare i file di stampa.",noMatchingFiles:"Nessun file corrispondente",noMatchingFilesDescription:"Nessun file corrisponde ai criteri di ricerca o filtro.",clearFilters:"Pulisci filtri",printedCount:"Stampato {{count}}x",uploadedBy:"Caricato da",deleteFolder:"Elimina cartella",deleteFile:"Elimina file",deleteFilesCount:"Elimina {{count}} file",deleteFolderConfirm:"Sei sicuro di voler eliminare questa cartella? Tutti i file dentro saranno eliminati.",deleteFileConfirm:"Sei sicuro di voler eliminare questo file?",deleteFilesConfirm:"Sei sicuro di voler eliminare {{count}} file selezionati? Questa azione non può essere annullata.",deleting:"Eliminazione...",noPermissionRenameFolder:"Non hai il permesso di rinominare cartelle",noPermissionLinkFolder:"Non hai il permesso di collegare cartelle",noPermissionDeleteFolder:"Non hai il permesso di eliminare cartelle",noPermissionPrint:"Non hai il permesso di stampare",noPermissionAddToQueue:"Non hai il permesso di aggiungere alla coda",noPermissionDownload:"Non hai il permesso di scaricare file",noPermissionRenameFile:"Non hai il permesso di rinominare questo file",noPermissionGenerateThumbnail:"Non hai il permesso di generare miniature",noPermissionDeleteFile:"Non hai il permesso di eliminare questo file",noPermissionCreateFolder:"Non hai il permesso di creare cartelle",noPermissionUpload:"Non hai il permesso di caricare file",noPermissionMoveFiles:"Non hai il permesso di spostare file",noPermissionDeleteFiles:"Non hai il permesso di eliminare file",toast:{folderCreated:"Cartella creata",folderDeleted:"Cartella eliminata",fileDeleted:"File eliminato",filesDeleted:"Eliminati {{count}} file",filesMoved:"File spostati",folderLinked:"Cartella collegata",folderUnlinked:"Cartella scollegata",addedToQueue:"Aggiunti {{count}} file alla coda",addedToQueuePartial:"Aggiunti {{added}} file, {{failed}} falliti",failedToAddToQueue:"Aggiunta file fallita: {{error}}",fileRenamed:"File rinominato",folderRenamed:"Cartella rinominata",thumbnailsGenerated:"Generate {{count}} miniature",thumbnailsGeneratedPartial:"Generate {{succeeded}} miniature, {{failed}} fallite",noStlMissingThumbnails:"Nessun file STL senza miniature",failedToGenerateThumbnails:"Generazione miniature fallita: {{error}}",thumbnailGenerated:"Miniatura generata",failedToGenerateThumbnail:"Generazione miniatura fallita: {{error}}"}},projects:{title:"Progetti",subtitle:"Organizza e traccia i tuoi progetti di stampa 3D",newProject:"Nuovo progetto",editProject:"Modifica progetto",deleteProject:"Elimina progetto",projectName:"Nome progetto",description:"Descrizione",noProjects:"Nessun progetto ancora",noProjectsFiltered:"Nessun progetto {{status}}",noProjectsFilteredHelp:"Non hai progetti {{status}}. I progetti appariranno qui quando il loro stato cambia.",createFirst:"Crea il tuo primo progetto per organizzare stampe correlate, tracciare progressi e gestire i tuoi build.",createFirstButton:"Crea il tuo primo progetto",create:"Crea",files:"File",prints:"Stampe",plates:"piatti",parts:"parti",lastModified:"Ultima modifica",deleteConfirm:"Sei sicuro di voler eliminare questo progetto? Archivi e elementi in coda saranno scollegati ma non eliminati.",addFiles:"Aggiungi file",removeFile:"Rimuovi file",viewDetails:"Vedi dettagli",namePlaceholder:"es., Build Voron 2.4",descriptionPlaceholder:"Descrizione opzionale...",color:"Colore",targetPlates:"Piatti target",targetPlatesPlaceholder:"es., 25",targetPlatesHelp:"Numero di job di stampa",targetParts:"Parti target",targetPartsPlaceholder:"es., 150",targetPartsHelp:"Totale oggetti necessari",tagsLabel:"Tag (separati da virgola)",tagsPlaceholder:"es., voron, funzionale, regalo",dueDate:"Data scadenza",priority:"Priorita",priorityLow:"Bassa",priorityNormal:"Normale",priorityHigh:"Alta",priorityUrgent:"Urgente",statusActive:"Attivo",statusCompleted:"Completato",statusArchived:"Archiviato",done:"Fatto",completed:"completato",failed:"fallito",inQueue:"in coda",noPrintsYet:"Nessuna stampa ancora",printJobs:"Job di stampa (piatti)",partsPrinted:"Parti stampate",failedParts:"Parti fallite",import:"Importa",export:"Esporta",importProject:"Importa progetto",exportAll:"Esporta tutti i progetti",loading:"Caricamento progetti...",noEditPermission:"Non hai il permesso di modificare progetti",noDeletePermission:"Non hai il permesso di eliminare progetti",noCreatePermission:"Non hai il permesso di creare progetti",noImportPermission:"Non hai il permesso di importare progetti",noExportPermission:"Non hai il permesso di esportare progetti",toast:{created:"Progetto creato",updated:"Progetto aggiornato",deleted:"Progetto eliminato",imported:"Progetto importato",multipleImported:"{{count}} progetti importati",importFailed:"Import fallito",exported:"Progetti esportati (solo metadati)"}},projectDetail:{notFound:"Progetto non trovato",backToProjects:"Torna a Progetti",export:"Esporta",exportProject:"Esporta progetto",noExportPermission:"Non hai il permesso di esportare progetti",noEditPermission:"Non hai il permesso di modificare progetti",partOf:"Parte di:",priorityLabel:"Priorita:",noPrints:"Nessuna stampa in questo progetto ancora",status:{active:"Attivo",completed:"Completato",archived:"Archiviato"},priority:{low:"Bassa",normal:"Normale",high:"Alta",urgent:"Urgente"},dueDate:{overdue:"Scaduto",today:"Scade oggi",daysLeft:"{{count}} giorni rimanenti"},progress:{platesProgress:"Avanzamento piatti",partsProgress:"Avanzamento parti",printJobs:"job di stampa",parts:"parti",percentComplete:"{{percent}}% completato",remaining:"{{count}} rimanenti"},stats:{printJobs:"Job di stampa",total:"totale",failed:"{{count}} falliti",partsPrinted:"{{count}} parti stampate",printTime:"Tempo di stampa",filamentUsed:"Filamento usato"},cost:{title:"Tracciamento costi",filamentCost:"Costo filamento",energy:"Energia",budget:"Budget",remaining:"Rimanente"},subProjects:{title:"Sotto-progetti ({{count}})"},notes:{title:"Note",noEditPermission:"Non hai il permesso di modificare le note",placeholder:"Aggiungi note su questo progetto...",empty:"Nessuna nota ancora. Clicca Modifica per aggiungere note."},files:{title:"File",linkFolders:"Collega cartelle dal Gestore file",forQuickAccess:"a questo progetto per accesso rapido.",fileCount:"{{count}} file",empty:"Nessuna cartella collegata. Vai a Gestore file e collega una cartella a questo progetto."},bom:{title:"Distinta materiali",acquired:"{{completed}}/{{total}} acquisiti",showAll:"Mostra tutti",hideDone:"Nascondi completati",addPart:"Aggiungi parte",noAddPermission:"Non hai il permesso di aggiungere parti",partNamePlaceholder:"Nome parte (es., viti M3x8)",partName:"Nome parte",qty:"Qta",price:"Prezzo ({{currency}})",sourcingUrlPlaceholder:"URL fornitura (opzionale)",remarksPlaceholder:"Note (opzionale)",deletePart:"Elimina parte",deleteConfirm:'Sei sicuro di voler eliminare "{{name}}"?',noUpdatePermission:"Non hai il permesso di aggiornare parti",noEditPermission:"Non hai il permesso di modificare parti",noDeletePermission:"Non hai il permesso di eliminare parti",totalCost:"Costo totale:",empty:"Nessuna parte nella distinta materiali. Aggiungi hardware, elettronica o altri componenti da reperire."},timeline:{title:"Timeline attivita",empty:"Nessuna attivita ancora."},template:{saveAsTemplate:"Salva come template",noCreatePermission:"Non hai il permesso di creare template"},queue:{title:"Coda",viewAll:"Vedi tutto",printing:"{{count}} in stampa",queued:"{{count}} in coda"},prints:{title:"Stampe ({{count}})"},toast:{projectUpdated:"Progetto aggiornato",partAdded:"Parte aggiunta",partRemoved:"Parte rimossa",exportFailed:"Export fallito",projectExported:"Progetto esportato",templateCreated:"Template creato"}},system:{title:"Informazioni sistema",version:"Versione",uptime:"Tempo attivo",cpuUsage:"Uso CPU",memoryUsage:"Uso memoria",diskUsage:"Uso disco",networkInfo:"Info rete",logs:"Log",debugMode:"Modalita debug",enableDebug:"Abilita log debug",disableDebug:"Disabilita log debug",downloadLogs:"Scarica log",clearLogs:"Cancella log",dockerInfo:"Info Docker",containerName:"Nome container",imageName:"Nome immagine",platform:"Piattaforma",architecture:"Architettura"},library:{title:"Libreria filamenti",addFilament:"Aggiungi filamento",editFilament:"Modifica filamento",deleteFilament:"Elimina filamento",vendor:"Produttore",material:"Materiale",color:"Colore",kFactor:"K Factor",temperature:"Temperatura",noFilaments:"Nessun filamento in libreria",deleteConfirm:"Sei sicuro di voler eliminare questo filamento?",importFromPrinter:"Importa da stampante",exportToFile:"Esporta su file"},spoolman:{title:"Integrazione Spoolman",enabled:"Spoolman abilitato",url:"URL Spoolman",connected:"Connesso",disconnected:"Non connesso",testConnection:"Testa connessione",sync:"Sincronizza",syncing:"Sincronizzazione...",lastSync:"Ultima sincronizzazione",linkToSpoolman:"Collega a Spoolman",openInSpoolman:"Apri in Spoolman",unlinkSpool:"Scollega bobina",selectSpool:"Seleziona bobina",noUnlinkedSpools:"Nessuna bobina scollegata disponibile",linkSuccess:"Bobina collegata a Spoolman con successo",linkFailed:"Collegamento bobina fallito",spoolId:"ID bobina",fillSourceLabel:"(Spoolman)",weight:"Peso",remaining:"Rimanente",disableWeightSync:"Disabilita sync peso stimato AMS",disableWeightSyncDesc:"Non aggiornare la capacità rimanente dalle stime AMS. Usalo se preferisci il tracciamento di Spoolman rispetto alle stime AMS. Le nuove bobine useranno comunque la stima AMS come peso iniziale.",reportPartialUsage:"Segnala uso parziale per stampe fallite",reportPartialUsageDesc:"Quando una stampa fallisce o viene annullata, segnala il filamento stimato usato fino a quel punto in base all'avanzamento layer."},inventory:{title:"Inventario Bobine",addSpool:"Aggiungi Bobina",editSpool:"Modifica Bobina",material:"Materiale",selectMaterial:"Seleziona materiale...",subtype:"Sottotipo",brand:"Marchio",searchBrand:"Cerca marchio...",useCustomBrand:'Usa "{{brand}}"',useCustomMaterial:"Usa materiale personalizzato: {{material}}",colorName:"Nome Colore",colorNamePlaceholder:"Jade White, Fire Red...",color:"Colore",hexColor:"Colore Hex",pickColor:"Scegli colore personalizzato",labelWeight:"Peso da Etichetta",coreWeight:"Peso Bobina Vuota",searchSpoolWeight:"Cerca peso bobina...",weightUsed:"Utilizzato",currentWeight:"Peso Rimanente",measuredWeight:"Peso Misurato",costPerKg:"Costo per kg",measuredWeightError:"Il peso misurato deve essere compreso tra {{min}}g e {{max}}g.",slicerFilament:"Filamento Slicer",slicerFilamentName:"Nome Preset Slicer",slicerPreset:"Preset Slicer",searchPresets:"Cerca preset filamento...",selectedPreset:"Selezionato",noPresetsFound:"Nessun preset trovato",tempOverrides:"Override Temperatura",note:"Nota",notePlaceholder:"Eventuali note aggiuntive su questa bobina...",archive:"Archivia",restore:"Ripristina",noSpools:"Ancora nessuna bobina. Aggiungi la tua prima bobina per iniziare.",noManualSpools:"Nessuna bobina aggiunta manualmente disponibile. Aggiungi prima una bobina al tuo inventario.",kProfiles:"K-Profiles",addKProfile:"Aggiungi K-Profile",assignSpool:"Assegna Bobina",unassignSpool:"Scollega",assignSuccess:"Bobina assegnata e slot AMS configurato",assignFailed:"Assegnazione bobina fallita",selectSpool:"Seleziona una bobina da assegnare a questo slot",assigned:"Assegnato",assigning:"Assegnazione...",searchSpools:"Cerca bobine...",allMaterials:"Tutti i Materiali",filterByBrand:"Filtra per marchio...",showArchived:"Mostra archiviate",quickAdd:"Aggiunta rapida (Scorta)",quantity:"Quantità",stock:"Scorta",configured:"Configurata",spoolsCreated:"{{count}} bobine create",spoolCreated:"Bobina creata",spoolUpdated:"Bobina aggiornata",spoolDeleted:"Bobina eliminata",spoolArchived:"Bobina archiviata",spoolRestored:"Bobina ripristinata",deleteConfirm:"Sei sicuro di voler eliminare questa bobina? Questa azione non può essere annullata.",advancedSettings:"Impostazioni Avanzate"},timelapse:{title:"Timelapse",create:"Crea timelapse",download:"Scarica",delete:"Elimina",preview:"Anteprima",frameRate:"Frame rate",quality:"Qualità",processing:"Elaborazione...",noTimelapses:"Nessun timelapse disponibile"},ams:{title:"AMS",slot:"Slot",empty:"Vuoto",emptySlot:"Slot vuoto",unknown:"Sconosciuto",humidity:"Umidità",temperature:"Temperatura",filamentType:"Tipo filamento",filamentColor:"Colore",remaining:"Rimanente",history:"Cronologia AMS",noHistory:"Nessuna cronologia disponibile",configureSlot:"Configura slot",externalSpool:"Bobina esterna",profile:"Profilo",kFactor:"K Factor",fill:"Livello",configure:"Configura",used:"utilizzato",remainingUnit:"rimanente"},printModal:{title:"Avvia stampa",selectPrinter:"Seleziona stampante",selectPlate:"Seleziona piatto",filamentMapping:"Mappatura filamento",totalCost:"Costo totale:",printSettings:"Impostazioni stampa",bedLeveling:"Livellamento piatto",flowCalibration:"Calibrazione flusso",vibrationCalibration:"Calibrazione vibrazioni",layerInspection:"Ispezione primo layer",timelapse:"Timelapse",startPrint:"Avvia stampa",addToQueue:"Aggiungi alla coda",cancel:"Annulla",noPrintersAvailable:"Nessuna stampante disponibile",printerBusy:"Stampante occupata",printerOffline:"Stampante offline",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Ugello sinistro",rightNozzleTooltip:"Ugello destro",filamentOverride:"Sostituzione filamento",filamentOverrideHint:"Sostituisci opzionalmente i filamenti per l'assegnazione basata sul modello. Lo scheduler abbinerà i filamenti selezionati invece dei valori 3MF originali.",originalFilament:"Originale",overrideWith:"Sostituisci con",resetToOriginal:"Ripristina originale"},backup:{title:"Backup e ripristino",createBackup:"Crea backup",restoreBackup:"Ripristina backup",restoreDescription:"Sostituisci tutti i dati da un file di backup",downloadBackup:"Scarica backup",uploadBackup:"Carica backup",lastBackup:"Ultimo backup",autoBackup:"Backup automatico",backupNow:"Esegui backup ora",restoreWarning:"Avviso: il ripristino sovrascriverà tutti i dati attuali.",includeArchives:"Includi archivi",includeSettings:"Includi impostazioni",includeProfiles:"Includi profili",backupSuccess:"Backup creato con successo",restoreSuccess:"Backup ripristinato con successo",backupFailed:"Backup fallito",restoreFailed:"Ripristino fallito",restoreNote:"La stampante virtuale verrà fermata durante il ripristino"},tags:{title:"Tag",addTag:"Aggiungi tag",editTag:"Modifica tag",deleteTag:"Elimina tag",tagName:"Nome tag",tagColor:"Colore tag",noTags:"Nessun tag",deleteConfirm:"Sei sicuro di voler eliminare questo tag?",manageTags:"Gestisci tag"},uploadModal:{title:"Carica file 3MF",dragDrop:"Trascina e rilascia file .3mf qui",or:"o",browseFiles:"Sfoglia file",extractionInfo:"Il modello stampante sarà estratto automaticamente dai metadati del file 3MF.",uploaded:"caricati",failed:"falliti",uploading:"Caricamento...",upload:"Carica",uploadFailed:"Caricamento fallito"},editArchive:{title:"Modifica archivio",name:"Nome",namePlaceholder:"Nome stampa",printer:"Stampante",noPrinter:"Nessuna stampante",project:"Progetto",noProject:"Nessun progetto",itemsPrinted:"Elementi stampati",itemsPrintedHelp:"Numero di elementi prodotti in questo job di stampa",notes:"Note",notesPlaceholder:"Aggiungi note su questa stampa...",externalLink:"Link esterno",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link a Printables, Thingiverse o altra fonte",tags:"Tag",tagsPlaceholder:"Aggiungi tag...",addMoreTags:"Aggiungi altri tag...",matchingTags:'Tag corrispondenti "{{query}}"',existingTags:"Tag esistenti",clickToAdd:"(clicca per aggiungere)",status:"Stato",failureReason:"Motivo fallimento",selectReason:"Seleziona motivo...",photos:"Foto del risultato stampato",photosHelp:"Clicca + per aggiungere foto del risultato stampato",printResult:"Risultato stampa",saving:"Salvataggio...",failureReasons:{adhesionFailure:"Fallimento adesione",spaghettiDetached:"Spaghetti / staccato",layerShift:"Spostamento layer",cloggedNozzle:"Ugello intasato",filamentRunout:"Filamento esaurito",warping:"Warping",stringing:"Stringing",underExtrusion:"Sotto-estrusione",powerFailure:"Mancanza corrente",userCancelled:"Annullato dall'utente",other:"Altro"},statuses:{completed:"Completato",failed:"Fallito",aborted:"Annullato",printing:"In stampa"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Nessuna stampante configurata",addPrinterInSettings:"Aggiungi una stampante in Impostazioni per gestire i K-profiles",noActivePrinters:"Nessuna stampante attiva",enablePrinterConnection:"Abilita una connessione stampante per vedere i K-profiles",loadingProfiles:"Caricamento K-Profiles...",printerOffline:"Stampante offline",printerOfflineDesc:"La stampante selezionata non e connessa. Accendila per vedere i K-profiles.",noMatchingProfiles:"Nessun profilo corrispondente",noMatchingProfilesDesc:"Nessun profilo corrisponde ai criteri di ricerca",noKProfiles:"Nessun K-Profile",noKProfilesDesc:"Nessun profilo pressure advance per ugello da {{diameter}}mm",createFirstProfile:"Crea primo profilo",printer:"Stampante",nozzle:"Ugello",refresh:"Aggiorna",addProfile:"Aggiungi profilo",export:"Esporta",import:"Importa",select:"Seleziona",selectAll:"Seleziona tutto",delete:"Elimina",searchPlaceholder:"Cerca per nome o filamento...",allExtruders:"Tutti gli estrusori",leftOnly:"Solo sinistro",rightOnly:"Solo destro",allFlow:"Tutto flow",hfOnly:"Solo HF",sOnly:"Solo S",sortName:"Ordina: Nome",sortKValue:"Ordina: K-Value",sortFilament:"Ordina: Filamento",leftExtruder:"Estrusore sinistro",rightExtruder:"Estrusore destro",modal:{addTitle:"Aggiungi K-Profile",editTitle:"Modifica K-Profile",profileName:"Nome profilo",profileNamePlaceholder:"Il mio profilo PLA",kValue:"K-Value",kValuePlaceholder:"0.020",kValueHelp:"Intervallo tipico: 0.01 - 0.06 per PLA, 0.02 - 0.10 per PETG",filament:"Filamento",selectFilament:"Seleziona filamento...",noFilamentsHelp:"Nessun filamento trovato. Crea prima un K-profile in Bambu Studio.",flowType:"Tipo flow",highFlow:"High Flow",standard:"Standard",nozzleSize:"Dimensione ugello",extruder:"Estrusore",extruders:"Estrusori",left:"Sinistra",right:"Destra",notes:"Note (salvate localmente)",notesPlaceholder:"Aggiungi note su questo profilo...",notesHelp:"Le note sono salvate in Bambuddy, non sulla stampante",syncing:"Sincronizzazione con stampante...",savingExtruder:"Salvataggio su estrusore {{current}}/{{total}}...",pleaseWait:"Attendere"},deleteConfirm:{title:"Elimina profilo",cannotUndo:"Questo non può essere annullato",message:'Sei sicuro di voler eliminare "{{name}}" dalla stampante?'},bulkDelete:{title:"Elimina profili",cannotUndo:"Questo non può essere annullato",message:"Sei sicuro di voler eliminare {{count}} profili selezionati dalla stampante?"},toast:{profileSaved:"K-profile salvato",profilesSaved:"K-profile salvato su {{count}} estrusori",selectAtLeastOneExtruder:"Seleziona almeno un estrusore",profileDeleted:"K-profile eliminato",profilesDeleted:"Eliminati {{count}} profili",exportedProfiles:"Esportati {{count}} profili",importedProfiles:"Importati {{count}} di {{total}} profili",noProfilesToExport:"Nessun profilo da esportare",invalidFileFormat:"Formato file non valido",failedToParseImport:"Parsing file import fallito",failedToSaveBatch:"Salvataggio K-profiles fallito",noteSaved:"Nota salvata",failedToSaveNote:"Salvataggio nota fallito"},permission:{noRead:"Non hai il permesso di aggiornare i profili",noCreate:"Non hai il permesso di aggiungere profili",noUpdate:"Non hai il permesso di aggiornare K-profiles",noDelete:"Non hai il permesso di eliminare K-profiles",noExport:"Non hai il permesso di esportare profili",noImport:"Non hai il permesso di importare profili"}},virtualPrinter:{title:"Stampante virtuale",running:"In esecuzione",stopped:"Ferma",description:{default:"Abilita una stampante virtuale che appare in Bambu Studio e OrcaSlicer. I file inviati a questa stampante saranno archiviati senza stampare.",proxy:"Abilita un proxy che inoltra il traffico slicer a una stampante reale, permettendo la stampa remota su qualsiasi rete."},enable:{title:"Abilita stampante virtuale",visibleInSlicer:'Visibile come "Bambuddy" nella ricerca slicer',proxyingTo:"In proxy verso {{name}}",notActive:"Non attivo"},model:{title:"Modello stampante",description:"Seleziona il modello stampante da emulare.",restartWarning:"Cambiare il modello riavviera la stampante virtuale"},accessCode:{title:"Codice accesso",isSet:"Codice accesso impostato",notSet:"Nessun codice accesso impostato - richiesto per abilitare",placeholder:"Inserisci codice 8 caratteri",placeholderChange:"Inserisci nuovo codice per cambiare",hint:"Deve essere esattamente 8 caratteri. Usato dagli slicer per autenticarsi.",charCount:"({{count}}/8)"},targetPrinter:{title:"Stampante target",configured:"Target proxy configurato",notConfigured:"Nessuna stampante target selezionata - richiesta per modalita proxy",placeholder:"Seleziona una stampante...",hint:"Seleziona la stampante a cui fare proxy. La stampante deve essere in modalita LAN.",noPrinters:"Nessuna stampante configurata. Aggiungi una stampante per usare la modalita proxy."},remoteInterface:{title:"Sovrascrittura interfaccia di rete",configured:"Sovrascrittura interfaccia attiva",optional:"Opzionale - usare se l'IP rilevato automaticamente e sbagliato (es. piu NIC, Docker, VPN)",placeholder:"Rilevamento automatico (predefinito)...",hint:"Sovrascrive l'indirizzo IP pubblicizzato via SSDP e usato nel certificato TLS. Utile quando Bambuddy ha piu interfacce di rete."},bindIp:{title:"Interfaccia di rete",placeholder:"Seleziona interfaccia...",hint:"Interfaccia di rete a cui questa stampante virtuale si collega. Deve essere unica per stampante."},proxy:{accessCodeHint:"In modalita proxy, usa il codice di accesso della stampante di destinazione nello slicer. La connessione viene inoltrata in modo trasparente alla stampante reale."},mode:{title:"Modalita",archive:"Archivio",archiveDesc:"Archivia subito i file",review:"Revisione",reviewDesc:"Rivedi prima di archiviare",queue:"Coda",queueDesc:"Archivia e aggiungi alla coda",proxy:"Proxy",proxyDesc:"Inoltra a stampante reale"},setupRequired:{title:"Configurazione necessaria",description:"La stampante virtuale richiede configurazioni di sistema aggiuntive prima di funzionare. Include port forwarding, regole firewall e impostazioni specifiche della piattaforma.",readGuide:"Leggi la guida prima di abilitare"},howItWorks:{title:"Come funziona",step1:"Sulla stessa LAN, le stampanti virtuali appaiono automaticamente nel tuo slicer (Bambu Studio / OrcaSlicer). Da altre reti, aggiungile manualmente tramite indirizzo IP e codice di accesso.",step2:'In modalità Archivio, Revisione e Coda, usa il pulsante "Invia" nel tuo slicer per caricare file 3MF su Bambuddy. Lo slicer mostrerà "Stampa riuscita" — il file viene salvato, non stampato.',step3:"In modalità Proxy, la stampante virtuale inoltra tutto il traffico a una stampante reale — le stampe partono immediatamente come con una connessione diretta."},status:{title:"Dettagli stato",printerName:"Nome stampante",model:"Modello",serialNumber:"Numero seriale",mode:"Modalita",pendingFiles:"File in sospeso",targetPrinter:"Stampante target",ftpPort:"Porta FTP",mqttPort:"Porta MQTT",ftpConnections:"Connessioni FTP",mqttConnections:"Connessioni MQTT"},toast:{updated:"Impostazioni stampante virtuale aggiornate",failedToUpdate:"Aggiornamento impostazioni fallito",accessCodeRequired:"Imposta prima un codice accesso",targetPrinterRequired:"Seleziona prima una stampante target",accessCodeEmpty:"Il codice accesso non può essere vuoto",accessCodeLength:"Il codice accesso deve essere esattamente 8 caratteri"}},modelViewer:{openInSlicer:"Apri nello slicer",tabs:{model:"Modello 3D",gcode:"Anteprima G-code"},notAvailable:"non disponibile",notSliced:"non sezionato",plates:"Piatti",allPlates:"Tutti i piatti",plateNumber:"Piatto {{number}}",plateCount:"{{count}} piatto",plateCount_other:"{{count}} piatti",objectCount:"{{count}} oggetto",objectCount_other:"{{count}} oggetti",filamentCount:"{{count}} filamento",filamentCount_other:"{{count}} filamenti",eta:"ETA {{minutes}} min",noPreview:"Nessuna anteprima disponibile per questo file",pagination:{pageOf:"Pagina {{current}} di {{total}}",prev:"Prec",next:"Succ"},errors:{failedToLoad:"Caricamento file fallito",noMeshes:"Nessuna mesh trovata nel file 3MF",unsupportedFormat:"Formato file non supportato"}},maintenanceDescriptions:{lubricateCarbonRods:"Applica lubrificante alle aste in carbonio per un movimento fluido",lubricateRails:"Applica lubrificante alle guide lineari per un movimento fluido",cleanNozzle:"Pulisci hotend e ugello per prevenire intasamenti",checkBelts:"Verifica tensione cinghie per stampe accurate",cleanBuildPlate:"Pulisci il piatto per migliorare l'adesione",checkExtruder:"Ispeziona ingranaggi estrusore per usura",checkCooling:"Assicurati che le ventole di raffreddamento funzionino",generalInspection:"Ispezione generale stampante",cleanCarbonRods:"Pulisci le aste in carbonio per ridurre attrito",cleanLinearRails:"Pulisci le guide lineari per rimuovere polvere e detriti",checkPtfeTube:"Ispeziona il tubo PTFE per usura o danni",replaceHepaFilter:"Sostituisci filtro HEPA per qualità aria",replaceCarbonFilter:"Sostituisci filtro a carbone attivo",lubricateLeftNozzleRail:"Lubrifica guida ugello sinistro (serie H2)"},configureAmsSlot:{title:"Configura Slot AMS",slotConfigured:"Slot configurato!",configuringSlot:"Configurazione slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Cerca preset...",colorPlaceholder:"Nome colore o hex (es. marrone, FF8800)",clearCustomColor:"Cancella colore personalizzato",noCloudPresets:"Nessun preset cloud. Accedi a Bambu Cloud per sincronizzare.",noPresetsAvailable:"Nessun preset disponibile. Accedi a Bambu Cloud o importa profili locali.",noMatchingPresets:"Nessun preset corrispondente trovato.",custom:"Personalizzato",builtin:"Integrato",settingsSentToPrinter:"Impostazioni inviate alla stampante",filamentProfile:"Profilo filamento",kProfileLabel:"Profilo K (Pressure Advance)",filteringFor:"Filtrando per: {{material}}",noKProfile:"Nessun profilo K (usa predefinito 0.020)",noMatchingKProfiles:"Nessun profilo K corrispondente. Verrà usato K=0.020 predefinito.",selectFilamentFirst:"Seleziona prima un profilo filamento",kFromCalibration:"K={{value}} dalla calibrazione stampante",customColorLabel:"Colore personalizzato (opzionale)",presetColors:"Colori {{name}}:",showLessColors:"Mostra meno colori",showMoreColors:"Mostra più colori",clear:"Cancella",hexLabel:"Hex: #{{hex}}",resetting:"Ripristino...",resetSlot:"Ripristina slot",cancel:"Annulla",configuring:"Configurazione...",configureSlot:"Configura slot"},time:{unknown:"-",waiting:"In attesa",justNow:"Proprio ora",now:"Ora",minsAgo:"{{count}}m fa",inMins:"tra {{count}}m",hoursAgo:"{{count}}h fa",inHours:"tra {{count}}h",daysAgo:"{{count}}g fa",inDays:"tra {{count}}g"},spoolbuddy:{nav:{dashboard:"Dashboard",ams:"AMS",inventory:"Inventario",printers:"Stampanti",settings:"Impostazioni"},status:{nfcReady:"Pronto",nfcOff:"Spento",offline:"Dispositivo offline"},dashboard:{idleMessage:"Posiziona la bobina sulla bilancia e scansiona il tag NFC"},weight:{noReading:"Nessuna lettura",stable:"Stabile",measuring:"Misurazione",tare:"Tara",calibrate:"Calibra",tareQueued:"Comando tara inviato"},spool:{remaining:"Rimanente"},tag:{unknownTitle:"Tag sconosciuto",linkExisting:"Collega a bobina esistente",createNew:"Crea nuova bobina"},actions:{assignAms:"Assegna AMS",updateWeight:"Aggiorna peso",editSpool:"Modifica bobina",viewHistory:"Visualizza cronologia",weightUpdated:"Peso bobina aggiornato"},ams:{noData:"Nessun dato AMS disponibile"},inventory:{search:"Cerca bobine...",empty:"Nessuna bobina trovata"},printers:{noPrinters:"Nessuna stampante configurata"},settings:{scaleCalibration:"Calibrazione bilancia",currentWeight:"Peso attuale",tareOffset:"Offset tara",knownWeight:"Peso noto",calibrated:"Calibrazione aggiornata",tareQueued:"Comando tara in coda",nfcReader:"Lettore NFC",nfcConnected:"Connesso",nfcDisconnected:"Disconnesso",deviceInfo:"Info dispositivo",deviceId:"ID dispositivo",uptime:"Tempo di attività",firmware:"Firmware"}}},mce={nav:{printers:"Impressoras",archives:"Arquivos",queue:"Fila",stats:"Estatísticas",profiles:"Perfis",maintenance:"Manutenção",projects:"Projetos",inventory:"Inventário",files:"Gerenciador de Arquivos",settings:"Configurações",system:"Sistema",collapseSidebar:"Recolher barra lateral",expandSidebar:"Expandir barra lateral",update:"Atualizar",updateAvailable:"Atualização disponível: v{{version}}",updateAvailableBanner:"Versão {{version}} está disponível!",viewUpdate:"Ver atualização",viewOnGithub:"Ver no GitHub",keyboardShortcuts:"Atalhos de teclado (?)",switchToLight:"Mudar para modo claro",switchToDark:"Mudar para modo escuro",smartSwitches:"Interruptores inteligentes",logout:"Sair"},common:{save:"Salvar",saving:"Salvando...",cancel:"Cancelar",delete:"Excluir",edit:"Editar",add:"Adicionar",close:"Fechar",confirm:"Confirmar",loading:"Carregando...",error:"Erro",success:"Sucesso",warning:"Aviso",enabled:"Ativado",disabled:"Desativado",yes:"Sim",no:"Não",on:"Ligado",off:"Desligado",all:"Todos",none:"Nenhum",search:"Pesquisar",filter:"Filtrar",sort:"Ordenar",refresh:"Atualizar",download:"Baixar",upload:"Enviar",actions:"Ações",status:"Status",name:"Nome",description:"Descrição",date:"Data",time:"Hora",hours:"Horas",minutes:"Minutos",seconds:"Segundos",days:"Dias",enable:"Ativar",disable:"Desativar",permissions:"Permissões",noPrinters:"Nenhuma impressora configurada",noData:"Nenhum dado disponível",linkNotFound:"Link não encontrado",required:"Obrigatório",optional:"Opcional",dismiss:"Dispensar",apply:"Aplicar",reset:"Redefinir",export:"Exportar",import:"Importar",clear:"Limpar",selectAll:"Selecionar tudo",deselectAll:"Desmarcar tudo",noChange:"— Sem alterações —",unchanged:"Inalterado",unassigned:"Não atribuído",unknown:"Desconhecido",unknownError:"Erro desconhecido",today:"Hoje",tomorrow:"Amanhã",asap:"O mais rápido possível",overdue:"Atrasado",now:"Agora",collapse:"Recolher",expand:"Expandir",viewArchive:"Ver arquivo",viewInFileManager:"Ver no Gerenciador de Arquivos",addedBy:"Adicionado por {{username}}",prints:"impressões",more:"+{{count}} mais",ascending:"Crescente",descending:"Decrescente",printer:"Impressora",remove:"Remover",type:"Tipo",print:"Imprimir",rename:"Renomear",move:"Mover",create:"Criar",duplicate:"Duplicar",left:"Esquerda",right:"Direita"},printers:{title:"Impressoras",addPrinter:"Adicionar Impressora",editPrinter:"Editar Impressora",deletePrinter:"Excluir Impressora",printerName:"Nome da Impressora",serialNumber:"Número de Série",ipAddress:"Endereço IP / Nome do Host",accessCode:"Código de Acesso",model:"Modelo",nozzleCount:"Número de Bicos",autoArchive:"Arquivamento Automático",status:{available:"Disponível",idle:"Ocioso",printing:"Imprimindo",paused:"Pausado",offline:"Offline",error:"Erro",finished:"Concluído",unknown:"Desconhecido"},temperatures:{nozzle:"Bico",bed:"Cama",chamber:"Câmara"},progress:"{{percent}}% concluído",timeRemaining:"{{time}} restante",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',maintenanceOk:"Manutenção OK",maintenanceWarning:"{{count}} aviso",maintenanceWarning_plural:"{{count}} avisos",maintenanceDue:"{{count}} devido",maintenanceDue_plural:"{{count}} devido",sort:{name:"Nome",status:"Status",model:"Modelo",location:"Localização",ascending:"Ordem crescente",descending:"Ordem decrescente"},cardSize:{small:"Cartões pequenos",medium:"Cartões médios",large:"Cartões grandes",extraLarge:"Cartões extra grandes"},hideOffline:"Ocultar offline",nextAvailable:"Próximo disponível",powerOn:"Ligar",offlinePrintersWithPlugs:"Impressoras offline com tomadas inteligentes",noPrintersConfigured:"Nenhuma impressora configurada ainda",readyToPrint:"Pronto para imprimir",external:"Externo",extL:"Ext-L",extR:"Ext-R",deleteArchives:"Excluir arquivos de impressão",noLabel:"Sem etiqueta",printPreview:"Pré-visualização de impressão",width:"Largura",height:"Altura",noObjectsFound:"Nenhum objeto encontrado",objectsLoadedOnPrintStart:"Objetos são carregados quando uma impressão começa",willBeSkipped:"Será ignorado",name:"Nome",serialCannotBeChanged:"Número de série não pode ser alterado",locationHelp:"Usado para agrupar impressoras e filtrar trabalhos na fila",wifiSignal:{veryWeak:"Muito fraco",weak:"Fraco",fair:"Regular",good:"Bom",excellent:"Excelente"},maintenanceUpToDate:"Toda a manutenção está em dia - Clique para ver",chamberLightOn:"Ligar luz da câmara",chamberLightOff:"Desligar luz da câmara",browseFiles:"Procurar arquivos da impressora",autoOffAfterPrint:"Desligamento automático após impressão",autoOffExecuted:"Desligamento automático executado - ligue a impressora para reiniciar",hmsErrors:"Erros HMS",viewHmsErrors:"Ver {{count}} erro(s) HMS",resume:"Retomar",pause:"Pausar",stop:"Parar",camera:"âmera",skipObject:"Ignorar objeto",reconnect:"Reconectar",mqttDebug:"Depuração MQTT",activeNozzle:"Ativo: {{nozzle}} bico",nozzleRack:"Suporte de bicos",nozzleDocked:"Acoplado",nozzleMounted:"Montado",nozzleActive:"Ativo",nozzleIdle:"Ocioso",nozzleDiameter:"Diâmetro",nozzleType:"Tipo",nozzleStatus:"Status",nozzleFilament:"Filamento",nozzleWear:"Desgaste",nozzleMaxTemp:"Temp Máx",nozzleSerial:"Serial",nozzleHardenedSteel:"Aço Endurecido",nozzleStainlessSteel:"Aço Inoxidável",nozzleTungstenCarbide:"Carboneto de Tungstênio",nozzleFlow:"Fluxo",nozzleHighFlow:"Alto Fluxo",nozzleStandardFlow:"Fluxo Padrão",firmwareUpdate:"Atualização de Firmware",firmwareInstructions:"No visor da impressora, vá para",firmwareNav:"Navegar para",settings:"Configurações",firmware:"Firmware",discoverPrinters:"Descobrir Impressoras",searching:"Procurando...",manualEntry:"Entrada Manual",addFromCloud:"Adicionar da Nuvem",toast:{printerDeleted:"Impressora excluída",printerAdded:"Impressora adicionada",printerUpdated:"Impressora atualizada",failedToDelete:"Falha ao excluir impressora",failedToAdd:"Falha ao adicionar impressora",failedToUpdate:"Falha ao atualizar impressora",commandSent:"Comando enviado",failedToSendCommand:"Falha ao enviar comando",turnedOn:"{{name}} ligado",failedToPowerOn:"Falha ao ligar {{name}}",scriptTriggered:"Script acionado",printStopped:"Impressão parada",printPaused:"Impressão pausada",printResumed:"Impressão retomada",referenceDeleted:"Referência excluída",detectionAreaSaved:"Área de detecção salva",failedToRunScript:"Falha ao executar script",failedToStopPrint:"Falha ao parar impressão",failedToPausePrint:"Falha ao pausar impressão",failedToResumePrint:"Falha ao retomar impressão",failedToControlChamberLight:"Falha ao controlar a luz da câmara",failedToUpdateSetting:"Falha ao atualizar configuração",failedToSkipObjects:"Falha ao ignorar objetos",failedToRereadRfid:"Falha ao reler RFID",failedToCheckPlate:"Falha ao verificar a placa",failedToUpdateLabel:"Falha ao atualizar etiqueta",failedToDeleteReference:"Falha ao excluir referência",failedToSaveDetectionArea:"Falha ao salvar área de detecção",plateCheckEnabled:"Verificação da placa ativada",plateCheckDisabled:"Verificação da placa desativada",calibrationSaved:"Calibração salva!",calibrationFailed:"Falha na calibração",rfidRereadInitiated:"Releitura de RFID iniciada"},connection:{connected:"Conectado",offline:"Offline"},queue:{inQueue:"{{count}} impressão na fila",inQueue_plural:"{{count}} impressões na fila"},controls:"Controles",rfid:{reread:"Releitura de RFID"},permission:{noAdd:"Você não tem permissão para adicionar impressoras",noEdit:"Você não tem permissão para editar impressoras",noDelete:"Você não tem permissão para excluir impressoras",noControl:"Você não tem permissão para controlar impressoras",noFiles:"Você não tem permissão para acessar arquivos de impressora",noAmsRfid:"Você não tem permissão para reler RFID AMS",noSmartPlugControl:"Você não tem permissão para controlar tomadas inteligentes"},modal:{addTitle:"Adicionar Impressora",editTitle:"Editar Impressora",myPrinter:"Minha Impressora",selectModel:"Selecionar modelo...",locationGroup:"Localização / Grupo (opcional)",locationPlaceholder:"ex.: Oficina, Escritório, Porão",autoArchiveLabel:"Arquivar automaticamente impressões concluídas",fromPrinterSettings:"A partir das configurações da impressora",modelOptional:"Modelo (opcional)",saveChanges:"Salvar alterações"},skipObjects:{tooltip:"Ignorar objetos",onlyWhilePrinting:"Ignorar objetos (apenas durante a impressão)",requiresMultiple:"Ignorar objetos (requer 2+ objetos)",title:"Ignorar Objetos",matchIdsInfo:"Correspondência de IDs com o display da sua impressora",printerShowsIds:"A tela da impressora mostra os IDs dos objetos na placa de construção",skipSelected:"Ignorar Selecionados",skipping:"Ignorando...",noObjectsSelected:"Nenhum objeto selecionado",selectObjectsToSkip:"Selecione os objetos que deseja ignorar na impressão atual",skipped:"Ignorado",objectsSkipped:"Objetos ignorados",activeCount:"{{count}} ativo",waitForLayer:"Aguarde a camada 2+ para ignorar objetos (atualmente na camada {{layer}})",skip:"Ignorar",confirmTitle:"Ignorar Objeto?",confirmMessage:'Tem certeza de que deseja ignorar "{{name}}"? Isso não pode ser desfeito.'},confirm:{deleteTitle:"Excluir Impressora",deleteMessage:'Tem certeza de que deseja excluir "{{name}}"? Isso removerá todas as configurações de conexão.',deleteArchivesNote:"Todo o histórico de impressão desta impressora será permanentemente excluído.",keepArchivesNote:"O histórico de impressão será mantido, mas não estará mais associado a esta impressora.",stopTitle:"Parar Impressão",stopMessage:'Tem certeza de que deseja parar a impressão atual em "{{name}}"? Isso cancelará o trabalho de impressão.',stopButton:"Parar Impressão",pauseTitle:"Pausar Impressão",pauseMessage:'Tem certeza de que deseja pausar a impressão atual em "{{name}}"?',pauseButton:"Pausar Impressão",resumeTitle:"Retomar Impressão",resumeMessage:'Tem certeza de que deseja retomar a impressão em "{{name}}"?',resumeButton:"Retomar Impressão",powerOnTitle:"Ligar Impressora",powerOnMessage:'Tem certeza de que deseja ligar a impressora "{{name}}"?',powerOnButton:"Ligar",powerOffTitle:"Desligar Impressora",powerOffMessage:'Tem certeza de que deseja desligar a impressora "{{name}}"?',powerOffWarning:'AVISO: "{{name}}" está imprimindo no momento! Tem certeza de que deseja desligar a impressora? Isso interromperá a impressão e pode danificar a impressora.',powerOffButton:"Desligar"},discovery:{title:"Descobrir Impressoras",searching:"Procurando...",scanning:"Escaneando...",scanProgress:"Escaneando... {{scanned}}/{{total}}",foundPrinters:"{{count}} impressora(s) encontrada(s)",noPrintersFound:"Nenhuma impressora encontrada",noPrintersFoundSubnet:"Nenhuma impressora encontrada na sub-rede especificada.",noPrintersFoundNetwork:"Nenhuma impressora encontrada na rede.",allConfigured:"Todas as impressoras descobertas já estão configuradas.",alreadyAdded:"Já adicionada",select:"Selecionar",manualEntry:"Entrada Manual",addFromCloud:"Adicionar da Nuvem",subnetToScan:"Sub-rede para escanear",dockerNote:"Docker detectado. Insira a sub-rede da sua impressora em notação CIDR. Requer network_mode: host no docker-compose.yml.",scanSubnet:"Escanear Sub-rede para Impressoras",discoverNetwork:"Descobrir Impressoras na Rede",scanningSubnet:"Escaneando sub-rede para impressoras Bambu...",scanningNetwork:"Escaneando rede...",serialRequired:"Serial necessário",unknown:"Desconhecido",failedToStart:"Falha ao iniciar a descoberta"},filaments:"Filamentos",openCameraOverlay:"Abrir sobreposição da câmera",openCameraWindow:"Abrir câmera em nova janela",firmwareUpdateAvailable:"Atualização de firmware disponível: {{current}} → {{latest}}",firmwareUpToDate:"Firmware {{version}} — Atualizado",firmwareUpdateButton:"Atualizar",plateDetection:{noPermission:"Você não tem permissão para atualizar impressoras",enabledClick:"Verificação da placa ativada - Clique para desativar",disabledClick:"Verificação da placa desativada - Clique para ativar",manageCalibration:"Gerenciar calibração da detecção da placa",calibrationRequired:"Calibração necessária",calibrationInstructions:"Certifique-se de que a placa de construção esteja <strong>completamente vazia</strong>, em seguida clique em Calibrar.",calibrationDescription:"A calibração captura uma imagem de referência da placa vazia. Verificações futuras compararão com esta referência para detectar objetos.",calibrationTip:"<strong>Dica:</strong> Você pode armazenar até 5 calibrações para diferentes placas. O sistema usa automaticamente a melhor correspondência ao verificar.",plateEmpty:"A placa parece vazia",objectsDetected:"Objetos detectados na placa",confidence:"Confiança",difference:"Diferença",analysisPreview:"Pré-visualização da análise:",analysisLegend:"Caixa verde = área de detecção, Sobreposição vermelha = diferenças em relação à calibração",savedReferences:"Referências salvas ({{count}}/{{max}})",deleteReference:"Excluir referência",labelPlaceholder:"Etiqueta...",clickToEdit:"{{label}} - Clique para editar",clickToAddLabel:"Clique para adicionar etiqueta"},fans:{partCooling:"Ventilador de resfriamento da peça",auxiliary:"Ventilador auxiliar",chamber:"Ventilador da câmara"},clickToViewHmsErrors:"Clique para ver erros do HMS",estimatedCompletion:"Tempo estimado de conclusão",slotOptions:"Opções de slot",firmwareModal:{title:"Atualização de Firmware",titleUpToDate:"Informações do Firmware",currentVersion:"Atual:",latestVersion:"Última:",releaseNotes:"Notas de Lançamento",checkingPrereqs:"Verificando pré-requisitos...",sdCardReady:"Cartão SD pronto. Clique abaixo para enviar o firmware.",uploadedSuccess:"Firmware enviado para o cartão SD!",applyInstructions:"Para aplicar a atualização na sua impressora:",step1:"Na tela sensível ao toque da impressora, vá para <strong>Configurações</strong>",step2:"Navegue até <strong>Firmware</strong>",step3:"Selecione <strong>Atualizar a partir do cartão SD</strong>",step4:"A atualização levará de 10 a 20 minutos",done:"Concluído",starting:"Iniciando...",uploadFirmware:"Enviar Firmware",uploadFailed:"Falha ao iniciar o envio: {{error}}",uploadedToast:"Firmware enviado! Inicie a atualização na tela da impressora."},accessCodePlaceholder:"Deixe vazio para manter o atual",roi:{title:"Área de Detecção (ROI)",xStart:"Início X",yStart:"Início Y",width:"Largura",height:"Altura",instruction:"Ajuste a área de detecção para focar na placa de construção. A caixa verde na pré-visualização mostra a área atual."},developerModeWarning:"O modo desenvolvedor LAN não está ativado em: {{names}}. Alguns recursos podem não funcionar.",howToEnable:"Como ativar"},archives:{title:"Arquivos de Impressão",searchPlaceholder:"Pesquisar arquivos...",filterByPrinter:"Filtrar por impressora",filterByStatus:"Filtrar por status",sortBy:"Ordenar por",sortNewest:"Mais recentes primeiro",sortOldest:"Mais antigos primeiro",sortName:"Nome",sortDuration:"Duração",sortLargest:"Maiores primeiro",sortSmallest:"Menores primeiro",sortSize:"Tamanho",noArchives:"Nenhum arquivo encontrado",noArchivesSearch:"Nenhum arquivo corresponde à sua pesquisa",noArchivesYet:"Ainda não há arquivos",loadingArchives:"Carregando arquivos...",releaseToUpload:"Solte para enviar",showAll:"Mostrar todos",showFavoritesOnly:"Mostrar apenas favoritos",gridView:"Visualização em grade",listView:"Visualização em lista",calendarView:"Visualização em calendário",logView:"Registro de impressão",manageTags:"Gerenciar etiquetas",showFailedPrints:"Mostrar impressões falhas",hideFailedPrints:"Ocultar impressões falhas",printTime:"Tempo de impressão",filamentUsed:"Filamento usado",cost:"Custo",reprint:"Reimprimir",preview:"Pré-visualizar",deleteArchive:"Excluir arquivo",deleteConfirm:"Tem certeza de que deseja excluir este arquivo?",favorite:"Favorito",unfavorite:"Remover dos favoritos",viewDetails:"Ver detalhes",status:{completed:"Concluído",failed:"Falhou",stopped:"Parado"},toast:{source3mfAttached:"Arquivo de origem 3MF anexado: {{filename}}",failedUploadSource3mf:"Falha ao enviar arquivo de origem 3MF",source3mfRemoved:"Arquivo de origem 3MF removido",failedRemoveSource3mf:"Falha ao remover arquivo de origem 3MF",f3dAttached:"F3D anexado: {{filename}}",failedUploadF3d:"Falha ao enviar F3D",f3dRemoved:"F3D removido",failedRemoveF3d:"Falha ao remover F3D",timelapseAttached:"Timelapse anexado: {{filename}}",timelapseAlreadyAttached:"Timelapse já anexado",noMatchingTimelapse:"Nenhum timelapse correspondente encontrado",failedScanTimelapse:"Falha ao escanear timelapse",failedAttachTimelapse:"Falha ao anexar timelapse",timelapseRemoved:"Timelapse removido",failedRemoveTimelapse:"Falha ao remover timelapse",timelapseUploaded:"Timelapse enviado: {{filename}}",failedUploadTimelapse:"Falha ao enviar timelapse",archiveDeleted:"Arquivo excluído",failedDeleteArchive:"Falha ao excluir arquivo",addedToFavorites:"Adicionado aos favoritos",removedFromFavorites:"Removido dos favoritos",projectUpdated:"Projeto atualizado",failedUpdateProject:"Falha ao atualizar projeto",linkCopied:"Link copiado para a área de transferência",failedCopyLink:"Falha ao copiar link",photoDeleted:"Foto excluída",failedDeletePhoto:"Falha ao excluir foto",failedDeleteArchives:"Falha ao excluir arquivos",failedUpdateFavorites:"Falha ao atualizar favoritos",exportDownloaded:"Exportação baixada",exportFailed:"Falha na exportação"},menu:{print:"Imprimir",schedule:"Agendar",openInBambuStudio:"Abrir no Slicer",slice:"Fatiar",externalLink:"Link externo",viewOnMakerWorld:"Ver no MakerWorld",preview3d:"Pré-visualização 3D",viewTimelapse:"Ver Timelapse",scanForTimelapse:"Escanear Timelapse",uploadTimelapse:"Enviar Timelapse",removeTimelapse:"Remover Timelapse",downloadSource3mf:"Baixar Source 3MF",uploadSource3mf:"Enviar Source 3MF",replaceSource3mf:"Substituir Source 3MF",removeSource3mf:"Remover Source 3MF",uploadF3d:"Enviar F3D",replaceF3d:"Substituir F3D",downloadF3d:"Baixar F3D",removeF3d:"Remover F3D",download:"Baixar",copyDownloadLink:"Copiar link de download",qrCode:"Qr Code",viewPhotos:"Ver fotos",viewPhotosCount:"Ver fotos ({{count}})",projectPage:"Página do projeto",addToFavorites:"Adicionar aos favoritos",removeFromFavorites:"Remover dos favoritos",edit:"Editar",goToProject:"Ir para o projeto: {{name}}",addToProject:"Adicionar ao projeto",removeFromProject:"Remover do projeto",loading:"Carregando...",noProjectsAvailable:"Nenhum projeto disponível",select:"Selecionar",deselect:"Desmarcar",delete:"Excluir"},permission:{noReprint:"Você não tem permissão para reimprimir este arquivo",noAddToQueue:"Você não tem permissão para adicionar à fila",noUpdateArchives:"Você não tem permissão para atualizar arquivos",noUploadFiles:"Você não tem permissão para enviar arquivos",noDownload:"Você não tem permissão para baixar arquivos",noCopyLink:"Você não tem permissão para copiar links de download",noDelete:"Você não tem permissão para excluir este arquivo",noCreate:"Você não tem permissão para criar arquivos"},card:{previousPlate:"Placa anterior",nextPlate:"Próxima placa",plateNumber:"Placa {{index}}",moreOptions:"Clique com o botão direito para mais opções",addToFavorites:"Adicionar aos favoritos",removeFromFavorites:"Remover dos favoritos",cancelled:"cancelado",failed:"falha",duplicate:"duplicado",duplicateTitle:"Este modelo já foi impresso antes",openSource3mf:"Abrir source 3MF no Bambu Studio (clique com o botão direito para mais opções)",downloadF3d:"Baixar arquivo de design do Fusion 360",viewTimelapse:"Ver timelapse",viewPhoto:"Ver 1 foto",viewPhotos:"Ver {{count}} fotos",openFolder:"Abrir pasta: {{name}}",slicedFile:"Arquivo fatiado - pronto para imprimir",sourceFile:"Apenas arquivo fonte - nenhum mapeamento AMS disponível",gcode:"GCODE",source:"SOURCE",project:"Projeto: {{name}}",estimated:"Estimado: {{time}}",actual:"Real: {{time}}",accuracy:"Precisão: {{percent}}%",filament:"{{weight}}g",layer:"{{count}} camada",layers:"{{count}} camadas",object:"{{count}} objeto",objects:"{{count}} objetos",slicedFor:"Fatiado para {{model}}",uploadedBy:"Enviado por",noPermissionReprint:"Você não tem permissão para reimprimir",noFileForReprint:"Nenhum arquivo 3MF disponível — o arquivo não pôde ser baixado da impressora quando a impressão foi registrada",noPermissionEdit:"Você não tem permissão para editar arquivos",noPermissionDelete:"Você não tem permissão para excluir arquivos",reprint:"Reimprimir",schedulePrint:"Agendar impressão",schedule:"Agendar",openInBambuStudio:"Abrir no Bambu Studio",openInBambuStudioToSlice:"Abrir no Bambu Studio para fatiar",slice:"Fatiar",externalLink:"Link externo",makerWorld:"MakerWorld: {{designer}}",viewProject:"Ver projeto",noExternalLink:"Nenhum link externo",preview3d:"Visualização 3D",download:"Baixar",edit:"Editar",delete:"Excluir"},modal:{deleteArchive:"Excluir Arquivo",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"? Esta ação não pode ser desfeita.',deleteButton:"Excluir",removeSource3mf:"Remover Source 3MF",removeSource3mfConfirm:'Tem certeza de que deseja remover o arquivo source 3MF de "{{name}}"? Isso excluirá o arquivo original do projeto do fatiador.',removeButton:"Remover",removeF3d:"Remover F3D",removeF3dConfirm:'Tem certeza de que deseja remover o arquivo de design do Fusion 360 de "{{name}}"?',removeTimelapse:"Remover Timelapse",removeTimelapseConfirm:'Tem certeza de que deseja remover o vídeo timelapse de "{{name}}"?',timelapse:"{{name}} - Timelapse",selectTimelapse:"Selecionar Timelapse",selectTimelapseDesc:"Nenhuma correspondência automática encontrada. Selecione o timelapse para esta impressão:",deleteArchives:"Excluir Arquivos",deleteArchivesConfirm:"Tem certeza de que deseja excluir {{count}} arquivo(s)? Esta ação não pode ser desfeita.",deleteCount:"Excluir {{count}}"},page:{title:"Arquivos",printsCount:"{{filtered}} de {{total}} impressões",dropFilesHere:"Solte arquivos .3mf aqui",releaseToUpload:"Solte para enviar",only3mfSupported:"Apenas arquivos .3mf são suportados",close:"Fechar",selected:"{{count}} selecionado(s)",selectAll:"Selecionar Todos",tags:"Tags",project:"Projeto",favorite:"Favorito",delete:"Excluir",toggledFavorites:"Favoritos alternados para {{count}} arquivo(s)",failedUpdateFavorites:"Falha ao atualizar favoritos",archivesDeleted:"{{count}} arquivo(s) excluído(s)",failedDeleteArchives:"Falha ao excluir arquivos",photoDeleted:"Foto excluída",failedDeletePhoto:"Falha ao excluir foto"},list:{name:"Nome",printer:"Impressora",date:"Data",size:"Tamanho",actions:"Ações",hasTimelapse:"Possui timelapse"},log:{date:"Data",printName:"Nome da Impressão",printer:"Impressora",user:"Usuário",status:"Status",duration:"Duração",filament:"Filamento",allPrinters:"Todas as Impressoras",allUsers:"Todos os Usuários",allStatuses:"Todos os Status",cancelled:"Cancelado",skipped:"Ignorado",dateFrom:"De",dateTo:"Até",noEntries:"Nenhuma entrada de registro de impressão encontrada",showing:"Mostrando {{count}} de {{total}} entradas",rowsPerPage:"Linhas",page:"Página",prev:"Anterior",next:"Próxima",clearLog:"Limpar Registro",clearLogTitle:"Limpar Registro de Impressão",clearLogConfirm:"Todas as entradas do registro de impressão serão permanentemente excluídas. Arquivos e itens da fila não serão afetados. Esta ação não pode ser desfeita. Tem certeza?",clearLogButton:"Limpar Tudo",cleared:"{{count}} entradas do registro de impressão limpas",clearFailed:"Falha ao limpar o registro de impressão"}},queue:{title:"Fila de Impressão",subtitle:"Agende e gerencie seus trabalhos de impressão",addToQueue:"Adicionar à Fila",print:"Imprimir",reprint:"Reimprimir",schedulePrint:"Agendar Impressão",editQueueItem:"Editar Item da Fila",printToPrinters:"Imprimir para {{count}} Impressoras",queueToPrinters:"Adicionar à Fila para {{count}} Impressoras",sending:"Enviando...",sendingProgress:"Enviando {{current}}/{{total}}...",adding:"Adicionando...",addingProgress:"Adicionando {{current}}/{{total}}...",savingProgress:"Salvando {{current}}/{{total}}...",clearQueue:"Limpar Fila",clearHistory:"Limpar Histórico",emptyQueue:"Fila vazia",position:"Posição",scheduledTime:"Hora Agendada",moveUp:"Mover para Cima",moveDown:"Mover para Baixo",startNow:"Iniciar Agora",printingInProgress:"Impressão em andamento...",viewArchive:"Ver Arquivo",viewInFileManager:"Ver no Gerenciador de Arquivos",itemCount:"{{count}} item",itemCount_plural:"{{count}} itens",dragToReorder:"Arraste para reordenar (apenas ASAP)",reorderHint:"A posição afeta apenas itens ASAP. Itens agendados são executados no horário definido.",addedBy:"Adicionado por {{name}}",nextInQueue:"Próximo na fila",clearPlate:"Limpar Placa e Iniciar Próximo",clearPlateSuccess:"Placa limpa — pronta para a próxima impressão",plateReady:"Placa limpa — pronta para a próxima impressão",plateNumber:"Placa {{index}}",sections:{currentlyPrinting:"Imprimindo Atualmente",queued:"Na Fila",history:"Histórico"},status:{pending:"Pendente",waiting:"Aguardando",printing:"Imprimindo",paused:"Pausado",completed:"Concluído",failed:"Falhou",skipped:"Ignorado",cancelled:"Cancelado"},summary:{printing:"Imprimindo",queued:"Na Fila",totalTime:"Tempo Total da Fila",totalWeight:"Peso Total da Fila",history:"Histórico"},filter:{allPrinters:"Todas as Impressoras",unassigned:"Não Atribuído",allStatus:"Todos os Status",allLocations:"Todos os Locais",any:"Qualquer"},sort:{byPosition:"Ordenar por Posição",byName:"Ordenar por Nome",byPrinter:"Ordenar por Impressora",bySchedule:"Ordenar por Agendamento",byDate:"Ordenar por Data",ascendingOldest:"Crescente (mais antigo primeiro)",descendingNewest:"Decrescente (mais recente primeiro)"},badges:{staged:"Preparado (início manual)",requiresPrevious:"Requer sucesso anterior",autoPowerOff:"Desligamento automático"},empty:{title:"Nenhuma impressão agendada",description:'Agende uma impressão a partir da página de Arquivos usando a opção "Agendar" no menu de contexto, ou arraste e solte arquivos para começar.'},time:{asap:"ASAP",overdue:"Atrasado",now:"Agora",lessThanMinute:"Em menos de um minuto",inMinutes:"Em {{count}} min",inHours:"Em {{count}} horas"},actions:{stopPrint:"Parar Impressão",startPrint:"Iniciar Impressão",requeue:"Reenfileirar"},bulkEdit:{title:"Editar {{count}} Item",title_plural:"Editar {{count}} Itens",description:"Apenas as configurações alteradas serão aplicadas aos itens selecionados.",printer:"Impressora",noChange:"— Sem alterações —",queueOptions:"Opções de Fila",staged:"Preparado (início manual)",autoPowerOff:"Desligamento automático após impressão",requirePrevious:"Requer sucesso anterior",printOptions:"Opções de Impressão",bedLevelling:"Nivelamento da Mesa",flowCalibration:"Calibração de Fluxo",vibrationCalibration:"Calibração de Vibração",layerInspection:"Inspeção da Primeira Camada",timelapse:"Timelapse",useAms:"Usar AMS",applyChanges:"Aplicar Alterações",selectAll:"Selecionar Todos",deselectAll:"Desmarcar Todos",selected:"{{count}} selecionado(s)",editSelected:"Editar Selecionados",cancelSelected:"Cancelar Selecionados"},confirm:{cancelTitle:"Cancelar Impressão Agendada",cancelMessage:'Tem certeza de que deseja cancelar "{{name}}"?',stopTitle:"Parar Impressão",stopMessage:'Tem certeza de que deseja parar a impressão atual "{{name}}"? Isso cancelará o trabalho de impressão na impressora.',removeTitle:"Remover do Histórico",removeMessage:'Tem certeza de que deseja remover "{{name}}" do histórico da fila?',clearHistoryTitle:"Limpar Histórico",clearHistoryMessage:"Tem certeza de que deseja remover todos os {{count}} itens do histórico?",cancelButton:"Cancelar Impressão",stopButton:"Parar Impressão",thisPrint:"esta impressão",thisItem:"este item"},toast:{cancelled:"Item da fila cancelado",cancelFailed:"Falha ao cancelar item",removed:"Item da fila removido",removeFailed:"Falha ao remover item",stopped:"Impressão parada",stopFailed:"Falha ao parar impressão",released:"Impressão liberada para a fila",startFailed:"Falha ao iniciar impressão",reorderFailed:"Falha ao reordenar fila",historyCleared:"Limpar {{count}} item(s) do histórico",clearHistoryFailed:"Falha ao limpar histórico",updateFailed:"Falha ao atualizar itens",bulkCancelled:"Cancelado {{count}} item(s)",bulkCancelFailed:"Falha ao cancelar itens"},permissions:{noStopPrint:"Você não tem permissão para parar impressões",noStartPrint:"Você não tem permissão para iniciar impressões",noEdit:"Você não tem permissão para editar este item da fila",noCancel:"Você não tem permissão para cancelar este item da fila",noRequeue:"Você não tem permissão para reenfileirar itens",noRemove:"Você não tem permissão para remover este item da fila",noClearHistory:"Você não tem permissão para limpar todo o histórico",noEditItems:"Você não tem permissão para editar itens da fila",noCancelItems:"Você não tem permissão para cancelar itens da fila"}},backgroundDispatch:{unknownFile:"Unknown file",unknownPrinter:"Unknown printer",startingPrints:"Starting prints",progressSummary:"{{complete}}/{{total}} complete • Dispatched: {{dispatched}} • Processing: {{processing}}",expandDetails:"Expand dispatch details",collapseDetails:"Collapse dispatch details",dismissToast:"Dismiss dispatch toast",cancelDispatchJob:"Cancel dispatch job",cancel:"Cancel",cancelling:"Cancelling…",status:{dispatched:"Dispatched",processing:"Processing",completed:"Completed",failed:"Failed",cancelled:"Cancelled"},toast:{cancellingUpload:"Cancelling upload...",cancelled:"Dispatch cancelled",cancelFailed:"Failed to cancel dispatch",completeWithFailures:"Background dispatch complete: {{completed}} succeeded, {{failed}} failed",completeSuccess:"Background dispatch complete: {{completed}} succeeded"}},stats:{title:"Dashboard",subtitle:"Arraste os widgets para reorganizar. Clique no ícone de olho para ocultar.",overview:"Visão Geral",totalPrints:"Total de Impressões",successRate:"Taxa de Sucesso",totalPrintTime:"Tempo Total de Impressão",printTime:"Tempo de Impressão",totalFilament:"Filamento Total Utilizado",filamentUsed:"Filamento Utilizado",filamentCost:"Custo do Filamento",totalCost:"Custo Total",energyUsed:"Energia Utilizada",energyCost:"Custo da Energia",averagePrintTime:"Tempo Médio de Impressão",printsPerDay:"Impressões por Dia",byPrinter:"Por Impressora",printsByPrinter:"Impressões por Impressora",byMaterial:"Por Material",byMonth:"Por Mês",last7Days:"Últimos 7 Dias",last30Days:"Últimos 30 Dias",last90Days:"Últimos 90 Dias",allTime:"Todo o Tempo",quickStats:"Estatísticas Rápidas",printActivity:"Atividade de Impressão",filamentTypes:"Tipos de Filamento",filamentTrends:"Tendências de Filamento",failureAnalysis:"Análise de Falhas",timeAccuracy:"Precisão do Tempo",successful:"Bem-sucedido:",failed:"Falhou:",perfectEstimate:"100% = estimativa perfeita",noTimeAccuracyData:"Nenhum dado de precisão de tempo disponível",noFilamentData:"Nenhum dado de filamento disponível",noPrinterData:"Nenhum dado de impressora disponível",noPrintData:"Nenhum dado de impressão disponível",noPrintDataLast30Days:"Nenhum dado de impressão nos últimos 30 dias",failureReasons:"Razões de Falha",topFailureReasons:"Principais Razões de Falha",failedPrintsCount:"{{failed}} / {{total}} impressões falharam",lastWeekRate:"Última semana: {{rate}}%",resetLayout:"Redefinir Layout",recalculateCosts:"Recalcular Custos",recalculateCostsHint:"Recalcular todos os custos do arquivo usando os preços atuais do filamento",exportStats:"Exportar Estatísticas",exportAsCsv:"Exportar como CSV",exportAsExcel:"Exportar como Excel",hiddenCount:"{{count}} Oculto",exportDownloaded:"Exportação baixada",exportFailed:"Falha na exportação",layoutReset:"Layout redefinido",recalculatedCosts:"Custos recalculados para {{count}} arquivos",recalculateFailed:"Falha ao recalcular custos",loadingStats:"Carregando estatísticas...",noPermissionResetLayout:"Você não tem permissão para redefinir o layout",noPermissionRecalculate:"Você não tem permissão para recalcular custos"},maintenance:{title:"Manutenção",overview:"Visão Geral",allOk:"Todas as manutenções estão em dia",dueCount:"{{count}} item pendente",dueCount_plural:"{{count}} itens pendentes",warningCount:"{{count}} aviso",warningCount_plural:"{{count}} avisos",totalPrintTime:"Tempo Total de Impressão",nextMaintenance:"Próxima Manutenção",nothingDue:"Nada pendente",tasks:"Tarefas",lastPerformed:"Última execução",interval:"Intervalo",hoursRemaining:"{{hours}}h restantes",hoursOverdue:"{{hours}}h atrasadas",markDone:"Marcar como Concluída",performMaintenance:"Realizar Manutenção",history:"Histórico",noHistory:"Nenhum histórico de manutenção",editPrintHours:"Editar Horas de Impressão",currentHours:"Horas Atuais",statusTab:"Status",settingsTab:"Configurações",overdueCount:"{{count}} atrasado",dueSoonCount:"{{count}} prestes a vencer",dueSoon:"Prestes a vencer",allGood:"Tudo certo",overdueBy:"Atrasado por {{duration}}",dueIn:"Vence em {{duration}}",timeLeft:"{{duration}} restantes",day:"1 dia",days:"{{count}} dias",week:"1 semana",weeks:"{{count}} semanas",month:"1 mês",months:"{{count}} meses",year:"1 ano",maintenanceTypes:"Tipos de Manutenção",maintenanceTypesDescription:"Tipos de sistema e suas tarefas de manutenção personalizadas",addCustomType:"Adicionar Tipo Personalizado",restoreDefaults:"Restaurar Tarefas Padrão",intervalType:"Tipo de Intervalo",intervalValue:"Intervalo ({{type}})",icon:"Icon",documentationLink:"Link da Documentação (opcional)",assignToPrinters:"Atribuir a Impressoras",selectAtLeastOnePrinter:"Selecione pelo menos uma impressora",addType:"Adicionar Tipo",custom:"Personalizado",printHours:"Horas de Impressão",calendarDays:"Dias de Calendário",exampleName:"ex., Substituir Filtro HEPA",viewDocumentation:"Ver documentação",timeBasedInterval:"Intervalo baseado em tempo",intervalOverrides:"Substituições de Intervalo",intervalOverridesDescription:"Personalize os intervalos para impressoras específicas",assignedToPrinters:"Atribuído a impressoras:",noPrintersAssigned:"Nenhuma impressora atribuída",addPrinterShort:"Adicionar:",printersAssignedClick:"{{count}} impressora(s) atribuída(s) - clique para gerenciar",removeFromPrinter:"Remover desta impressora",types:{lubricateCarbonRods:"Lubricar Barras de Carbono",lubricateRails:"Lubricar Trilhos Lineares",cleanNozzle:"Limpar Bico/Hotend",checkBelts:"Verificar Tensão das Correias",cleanBuildPlate:"Limpar Plataforma de Impressão",checkExtruder:"Verificar Engrenagens do Extrusor",checkCooling:"Verificar Ventiladores de Resfriamento",generalInspection:"Inspeção Geral",cleanCarbonRods:"Limpar Barras de Carbono",cleanLinearRails:"Limpar Trilhos Lineares",checkPtfeTube:"Verificar Tubo PTFE",replaceHepaFilter:"Substituir Filtro HEPA",replaceCarbonFilter:"Substituir Filtro de Carbono",lubricateLeftNozzleRail:"Lubrificar Trilho do Bico Esquerdo"},maintenanceComplete:"Manutenção marcada como concluída",typeUpdated:"Tipo de manutenção atualizado",typeDeleted:"Tipo de manutenção excluído",defaultsRestored:"Restauradas {{count}} tarefa(s) padrão",printHoursUpdated:"Horas de impressão atualizadas",printerAssigned:"Impressora atribuída",printerRemoved:"Impressora removida",deleteTypeConfirm:'Excluir "{{name}}"?',deleteSystemTypeTitle:"Excluir tarefa de manutenção padrão?",deleteSystemTypeMessage:'Tem certeza de que deseja excluir a tarefa de manutenção padrão "{{name}}"?',noPermissionUpdate:"Você não tem permissão para atualizar itens de manutenção",noPermissionPerform:"Você não tem permissão para realizar manutenção",noPermissionEditTypes:"Você não tem permissão para editar tipos de manutenção",noPermissionDeleteTypes:"Você não tem permissão para excluir tipos de manutenção",noPermissionEditHours:"Você não tem permissão para editar horas de impressão",noPermissionRemovePrinter:"Você não tem permissão para remover atribuições de impressora",noPermissionAssignPrinter:"Você não tem permissão para atribuir impressoras",noPermissionEditIntervals:"Você não tem permissão para editar intervalos",configureSettings:"Configure tipos de manutenção e intervalos"},settings:{title:"Configurações",general:"Geral",tabs:{general:"Geral",smartPlugs:"Tomadas Inteligentes",notifications:"Notificações",filament:"Filamento",network:"Rede",apiKeys:"Chaves API",virtualPrinter:"Impressora Virtual",users:"Autenticação",backup:"Backup",emailAuth:"Autenticação por Email"},email:{smtpSettings:"Configuração SMTP",smtpHost:"Servidor SMTP",smtpPort:"Porta SMTP",security:"Segurança",authentication:"Autenticação",username:"Nome de Usuário",password:"Senha",fromEmail:"Email de Remetente",fromName:"Nome de Remetente",testConnection:"Testar Conexão SMTP",testRecipient:"Email de Teste",sendTest:"Enviar Email de Teste",sending:"Enviando...",save:"Salvar Configurações",saving:"Salvando...",advancedAuth:"Autenticação Avançada",advancedAuthEnabled:"Autenticação Avançada está habilitada",advancedAuthEnabledDesc:"Recursos de gerenciamento de usuários baseados em email estão ativos. Novos usuários receberão senhas geradas automaticamente por email, e os usuários podem redefinir suas senhas através do recurso de esqueci minha senha.",advancedAuthDisabled:"Autenticação Avançada está desabilitada",advancedAuthDisabledDesc:"Habilite a autenticação avançada para ativar recursos baseados em email para gerenciamento de usuários.",enable:"Habilitar",disable:"Desabilitar",feature1:"Senhas são geradas automaticamente e enviadas por email para novos usuários",feature2:"Usuários podem fazer login com nome de usuário ou email",feature3:"Recurso de esqueci minha senha está disponível",feature4:"Administradores podem redefinir senhas de usuários via email",errors:{requiredFields:"Por favor, preencha todos os campos obrigatórios",usernameRequired:"Nome de usuário é obrigatório quando a autenticação está habilitada",enterTestEmail:"Por favor, insira um endereço de email de teste",smtpServerAndEmail:"Por favor, preencha o servidor SMTP e o email de remetente antes de testar",usernamePasswordRequired:"Nome de usuário e senha são obrigatórios quando a autenticação está habilitada",configureSmtpFirst:"Por favor, configure e teste as configurações SMTP primeiro"},success:{settingsSaved:"Configurações SMTP salvas com sucesso"},securityOptions:{starttls:"STARTTLS (Porta 587)",ssl:"SSL/TLS (Porta 465)",none:"Nenhuma (Porta 25)"},authOptions:{enabled:"Habilitado",disabled:"Desabilitado"}},appearance:"Aparência",notifications:"Notificações",smartPlugs:"Tomadas Inteligentes",spoolman:"Spoolman",updates:"Atualizações",language:"Idioma",languageDescription:"Selecione seu idioma preferido",theme:"Tema",themeLight:"Claro",themeDark:"Escuro",themeSystem:"Sistema",defaultView:"Visualização Padrão",defaultViewDescription:"Página a ser exibida ao abrir o aplicativo",checkForUpdates:"Verificar Atualizações",autoUpdate:"Atualização Automática",currentVersion:"Versão Atual",latestVersion:"Última Versão",upToDate:"Você está atualizado",updateAvailable:"Atualização disponível",notificationLanguage:"Idioma das Notificações",notificationLanguageDescription:"Idioma para notificações push",bedCooledThreshold:"Limite de Resfriamento da Cama",bedCooledThresholdDescription:"Temperatura abaixo da qual a cama é considerada resfriada após uma impressão",notificationProviders:"Provedores de Notificação",addProvider:"Adicionar Provedor",editProvider:"Editar Provedor",providerType:"Tipo de Provedor",testNotification:"Testar Notificação",testSuccess:"Notificação de teste enviada com sucesso",testFailed:"Falha ao enviar notificação de teste",quietHours:"Horas de Silêncio",quietHoursDescription:"Não perturbe durante essas horas",quietHoursStart:"Início",quietHoursEnd:"Fim",events:{title:"Eventos de Notificação",printStart:"Impressão Iniciada",printComplete:"Impressão Concluída",printFailed:"Falha na Impressão",printStopped:"Impressão Interrompida",printProgress:"Marcos de Progresso",printProgressDescription:"Notificar em 25%, 50%, 75%",printerOffline:"Impressora Offline",printerError:"Erro na Impressora",filamentLow:"Filamento Baixo",maintenanceDue:"Manutenção Pendente",maintenanceDueDescription:"Notificar quando a manutenção for necessária"},smartPlug:{title:"Tomadas Inteligentes",add:"Adicionar Tomada Inteligente",edit:"Editar Tomada Inteligente",name:"Nome",ipAddress:"Endereço IP",linkedPrinter:"Impressora Vinculada",autoOn:"Ligar Automaticamente",autoOnDescription:"Ligar quando a impressão começar",autoOff:"Desligar Automaticamente",autoOffDescription:"Desligar após a conclusão da impressão",offDelay:"Atraso para Desligar",offDelayMinutes:"Minutos após a impressão",offDelayTemp:"Quando o bico estiver abaixo da temperatura",currentState:"Estado Atual",turnOn:"Ligar",turnOff:"Desligar"},filamentTracking:"Rastreamento de Filamento",filamentTrackingDesc:"Escolha como rastrear seus rolos de filamento. Você pode usar o inventário interno ou conectar a um servidor Spoolman externo.",trackingModeBuiltIn:"Inventário Interno",trackingModeBuiltInDesc:"Correspondência automática de RFID e rastreamento de uso incluídos",trackingModeSpoolmanDesc:"Servidor de gerenciamento de filamento externo",builtInFeatureRfid:"Detecta automaticamente rolos RFID da Bambu Lab no AMS",builtInFeatureUsage:"Rastreia o consumo de filamento por impressão",builtInFeatureCatalog:"Gerencia rolos, cores e perfis de fator K",builtInFeatureThirdParty:"Rolos de terceiros podem ser atribuídos aos rolos do inventário",amsSyncButton:"Sincronizar Pesos do AMS",amsSyncTitle:"Sincronizar Pesos dos Rolos do AMS",amsSyncMessage:"Isso substituirá todos os pesos dos rolos do inventário pelos valores atuais de % restante do AMS das impressoras conectadas. Use isso para recuperar dados de peso corrompidos. As impressoras devem estar online.",amsSyncing:"Sincronizando...",amsSyncSuccess:"{{synced}} rolo(s) sincronizado(s), {{skipped}} ignorado(s)",amsSyncError:"Falha ao sincronizar pesos do AMS",spoolmanUrl:"Spoolman URL",spoolmanUrlHint:"URL do seu servidor Spoolman (por exemplo, http://localhost:7912)",spoolmanConnected:"Conectado",spoolmanDisconnected:"Desconectado",status:"Status",connect:"Conectar",disconnect:"Desconectar",howSyncWorks:"Como a Sincronização Funciona",syncInfoRfidOnly:"Apenas rolos oficiais da Bambu Lab com RFID são sincronizados",syncInfoAutoCreate:"Novos rolos são criados automaticamente no Spoolman na primeira sincronização",syncInfoThirdPartySkipped:"Rolos não oficiais da Bambu Lab (terceiros, reabastecidos) são ignorados",linkingExistingSpools:"Vinculando Rolos Existentes",linkingExistingSpoolsDesc:'Para vincular rolos existentes do Spoolman ao seu AMS, passe o mouse sobre um slot do AMS e clique em "Vincular ao Spoolman".',syncMode:"Modo de Sincronização",syncModeAuto:"Automático",syncModeManual:"Apenas Manual",syncModeAutoDesc:"Os dados do AMS são sincronizados automaticamente quando alterações são detectadas",syncModeManualDesc:"Somente sincronize quando acionado manualmente",syncAmsData:"Sincronizar Dados do AMS",syncAmsDataDesc:"Sincronize manualmente os dados do AMS da impressora com o Spoolman",allPrinters:"Todas as Impressoras",noDefaultPrinter:"Sem padrão (perguntar a cada vez)",sidebarOrder:"Ordem da barra lateral",saveThumbnails:"Salvar miniaturas",captureFinishPhoto:"Capturar foto de conclusão",noPrintersConfigured:"Nenhuma impressora configurada",archiveMode:{always:"Sempre criar entrada de arquivo",never:"Nunca criar entrada de arquivo",ask:"Perguntar a cada vez"},checkForUpdatesLabel:"Verificar atualizações",checkPrinterFirmware:"Verificar firmware da impressora",includeBetaUpdates:"Incluir versões beta",includeBetaUpdatesDesc:"Notificar sobre versões beta e pré-lançamento ao verificar atualizações",enableRetry:"Habilitar tentativa",homeAssistantDescription:"Controlar tomadas inteligentes via Home Assistant",environmentManagedLabel:"(Gerenciado pelo Ambiente)",autoEnabledViaEnv:"Habilitado automaticamente via variáveis de ambiente",urlFromEnvReadOnly:"Valor definido pela variável de ambiente HA_URL (somente leitura)",tokenFromEnvReadOnly:"Valor definido pela variável de ambiente HA_TOKEN (somente leitura)",mqttConnectedTo:"Conectado a",prometheusDescription:"Expor dados da impressora no formato Prometheus",noSmartPlugsTitle:"Nenhuma tomada inteligente configurada",noSmartPlugsDescription:"Adicione uma tomada inteligente baseada em Tasmota para monitorar o consumo de energia e automatizar o controle de energia.",noProvidersTitle:"Nenhum provedor configurado",noProvidersDescription:"Adicione um provedor para receber alertas.",noTemplatesAvailable:"Nenhum modelo disponível. Reinicie o backend para gerar os modelos padrão.",apiPermissionView:"Visualizar status da impressora e fila",apiPermissionEdit:"Adicionar e remover itens da fila de impressão",apiKeysEmptyTitle:"Nenhuma chave API",apiKeysEmptyDescription:"Crie uma chave API para integrar com serviços externos.",noUsersFound:"Nenhum usuário encontrado",noGroupsFound:"Nenhum grupo encontrado",noGroupsAvailable:"Nenhum grupo disponível",passwordsDoNotMatch:"As senhas não coincidem",systemGroupWarning:"Os nomes dos grupos do sistema não podem ser alterados",authDisabledTitle:"Autenticação Desativada",authDisabledFeature1:"Exigir login para acessar o sistema",authDisabledFeature2:"Criar múltiplos usuários com permissões baseadas em grupos",authDisabledFeature3:"Controlar acesso com mais de 50 permissões granulares",userHasCreated:"Este usuário criou:",userItemsQuestion:"O que você gostaria de fazer com esses itens?",deleteUserConfirm:"Tem certeza de que deseja excluir este usuário?",actionCannotBeUndone:"Esta ação não pode ser desfeita.",addFirstSmartPlug:"Adicione sua primeira tomada inteligente",providers:"Provedores",log:"Registro",testAll:"Testar tudo",testResults:"Resultados do teste",testPassedCount:"{{count}} aprovado",testFailedCount:"{{count}} falhou",messageTemplates:"Modelos de mensagem",messageTemplatesDescription:"Personalize as mensagens de notificação para cada evento.",apiKeys:"Chaves API",apiKeysDescription:"Crie chaves API para integrações externas e webhooks.",createKey:"Criar Chave",apiKeyCreated:"Chave API criada com sucesso",apiKeyCopyWarning:"Copie esta chave agora - ela não será exibida novamente!",useInApiBrowser:"Usar no Navegador API",createNewApiKey:"Criar Nova Chave API",keyName:"Nome da Chave",keyNamePlaceholder:"e.g., Home Assistant, OctoPrint",readStatus:"Status de Leitura",readStatusDescription:"Visualizar status da impressora e fila",manageQueue:"Gerenciar Fila",manageQueueDescription:"Adicionar e remover itens da fila de impressão",controlPrinter:"Controlar Impressora",controlPrinterDescription:"Pausar, retomar e parar impressões",unnamedKey:"Chave Sem Nome",lastUsed:"Último uso",read:"Ler",control:"Controlar",createFirstKey:"Crie sua primeira chave",webhookEndpoints:"Endpoints de Webhook",webhookApiKeyHint:"Use sua chave API no cabeçalho X-API-Key.",webhook:{getAllStatus:"Obter status de todas as impressoras",getSpecificStatus:"Obter status de uma impressora específica",addToQueue:"Adicionar à fila de impressão",pausePrint:"Pausar impressão",resumePrint:"Retomar impressão",stopPrint:"Parar impressão"},apiBrowser:"Navegador API",apiBrowserDescription:"Explore e teste todos os endpoints de API disponíveis.",apiKeyForTesting:"Chave API para Teste",apiKeyPlaceholder:"Cole sua chave API aqui para testar endpoints autenticados...",apiKeyHint:"Esta chave será enviada como cabeçalho X-API-Key nas solicitações.",deleteApiKeyTitle:"Excluir Chave API",deleteApiKeyMessage:"Tem certeza de que deseja excluir esta chave API? Quaisquer integrações usando esta chave deixarão de funcionar.",deleteKey:"Excluir Chave",amsDisplayThresholds:"Limiares de Exibição AMS",amsThresholdsDescription:"Configure os limiares de cores para os indicadores de umidade e temperatura do AMS.",humidity:"Umidade",goodGreen:"Bom (verde)",fairOrange:"Razoável (laranja)",aboveFairBad:"Acima do limiar razoável mostra como vermelho (ruim)",temperature:"Temperatura",goodBlue:"Bom (azul)",aboveFairHot:"Acima do limiar razoável mostra como vermelho (quente)",historyRetention:"Retenção de Histórico",keepSensorHistory:"Manter histórico do sensor por",historyRetentionDescription:"Dados antigos de umidade e temperatura serão automaticamente excluídos",printModal:"Modal de Impressão",expandCustomMapping:"Expandir mapeamento personalizado por padrão",expandCustomMappingDescription:"Ao imprimir em várias impressoras, mostrar o mapeamento AMS por impressora expandido",authentication:"Autenticação",authEnabledDescription:"Sua instância está protegida com autenticação de usuário",authDisabledDescription:"Ative para exigir login e gerenciar o acesso dos usuários",authDisabledMessage:"Ative a autenticação para criar contas de usuário, gerenciar permissões e proteger sua instância do Bambuddy.",enableAuthentication:"Ativar Autenticação",currentUser:"Usuário Atual",changePassword:"Alterar Senha",admin:"Administrador",users:"Usuários",addUser:"Adicionar Usuário",groups:"Grupos",addGroup:"Adicionar Grupo",system:"Sistema",noDescription:"Sem descrição",userCount:"{{count}} usuários",permissionCount:"{{count}} permissões",createUser:"Criar Usuário",username:"Nome de Usuário",enterUsername:"Digite o nome de usuário",password:"Senha",enterPassword:"Digite a senha (mínimo 6 caracteres)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha",viewReleaseOnGitHub:"Ver lançamento no GitHub",turnAllPlugsOn:"Ligar todas as tomadas",turnAllPlugsOff:"Desligar todas as tomadas",clearNotificationLogs:"Limpar Logs de Notificação",clearLogsMessage:"Isso excluirá permanentemente todos os logs de notificação com mais de 30 dias. Esta ação não pode ser desfeita.",clearLogs:"Limpar Logs",resetUiPreferences:"Redefinir Preferências de UI",resetUiPreferencesMessage:"Isso redefinirá todas as preferências de UI para os padrões: ordem da barra lateral, tema, layout do painel, modos de exibição e preferências de classificação. Suas impressoras, arquivos e configurações do servidor NÃO serão afetados. A página será recarregada após a limpeza.",resetPreferences:"Redefinir Preferências",deleteGroupTitle:"Excluir Grupo",deleteGroupMessage:"Tem certeza de que deseja excluir este grupo? Usuários neste grupo perderão essas permissões.",deleteGroup:"Excluir Grupo",disableAuthenticationTitle:"Desativar Autenticação",disableAuthenticationMessage:"Tem certeza de que deseja desativar a autenticação? Isso tornará sua instância do Bambuddy acessível sem login. Todos os usuários permanecerão no banco de dados, mas a autenticação será desativada.",disableAuthentication:"Desativar Autenticação",configureBambuddy:"Configurar Bambuddy",systemDefault:"Padrão do Sistema",archiveSettings:"Configurações de Arquivo",newWindow:"Nova Janela",embeddedOverlay:"Sobreposição Incorporada",preferredSlicer:"Fatiador Preferido",preferredSlicerDescription:"Escolha qual aplicativo de fatiamento abrirá os arquivos",externalCameras:"Câmeras Externas",costTracking:"Rastreamento de Custos",printsOnly:"Apenas Impressões",totalConsumption:"Consumo Total",dataManagement:"Gerenciamento de Dados",storageUsage:"Uso de Armazenamento",storageUsageDescription:"Detalhamento do uso de dados por categoria",storageUsageTotal:"Total",storageUsageErrors:"Erros",storageUsageOtherBreakdown:"Outros (inclui ativos estáticos, scripts e arquivos de configuração)",storageUsageSystem:"Sistema",storageUsageData:"Dados",storageUsageUnavailable:"Informações de uso de armazenamento indisponíveis",clearNotificationLogsDescription:"Excluir logs de notificação com mais de 30 dias",resetUiPreferencesDescription:"Redefinir ordem da barra lateral, tema, modos de exibição e preferências de layout. Impressoras, arquivos e configurações não são afetados.",enableHomeAssistant:"Ativar Home Assistant",enableMqtt:"Ativar MQTT",useTls:"Usar TLS",enableMetricsEndpoint:"Ativar Endpoint de Métricas",availableMetrics:"Métricas Disponíveis",editUser:"Editar Usuário",deleteUserTitle:"Excluir Usuário",groupName:"Nome do Grupo",leaveEmptyForAnonymous:"Deixe vazio para anônimo",leaveEmptyForNoAuth:"Deixe vazio para sem autenticação",enterNewPassword:"Digite a nova senha",confirmNewPassword:"Confirme a nova senha",enterGroupName:"Digite o nome do grupo",enterDescriptionOptional:"Digite a descrição (opcional)",enterCurrentPassword:"Digite a senha atual",enterNewPasswordMin6:"Digite a nova senha (mínimo 6 caracteres)",toast:{keyCopied:"Chave copiada para a área de transferência",copyFailed:"Falha ao copiar a chave",keyAddedToBrowser:"Chave adicionada ao Navegador de API",clearLogsFailed:"Falha ao limpar logs",uiPreferencesReset:"Preferências de UI redefinidas. Atualizando...",authDisabled:"Autenticação desativada com sucesso",authDisableFailed:"Falha ao desativar a autenticação",apiKeyCreated:"Chave de API criada",apiKeyDeleted:"Chave de API excluída",userCreated:"Usuário criado com sucesso",userUpdated:"Usuário atualizado com sucesso",userDeleted:"Usuário excluído com sucesso",groupCreated:"Grupo criado com sucesso",groupUpdated:"Grupo atualizado com sucesso",groupDeleted:"Grupo excluído com sucesso",fillRequiredFields:"Por favor, preencha todos os campos obrigatórios",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres",enterGroupName:"Por favor, insira um nome de grupo",settingsSaved:"Configurações salvas",cameraSettingsSaved:"Configurações da câmera salvas",enterCameraUrl:"Por favor, insira a URL da câmera",passwordChanged:"Senha alterada com sucesso",connectionFailed:"Falha na conexão",testFailed:"Falha no teste",cameraConnected:"Câmera conectada{{resolution}}"},testConnection:"Testar Conexão",catalog:{spoolCatalog:"Catálogo de Carretéis",spoolCatalogDescription:"Pesos de carretéis vazios por marca/tipo. Usado para pesquisa automática de peso ao adicionar carretéis.",searchCatalog:"Pesquisar no catálogo...",addNewEntry:"Adicionar Nova Entrada",namePlaceholder:"Nome (ex.: Bambu Lab - Plástico)",weight:"Peso",type:"Tipo",default:"Padrão",custom:"Personalizado",noMatch:"Nenhuma entrada corresponde à sua pesquisa",empty:"Nenhuma entrada no catálogo",deleteEntry:"Excluir Entrada",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',resetCatalog:"Redefinir Catálogo",resetConfirm:"Redefinir catálogo para os padrões? Isso removerá todas as entradas personalizadas.",loadFailed:"Falha ao carregar o catálogo de carretéis",nameWeightRequired:"Nome e peso são obrigatórios",entryAdded:"Entrada adicionada",addFailed:"Falha ao adicionar entrada",entryUpdated:"Entrada atualizada",updateFailed:"Falha ao atualizar entrada",entryDeleted:"Entrada excluída",deleteFailed:"Falha ao excluir entrada",resetSuccess:"Catálogo redefinido para os padrões",resetFailed:"Falha ao redefinir catálogo",exported:"Exportadas {{count}} entradas",imported:"Importadas {{added}} entradas ({{skipped}} ignoradas)",importFailed:"Falha ao importar: formato JSON inválido",exportTooltip:"Exportar catálogo para JSON",importTooltip:"Importar catálogo de JSON",resetTooltip:"Redefinir para os padrões"},colorCatalog:{title:"Catálogo de Cores",description:"Cores de filamento por fabricante/material. Usado para pesquisa automática de cores ao adicionar carretéis.",searchColors:"Pesquisar cores...",allManufacturers:"Todos os fabricantes",addNewColor:"Adicionar Nova Cor",manufacturer:"Fabricante",colorName:"Nome da Cor",hex:"Hex",materialOptional:"Material (opcional)",showing:"Mostrando {{filtered}} de {{total}} cores",noMatch:"Nenhuma cor corresponde à sua pesquisa",empty:"Nenhuma cor no catálogo",deleteColor:"Excluir Cor",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',resetCatalog:"Redefinir Catálogo de Cores",resetConfirm:"Redefinir catálogo para os padrões? Isso removerá todas as cores personalizadas.",sync:"Sincronizar",starting:"Iniciando...",syncTooltip:"Sincronizar do FilamentColors.xyz (2000+ cores, pode levar um minuto)",loadFailed:"Falha ao carregar o catálogo de cores",fieldsRequired:"Fabricante, nome da cor e cor hex são obrigatórios",colorAdded:"Cor adicionada",addFailed:"Falha ao adicionar cor",colorUpdated:"Cor atualizada",updateFailed:"Falha ao atualizar cor",colorDeleted:"Cor excluída",deleteFailed:"Falha ao excluir cor",resetSuccess:"Catálogo de cores redefinido para os padrões",resetFailed:"Falha ao redefinir catálogo",syncUpToDate:"Já está atualizado ({{count}} cores verificadas)",syncComplete:"Adicionadas {{added}} novas cores ({{skipped}} já existiam)",syncError:"Erro de sincronização",syncFailed:"Falha ao sincronizar do FilamentColors.xyz",exported:"Exportadas {{count}} cores",imported:"Importadas {{added}} cores ({{skipped}} ignoradas)",importFailed:"Falha ao importar: formato JSON inválido"}},notification:{printStarted:{title:"Impressão Iniciada",body:"{{printer}}: {{filename}} iniciou a impressão"},printCompleted:{title:"Impressão Concluída",body:"{{printer}}: {{filename}} foi concluída com sucesso"},printFailed:{title:"Falha na Impressão",body:"{{printer}}: {{filename}} falhou"},printStopped:{title:"Impressão Interrompida",body:"{{printer}}: {{filename}} foi interrompida"},printProgress:{title:"Progresso da Impressão",body:"{{printer}}: {{filename}} está {{percent}}% concluída"},printerOffline:{title:"Impressora Offline",body:"{{printer}} está offline"},printerError:{title:"Erro na Impressora",body:"{{printer}}: {{error}}"},filamentLow:{title:"Filamento Baixo",body:"{{printer}}: O filamento está acabando"},maintenanceDue:{title:"Manutenção Pendente",body:"{{printer}}: {{items}} precisam de atenção"}},errors:{generic:"Algo deu errado",networkError:"Erro de rede. Por favor, verifique sua conexão.",notFound:"Não encontrado",unauthorized:"Não autorizado",serverError:"Erro no servidor",validationError:"Por favor, verifique sua entrada",printerConnectionFailed:"Falha ao conectar à impressora",saveFailed:"Falha ao salvar alterações",deleteFailed:"Falha ao excluir",loadFailed:"Falha ao carregar dados"},hmsErrors:{title:"Erros - {{name}}",noErrors:"Nenhum erro",viewOnWiki:"Ver no Bambu Lab Wiki",clearInstructions:"Limpe os erros na impressora para descartá-los aqui.",clearErrors:"Limpar Erros",clearSuccess:"Erros HMS limpos",clearFailed:"Falha ao limpar erros HMS"},mqttDebug:{title:"MQTT Log de Depuração",searchPlaceholder:"Pesquisar tópico ou payload...",noMessages:"Nenhuma mensagem registrada ainda",startLoggingHint:'Clique em "Iniciar Registro" para começar a capturar mensagens MQTT',noMessagesMatch:"Nenhuma mensagem corresponde ao seu filtro",adjustFilterHint:"Tente ajustar seus critérios de pesquisa ou filtro",incoming:"Entrada",outgoing:"Saída",loggingStopped:"Registro interrompido",loggingActive:"Registro ativo - as mensagens serão atualizadas automaticamente",startLogging:"Iniciar Registro",stopLogging:"Parar Registro",clearLog:"Limpar Registro",topic:"ópico",timestamp:"Carimbo de Data/Hora",direction:"Direção",all:"Todos"},printerFiles:{title:"Gerenciador de Arquivos",storageUsed:"Usado:",storageFree:"Livre:",filterPlaceholder:"Filtrar arquivos...",deleteButton:"Excluir",deleteFiles:"Excluir {{count}} arquivos",deleteFileConfirm:'Excluir "{{name}}"? Isso não pode ser desfeito.',deleteFilesConfirm:"Excluir {{count}} arquivos selecionados? Isso não pode ser desfeito.",noFiles:"Nenhum arquivo na impressora",loadingFiles:"Carregando arquivos...",failedToLoad:"Falha ao carregar arquivos",toast:{filesDeleted:"Arquivos excluídos: {{count}}",deleteFailed:"Falha ao excluir: {{error}}"}},confirm:{delete:"Tem certeza de que deseja excluir isso?",unsavedChanges:"Você tem alterações não salvas. Tem certeza de que deseja sair?",clearQueue:"Tem certeza de que deseja limpar a fila?"},login:{title:"Bambuddy Login",subtitle:"Faça login na sua conta",username:"Nome de usuário",usernamePlaceholder:"Digite seu nome de usuário",usernameOrEmail:"Nome de usuário ou Email",usernameOrEmailPlaceholder:"Nome de usuário ou Email",password:"Senha",passwordPlaceholder:"Digite sua senha",signIn:"Entrar",signingIn:"Entrando...",forgotPassword:"Esqueceu sua senha?",loginSuccess:"Login realizado com sucesso",loginFailed:"Falha no login",enterCredentials:"Por favor, insira nome de usuário e senha",forgotPasswordTitle:"Esqueceu a Senha",forgotPasswordMessage:"Se você esqueceu sua senha, entre em contato com o administrador do sistema para redefini-la.",forgotPasswordEmailMessage:"Digite seu endereço de email e enviaremos uma nova senha.",emailAddress:"Endereço de Email",emailPlaceholder:"seu.email@exemplo.com",cancel:"Cancelar",sending:"Enviando...",sendResetEmail:"Enviar Email de Redefinição",howToReset:"Como redefinir sua senha:",resetStep1:"Entre em contato com o administrador do Bambuddy",resetStep2:"Peça para redefinir sua senha na Gestão de Usuários",resetStep3:"Eles podem definir uma nova senha temporária para você",resetStep4:"Faça login com a nova senha e altere-a nas Configurações",gotIt:"Entendi"},setup:{title:"Bambuddy Configuração",subtitle:"Configure a autenticação para sua instância do Bambuddy",enableAuth:"Ativar Autenticação",adminAccount:"Conta de Administrador",adminAccountDesc:"Se usuários administradores já existirem, a autenticação será ativada usando as contas de administrador existentes. Deixe os campos abaixo vazios para usar os administradores existentes ou insira novas credenciais para criar um novo usuário administrador.",adminUsername:"Nome de usuário do administrador",adminPassword:"Senha do administrador",optionalIfAdminExists:"(opcional se usuários administradores existirem)",adminUsernamePlaceholder:"Digite o nome de usuário do administrador (opcional)",adminPasswordPlaceholder:"Digite a senha do administrador (opcional)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha do administrador",settingUp:"Configurando...",completeSetup:"Concluir Configuração",toast:{authEnabledAdminCreated:"Autenticação ativada e usuário administrador criado",authEnabledExistingAdmins:"Autenticação ativada usando usuários administradores existentes",setupCompleted:"Configuração concluída",enterBothCredentials:"Por favor, insira o nome de usuário e a senha do administrador, ou deixe ambos vazios para usar os usuários administradores existentes",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres"}},changePassword:{title:"Alterar Senha",currentPassword:"Senha Atual",currentPasswordPlaceholder:"Digite a senha atual",newPassword:"Nova Senha",newPasswordPlaceholder:"Digite a nova senha (mínimo 6 caracteres)",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a nova senha",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres",changing:"Alterando...",success:"Senha alterada com sucesso",failed:"Falha ao alterar a senha"},plateAlert:{title:"Impressão Pausada!",message:"Objetos detectados na mesa de impressão. A impressão foi automaticamente pausada. Por favor, limpe a mesa e retome a impressão.",understand:"Entendi"},camera:{title:"Visualização da Câmera",invalidPrinterId:"ID da impressora inválido",live:"Ao Vivo",snapshot:"Captura",restartStream:"Reiniciar transmissão",refreshSnapshot:"Atualizar captura",fullscreen:"Tela Cheia",exitFullscreen:"Sair da Tela Cheia",connectingToCamera:"Conectando à câmera...",capturingSnapshot:"Capturando imagem...",connectionLost:"Conexão perdida",connectionFailed:"Falha na conexão com a câmera",reconnecting:"Reconectando em {{countdown}}s... (tentativa {{attempt}}/{{max}})",reconnectNow:"Reconectar agora",cameraUnavailable:"Câmera indisponível",cameraUnavailableDesc:"Certifique-se de que a impressora está ligada e conectada.",noCamera:"Nenhuma câmera disponível",retry:"Tentar novamente",cameraStream:"Transmissão da câmera",zoomOut:"Reduzir zoom",zoomIn:"Aumentar zoom",resetZoom:"Redefinir zoom",recording:"Gravando",startRecording:"Iniciar gravação",stopRecording:"Parar gravação",chamberLight:"Alternar luz da câmara"},groups:{title:"Gerenciamento de Grupos",subtitle:"Gerenciar grupos de permissão para controle de acesso",backToSettings:"Voltar para Configurações",createGroup:"Criar Grupo",noPermission:"Você não tem permissão para acessar esta página.",system:"Sistema",noDescription:"Sem descrição",usersCount:"{{count}} usuários",permissionsCount:"{{count}} permissões",edit:"Editar",delete:"Excluir",toast:{created:"Grupo criado com sucesso",updated:"Grupo atualizado com sucesso",deleted:"Grupo excluído com sucesso",enterGroupName:"Por favor, insira um nome para o grupo"},modal:{editGroup:"Editar Grupo",createGroup:"Criar Grupo",cancel:"Cancelar",saving:"Salvando...",creating:"Criando...",saveChanges:"Salvar Alterações"},form:{groupName:"Nome do Grupo",groupNamePlaceholder:"Insira o nome do grupo",systemGroupWarning:"Os nomes dos grupos do sistema não podem ser alterados",description:"Descrição",descriptionPlaceholder:"Insira a descrição (opcional)",permissions:"Permissões ({{count}} selecionadas)"},deleteModal:{title:"Excluir Grupo",message:"Tem certeza de que deseja excluir este grupo? Os usuários deste grupo perderão essas permissões.",confirm:"Excluir Grupo"},editor:{title:"Editar Grupo",createTitle:"Criar Grupo",search:"Pesquisar permissões...",selectAll:"Selecionar Tudo",clearAll:"Limpar Tudo",permissionsSelected:"{{count}} selecionada(s)",noResults:"Nenhuma permissão corresponde à sua pesquisa"}},users:{title:"Gerenciamento de Usuários",subtitle:"Gerenciar usuários e seu acesso à sua instância do Bambuddy",backToSettings:"Voltar para Configurações",createUser:"Criar Usuário",noPermission:"Você não tem permissão para acessar esta página.",admin:"Admin",noGroups:"Sem grupos",active:"Ativo",inactive:"Inativo",edit:"Editar",delete:"Excluir",system:"Sistema",noGroupsAvailable:"Nenhum grupo disponível",table:{username:"Nome de Usuário",groups:"Grupos",status:"Status",actions:"Ações"},toast:{created:"Usuário criado com sucesso",updated:"Usuário atualizado com sucesso",deleted:"Usuário excluído com sucesso",fillRequired:"Por favor, preencha todos os campos obrigatórios",passwordsDoNotMatch:"As senhas não coincidem",passwordTooShort:"A senha deve ter pelo menos 6 caracteres"},modal:{createUser:"Criar Usuário",editUser:"Editar Usuário",cancel:"Cancelar",creating:"Criando...",saving:"Salvando...",saveChanges:"Salvar Alterações",advancedAuthSubtitle:"com Autenticação Avançada"},form:{username:"Nome de Usuário",usernamePlaceholder:"Insira o nome de usuário",email:"Email",emailPlaceholder:"user@example.com",password:"Senha",passwordPlaceholder:"Insira a senha",confirmPassword:"Confirmar Senha",confirmPasswordPlaceholder:"Confirme a senha",newPasswordPlaceholder:"Insira a nova senha",confirmNewPasswordPlaceholder:"Confirme a nova senha",leaveBlankToKeep:"deixe em branco para manter a atual",groups:"Grupos",optional:"opcional",autoGeneratedPassword:"Uma senha segura será gerada automaticamente e enviada por e-mail ao usuário.",passwordManagedByAdvancedAuth:'A senha é gerenciada pela Autenticação Avançada. Use "Redefinir Senha" para enviar uma nova senha ao usuário por e-mail.',resetPassword:"Redefinir Senha",resettingPassword:"Redefinindo Senha..."},deleteModal:{title:"Excluir Usuário",message:"Tem certeza de que deseja excluir este usuário? Esta ação não pode ser desfeita.",confirm:"Excluir Usuário"}},streamOverlay:{title:"Stream Overlay",invalidPrinterId:"ID da impressora inválido",cameraStream:"Transmissão da câmera",progress:"Progresso da impressão",eta:"ETA",printerIdle:"Impressora ociosa",printerOffline:"Impressora offline",status:{printing:"Imprimindo",paused:"Pausado",finished:"Concluído",failed:"Falhou",idle:"Ocioso",unknown:"Desconhecido"}},profiles:{title:"Perfis",subtitle:"Gerencie seus presets de fatiador e calibrações de avanço de pressão",tabs:{cloud:"Perfis na Nuvem",local:"Perfis Locais",kprofiles:"K-Perfis"},localProfiles:{title:"Perfis Locais",subtitle:"Importe e gerencie presets de fatiador do OrcaSlicer",import:"Importar Perfis",importDesc:"Solte arquivos .bbscfg, .bbsflmt, .orca_filament, .zip ou .json aqui",importing:"Importando...",search:"Pesquisar presets locais...",noPresets:"Nenhum preset local ainda",badge:"Local",edit:"Editar",delete:"Excluir",cancel:"Cancelar",deleteConfirmTitle:"Excluir Preset",deleteConfirm:"Tem certeza de que deseja excluir este preset? Esta ação não pode ser desfeita.",source:"Fonte",inheritsFrom:"Herdado de",filamentType:"Tipo",vendor:"Fornecedor",compatiblePrinters:"Impressoras Compatíveis",nozzleTemp:"Temperatura do Bico",cost:"Custo",density:"Densidade",pressureAdvance:"Avanço de Pressão",filament:"Filamento",process:"Processo",printer:"Impressora",toast:{importSuccess:"{{count}} preset(s) importada(s)",importSkipped:"{{count}} preset(s) ignorada(s) (duplicadas)",importError:"{{count}} erro(s) durante a importação",deleted:"Preset excluído",updated:"Preset atualizado"}},connectedAs:"Conectado como",logout:"Sair",noLogoutPermission:"Você não tem permissão para sair",failedToLoad:"Falha ao carregar perfis",retry:"Tentar novamente",time:{justNow:"Agora mesmo",minsAgo:"há {{count}} minutos",hoursAgo:"há {{count}} horas",daysAgo:"há {{count}} dias"},toast:{loggedOut:"Desconectado"},login:{title:"Conectar ao Bambu Cloud",subtitle:"Sincronize seus presets de fatiador entre dispositivos",email:"Email",password:"Senha",region:"Região",regionGlobal:"Global",regionChina:"China",verificationCode:"Código de Verificação",totpCode:"Código do Autenticador",checkEmail:"Verifique seu email ({{email}}) para um código de 6 dígitos",enterTotpHint:"Digite o código de 6 dígitos do seu aplicativo autenticador",accessToken:"Token de Acesso",accessTokenHint:"Cole seu token de acesso Bambu Lab (do Bambu Studio)",back:"Voltar",loginButton:"Entrar",verifyButton:"Verificar",setTokenButton:"Definir Token",useToken:"Usar token de acesso em vez disso",useEmail:"Entrar com email em vez disso",toast:{loggedIn:"Conectado com sucesso",codeSent:"Código de verificação enviado para seu email",enterTotp:"Digite o código do seu aplicativo autenticador",tokenSet:"Token definido com sucesso"}},presets:{myPreset:"Meu preset (editável)",duplicate:"Duplicar",editable:"Editável",failedToLoadDetails:"Falha ao carregar detalhes do preset",deleteConfirm:"Excluir este preset?",deleteWarning:'Isso excluirá permanentemente "{{name}}" do Bambu Cloud. Esta ação não pode ser desfeita.',noDuplicatePermission:"Você não tem permissão para duplicar presets",noEditPermission:"Você não tem permissão para editar presets",noDeletePermission:"Você não tem permissão para excluir presets",types:{filament:"Preset de filamento",printer:"Preset de impressora",process:"Preset de processo"},toast:{deleted:"Preset excluído",created:"Preset criado",updated:"Preset atualizado",duplicated:"Preset duplicado",fieldAdded:'Campo "{{key}}" adicionado',exported:"Preset exportado"},baseLabel:"Base: {{name}}",currentLabel:"Atual: {{name}}",newPreset:"Novo Preset",editPreset:"Editar Preset",duplicatePreset:"Duplicar Preset",createNewPreset:"Criar Novo Preset",customizeSettings:"Personalizar configurações para seu novo preset",compareWithBase:"Comparar com o preset base",compare:"Comparar",basePreset:"Preset Base",selectBasePreset:"Selecionar preset base...",presetName:"Nome do Preset",myCustomPreset:"Meu preset personalizado",inheritsFrom:"Herdado de",dropJsonToImport:"Solte o arquivo JSON para importar",tabs:{common:"Comum",allFields:"Todos os Campos"},availableFields:"Campos Disponíveis",searchFieldsPlaceholder:"Pesquisar campos...",noMatchingFields:"Nenhum campo correspondente",allFieldsAdded:"Todos os campos adicionados",addCustomField:"Adicionar campo personalizado",yourOverrides:"Suas Substituições",noOverridesYet:"Nenhuma substituição ainda",clickFieldsToAdd:"Clique nos campos à esquerda para adicioná-los",saveAsTemplate:"Salvar como modelo",jsonTip:"Dica: Arraste e solte um arquivo .json em qualquer lugar deste modal para importar configurações"},cloudView:{searchPlaceholder:"Pesquisar presets...",templates:"Modelos",refresh:"Atualizar",newPreset:"Novo Preset",clearFilters:"Limpar filtros",compareMode:"Modo de Comparação",selectAnotherPreset:"Selecionar outro preset {{type}}",clickTwoPresets:"Clique em dois presets do mesmo tipo para comparar",selectFirst:"1. Selecionar primeiro",selectSecond:"2. Selecionar segundo",compareNow:"Comparar Agora",lastSynced:"Última sincronização:",showingCount:"Mostrando {{showing}} de {{total}} presets",noPresetsFound:"Nenhum preset encontrado",columns:{filament:"Filamento",process:"Processo",printer:"Impressora"},noFilamentPresets:"Nenhum preset de filamento",noProcessPresets:"Nenhum preset de processo",noPrinterPresets:"Nenhum preset de impressora",filters:{type:"Tipo",owner:"Proprietário",printer:"Impressora",nozzle:"Bico",filament:"Filamento",layer:"Camada",all:"Todos",myPresets:"Meus Presets",builtIn:"Integrado",process:"Processo"},noTemplatesPermission:"Você não tem permissão para gerenciar modelos",noRefreshPermission:"Você não tem permissão para atualizar perfis",noCreatePermission:"Você não tem permissão para criar presets"},templates:{title:"Modelos Rápidos",noTemplates:"Nenhum modelo ainda",createFirst:"Crie modelos a partir do editor de presets",typeFilter:"Tipo:",deleteTitle:"Excluir Modelo",deleteWarning:"Esta ação não pode ser desfeita",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',namePlaceholder:"Nome do modelo",descriptionPlaceholder:"Descrição",settingsJson:"Configurações (JSON)",fieldsCount:"{{count}} campos",shownInModals:"Exibido em modais",hiddenInModals:"Oculto em modais",apply:"Aplicar",toast:{deleted:"Modelo excluído",updated:"Modelo atualizado",created:"Modelo criado",applied:"Modelo aplicado"}}},support:{debugLoggingActive:"Registro de depuração ativo",manageLogs:"Gerenciar",collectItem7:"Conectividade da impressora e versões de firmware",collectItem8:"Status de integração (Spoolman, MQTT, HA)",collectItem9:"Interfaces de rede (somente sub-redes)",collectItem10:"Versões de pacotes Python",collectItem11:"Verificações de integridade do banco de dados",collectItem12:"Detalhes do ambiente Docker"},fileManager:{title:"Gerenciador de Arquivos",subtitle:"Organize e gerencie seus arquivos de impressão",uploadFiles:"Enviar Arquivos",newFolder:"Nova Pasta",folderName:"Nome da Pasta",folderNamePlaceholder:"ex.: Peças Funcionais",renameFile:"Renomear Arquivo",renameFolder:"Renomear Pasta",moveFiles:"Mover {{count}} Arquivo(s)",rootNoFolder:"Raiz (Sem Pasta)",current:"Atual",linkFolder:"Vincular Pasta",linkFolderDescription:'Vincular "{{name}}" a um projeto ou arquivo para acesso rápido.',project:"Projeto",archive:"Arquivo",noProjectsFound:"Nenhum projeto encontrado",noArchivesFound:"Nenhum arquivo encontrado",unlink:"Desvincular",link:"Vincular",dragDropFiles:"Arraste e solte os arquivos aqui",dropFilesHere:"Solte os arquivos aqui",orClickToBrowse:"ou clique para procurar",allFileTypesSupported:"Todos os tipos de arquivos são suportados. Arquivos ZIP serão extraídos.",zipFilesDetected:"Arquivos ZIP detectados",zipExtractOptions:"Arquivos ZIP serão extraídos. Escolha como lidar com a estrutura de pastas:",preserveZipStructure:"Preservar estrutura de pastas do ZIP",createFolderFromZip:"Criar pasta a partir do nome do arquivo ZIP",stlThumbnailGeneration:"Geração de miniaturas STL",zipMayContainStl:"Arquivos ZIP podem conter arquivos STL. Miniaturas podem ser geradas durante a extração.",thumbnailsCanBeGenerated:"Miniaturas podem ser geradas para arquivos STL. Modelos grandes podem levar mais tempo para processar.",generateThumbnailsForStl:"Gerar miniaturas para arquivos STL",threemfDetected:"Arquivos 3MF detectados",threemfExtractionInfo:"Modelo da impressora, material, cor e configurações de impressão serão extraídos automaticamente dos arquivos 3MF.",willBeExtracted:"Será extraído",filesExtracted:"{{count}} arquivos extraídos",uploadComplete:"Upload concluído: {{succeeded}} bem-sucedidos",uploadFailed:"{{count}} falhou",uploading:"Enviando...",changeLink:"Alterar link...",linkTo:"Vincular a...",linkToProjectOrArchive:"Vincular a projeto ou arquivo",addToQueue:"Adicionar à fila",schedulePrint:"Agendar impressão",generateThumbnail:"Gerar miniatura",generateThumbnails:"Gerar miniaturas",generateThumbnailsForMissing:"Gerar miniaturas para arquivos STL que não possuem",gridView:"Visualização em grade",listView:"Visualização em lista",lowDiskSpaceWarning:"Aviso de pouco espaço em disco",lowDiskSpaceDetails:"Apenas {{free}} livres de {{total}} no total. O limite está definido para {{threshold}} GB nas configurações.",files:"Arquivos",folders:"Pastas",size:"Tamanho",free:"Livre",allFiles:"Todos os arquivos",wrap:"Quebrar texto",enableTextWrapping:"Ativar quebra de texto",disableTextWrapping:"Desativar quebra de texto",dragToResizeTooltip:"Arraste para redimensionar, clique duas vezes para redefinir",searchFiles:"Pesquisar arquivos...",allTypes:"Todos os tipos",prints:"Impressões",ascending:"Crescente",descending:"Decrescente",resultsCount:"{{showing}} de {{total}} arquivos",selectAll:"Selecionar tudo",deselectAll:"Desmarcar tudo",selected:"{{count}} selecionado(s)",adding:"Adicionando...",loadingFiles:"Carregando arquivos...",folderIsEmpty:"A pasta está vazia",noFilesYet:"Nenhum arquivo ainda",folderEmptyDescription:"Envie arquivos ou mova arquivos para esta pasta para começar.",noFilesDescription:"Envie arquivos para começar a organizar seus arquivos relacionados à impressão.",noMatchingFiles:"Nenhum arquivo correspondente",noMatchingFilesDescription:"Nenhum arquivo corresponde aos seus critérios de pesquisa ou filtro.",clearFilters:"Limpar filtros",printedCount:"Impresso {{count}}x",uploadedBy:"Enviado por",deleteFolder:"Excluir pasta",deleteFile:"Excluir arquivo",deleteFilesCount:"Excluir {{count}} arquivos",deleteFolderConfirm:"Tem certeza de que deseja excluir esta pasta? Todos os arquivos dentro também serão excluídos.",deleteFileConfirm:"Tem certeza de que deseja excluir este arquivo?",deleteFilesConfirm:"Tem certeza de que deseja excluir {{count}} arquivos selecionados? Esta ação não pode ser desfeita.",deleting:"Excluindo...",noPermissionRenameFolder:"Você não tem permissão para renomear pastas",noPermissionLinkFolder:"Você não tem permissão para vincular pastas",noPermissionDeleteFolder:"Você não tem permissão para excluir pastas",noPermissionPrint:"Você não tem permissão para imprimir",noPermissionAddToQueue:"Você não tem permissão para adicionar à fila",noPermissionDownload:"Você não tem permissão para baixar arquivos",noPermissionRenameFile:"Você não tem permissão para renomear este arquivo",noPermissionGenerateThumbnail:"Você não tem permissão para gerar miniaturas",noPermissionDeleteFile:"Você não tem permissão para excluir este arquivo",noPermissionCreateFolder:"Você não tem permissão para criar pastas",noPermissionUpload:"Você não tem permissão para enviar arquivos",noPermissionMoveFiles:"Você não tem permissão para mover arquivos",noPermissionDeleteFiles:"Você não tem permissão para excluir arquivos",toast:{folderCreated:"Pasta criada",folderDeleted:"Pasta excluída",fileDeleted:"Arquivo excluído",filesDeleted:"Excluídos {{count}} arquivos",filesMoved:"Arquivos movidos",folderLinked:"Pasta vinculada",folderUnlinked:"Pasta desvinculada",addedToQueue:"Adicionado {{count}} arquivo(s) à fila",addedToQueuePartial:"Adicionado {{added}} arquivo(s), {{failed}} falharam",failedToAddToQueue:"Falha ao adicionar arquivos: {{error}}",fileRenamed:"Arquivo renomeado",folderRenamed:"Pasta renomeada",thumbnailsGenerated:"Geradas {{count}} miniatura(s)",thumbnailsGeneratedPartial:"Geradas {{succeeded}} miniatura(s), {{failed}} falharam",noStlMissingThumbnails:"Nenhum arquivo STL sem miniatura",failedToGenerateThumbnails:"Falha ao gerar miniaturas: {{error}}",thumbnailGenerated:"Miniatura gerada",failedToGenerateThumbnail:"Falha ao gerar miniatura: {{error}}"}},projects:{title:"Projetos",subtitle:"Organize e acompanhe seus projetos de impressão 3D",newProject:"Novo Projeto",editProject:"Editar Projeto",deleteProject:"Excluir Projeto",projectName:"Nome do Projeto",description:"Descrição",noProjects:"Nenhum projeto ainda",noProjectsFiltered:"Nenhum projeto {{status}}",noProjectsFilteredHelp:"Você não tem nenhum projeto {{status}}. Os projetos aparecerão aqui quando seu status mudar.",createFirst:"Crie seu primeiro projeto para começar a organizar impressões relacionadas, acompanhar o progresso e gerenciar suas construções.",createFirstButton:"Crie Seu Primeiro Projeto",create:"Criar",files:"Arquivos",prints:"Impressões",plates:"Placas",parts:"Peças",lastModified:"Última Modificação",deleteConfirm:"Tem certeza de que deseja excluir este projeto? Arquivos e itens da fila serão desvinculados, mas não excluídos.",addFiles:"Adicionar Arquivos",removeFile:"Remover Arquivo",viewDetails:"Ver Detalhes",namePlaceholder:"ex., Voron 2.4 Build",descriptionPlaceholder:"Descrição opcional...",color:"Cor",targetPlates:"Placas Alvo",targetPlatesPlaceholder:"ex., 25",targetPlatesHelp:"Número de trabalhos de impressão",targetParts:"Peças Alvo",targetPartsPlaceholder:"ex., 150",targetPartsHelp:"Total de objetos necessários",tagsLabel:"Tags (separadas por vírgula)",tagsPlaceholder:"ex., voron, funcional, presente",dueDate:"Data de Vencimento",priority:"Prioridade",priorityLow:"Baixa",priorityNormal:"Normal",priorityHigh:"Alta",priorityUrgent:"Urgente",statusActive:"Ativo",statusCompleted:"Concluído",statusArchived:"Arquivado",done:"Concluído",completed:"Concluído",failed:"Falhou",inQueue:"Na fila",noPrintsYet:"Nenhuma impressão ainda",printJobs:"Trabalhos de impressão (placas)",partsPrinted:"Peças impressas",failedParts:"Peças falhadas",import:"Importar",export:"Exportar",importProject:"Importar projeto",exportAll:"Exportar todos os projetos",loading:"Carregando projetos...",noEditPermission:"Você não tem permissão para editar projetos",noDeletePermission:"Você não tem permissão para excluir projetos",noCreatePermission:"Você não tem permissão para criar projetos",noImportPermission:"Você não tem permissão para importar projetos",noExportPermission:"Você não tem permissão para exportar projetos",toast:{created:"Projeto criado",updated:"Projeto atualizado",deleted:"Projeto excluído",imported:"Projeto importado",multipleImported:"{{count}} projetos importados",importFailed:"Falha na importação",exported:"Projetos exportados (apenas metadados)"}},projectDetail:{notFound:"Projeto não encontrado",backToProjects:"Voltar para Projetos",export:"Exportar",exportProject:"Exportar projeto",noExportPermission:"Você não tem permissão para exportar projetos",noEditPermission:"Você não tem permissão para editar projetos",partOf:"Parte de:",priorityLabel:"Prioridade:",noPrints:"Nenhuma impressão neste projeto ainda",status:{active:"Ativo",completed:"Concluído",archived:"Arquivado"},priority:{low:"Baixa",normal:"Normal",high:"Alta",urgent:"Urgente"},dueDate:{overdue:"Atrasado",today:"Vence hoje",daysLeft:"{{count}} dias restantes"},progress:{platesProgress:"Progresso das Placas",partsProgress:"Progresso das Peças",printJobs:"Trabalhos de Impressão",parts:"Peças",percentComplete:"{{percent}}% concluído",remaining:"{{count}} restantes"},stats:{printJobs:"Trabalhos de Impressão",total:"total",failed:"{{count}} falhou",partsPrinted:"{{count}} peças impressas",printTime:"Tempo de Impressão",filamentUsed:"Filamento Usado"},cost:{title:"Rastreamento de Custos",filamentCost:"Custo do Filamento",energy:"Energia",budget:"Orçamento",remaining:"Restante"},subProjects:{title:"Sub-projetos ({{count}})"},notes:{title:"Notas",noEditPermission:"Você não tem permissão para editar notas",placeholder:"Adicione notas sobre este projeto...",empty:"Nenhuma nota ainda. Clique em Editar para adicionar notas."},files:{title:"Arquivos",linkFolders:"Vincular pastas do Gerenciador de Arquivos",forQuickAccess:"a este projeto para acesso rápido.",fileCount:"{{count}} arquivo(s)",empty:"Nenhuma pasta vinculada. Vá para o Gerenciador de Arquivos e vincule uma pasta a este projeto."},bom:{title:"Lista de Materiais",acquired:"{{completed}}/{{total}} adquiridos",showAll:"Mostrar todos",hideDone:"Ocultar concluídos",addPart:"Adicionar Peça",noAddPermission:"Você não tem permissão para adicionar peças",partNamePlaceholder:"Nome da peça (ex.: parafusos M3x8)",partName:"Nome da peça",qty:"Quantidade",price:"Preço ({{currency}})",sourcingUrlPlaceholder:"URL de fornecimento (opcional)",remarksPlaceholder:"Observações (opcional)",deletePart:"Excluir Peça",deleteConfirm:'Tem certeza de que deseja excluir "{{name}}"?',noUpdatePermission:"Você não tem permissão para atualizar peças",noEditPermission:"Você não tem permissão para editar peças",noDeletePermission:"Você não tem permissão para excluir peças",totalCost:"Custo total:",empty:"Nenhuma peça na lista de materiais. Adicione hardware, eletrônicos ou outros componentes para rastrear o que precisa ser adquirido."},timeline:{title:"Linha do Tempo de Atividades",empty:"Nenhuma atividade ainda."},template:{saveAsTemplate:"Salvar como Modelo",noCreatePermission:"Você não tem permissão para criar modelos"},queue:{title:"Fila",viewAll:"Ver todos",printing:"{{count}} imprimindo",queued:"{{count}} na fila"},prints:{title:"Impressões ({{count}})"},toast:{projectUpdated:"Projeto atualizado",partAdded:"Peça adicionada",partRemoved:"Peça removida",exportFailed:"Falha na exportação",projectExported:"Projeto exportado",templateCreated:"Modelo criado"}},system:{title:"Informações do Sistema",version:"Versão",uptime:"Tempo de Atividade",cpuUsage:"Uso da CPU",memoryUsage:"Uso da Memória",diskUsage:"Uso do Disco",networkInfo:"Informações de Rede",logs:"Logs",debugMode:"Modo de Depuração",enableDebug:"Ativar Registro de Depuração",disableDebug:"Desativar Registro de Depuração",downloadLogs:"Baixar Logs",clearLogs:"Limpar Logs",dockerInfo:"Informações do Docker",containerName:"Nome do Contêiner",imageName:"Nome da Imagem",platform:"Plataforma",architecture:"Arquitetura"},library:{title:"Biblioteca de Filamentos",addFilament:"Adicionar Filamento",editFilament:"Editar Filamento",deleteFilament:"Excluir Filamento",vendor:"Fornecedor",material:"Material",color:"Cor",kFactor:"Fator K",temperature:"Temperatura",noFilaments:"Nenhum filamento na biblioteca",deleteConfirm:"Tem certeza de que deseja excluir este filamento?",importFromPrinter:"Importar da Impressora",exportToFile:"Exportar para Arquivo"},spoolman:{title:"Integração com Spoolman",enabled:"Spoolman Ativado",url:"URL do Spoolman",connected:"Conectado",disconnected:"Não Conectado",testConnection:"Testar Conexão",sync:"Sincronizar",syncing:"Sincronizando...",lastSync:"Última Sincronização",linkToSpoolman:"Vincular ao Spoolman",openInSpoolman:"Abrir no Spoolman",unlinkSpool:"Desvincular Carretel",selectSpool:"Selecionar Carretel",noUnlinkedSpools:"Nenhum carretel desvinculado disponível",linkSuccess:"Carretel vinculado ao Spoolman com sucesso",linkFailed:"Falha ao vincular carretel",spoolId:"Carretel ID (Spool ID)",fillSourceLabel:"(Spoolman)",weight:"Peso",remaining:"Restante",disableWeightSync:"Desativar Sincronização de Peso Estimado do AMS",disableWeightSyncDesc:"Não atualize a capacidade restante a partir das estimativas do AMS. Use isso se preferir o rastreamento de uso do Spoolman em vez das estimativas baseadas em porcentagem do AMS. Novos carretéis ainda usarão a estimativa do AMS como seu peso inicial.",reportPartialUsage:"Relatar Uso Parcial para Impressões Falhadas",reportPartialUsageDesc:"Quando uma impressão falha ou é cancelada, relate o filamento estimado usado até aquele ponto com base no progresso das camadas."},inventory:{title:"Inventário de Carretéis",addSpool:"Adicionar Carretel",editSpool:"Editar Carretel",material:"Material",selectMaterial:"Selecionar material...",subtype:"Subtipo",brand:"Marca",searchBrand:"Pesquisar marca...",useCustomBrand:'Usar "{{brand}}"',useCustomMaterial:"Usar material personalizado: {{material}}",colorName:"Nome da Cor",colorNamePlaceholder:"Jade White, Fire Red...",color:"Cor",hexColor:"Cor Hexadecimal",pickColor:"Escolher cor personalizada",labelWeight:"Peso da Etiqueta",coreWeight:"Peso do Carretel Vazio",searchSpoolWeight:"Pesquisar peso do carretel...",weightUsed:"Usado",currentWeight:"Peso Restante",measuredWeight:"Peso Medido",costPerKg:"Custo por kg",measuredWeightError:"O peso medido deve estar entre {{min}}g e {{max}}g.",slicerFilament:"Filamento do Fatiador",slicerFilamentName:"Nome do Predefinido do Fatiador",slicerPreset:"Predefinido do Fatiador",searchPresets:"Pesquisar predefinições de filamento...",selectedPreset:"Selecionado",noPresetsFound:"Nenhuma predefinição encontrada",tempOverrides:"Substituições de Temperatura",note:"Nota",notePlaceholder:"Quaisquer notas adicionais sobre este spool...",archive:"Arquivar",restore:"Restaurar",noSpools:"Nenhum carretel ainda. Adicione seu primeiro carretel para começar.",noManualSpools:"Nenhum carretel adicionado manualmente disponível. Adicione um carretel ao seu inventário primeiro.",kProfiles:"K-Perfis",addKProfile:"Adicionar K-Perfil",assignSpool:"Atribuir Carretel",unassignSpool:"Desatribuir",assignSuccess:"Carretel atribuído e slot AMS configurado",assignFailed:"Falha ao atribuir carretel",selectSpool:"Selecione um carretel para atribuir a este slot",assigned:"Atribuído",assigning:"Atribuindo...",searchSpools:"Pesquisar carretéis...",allMaterials:"Todos os Materiais",filterByBrand:"Filtrar por marca...",showArchived:"Mostrar arquivados",quickAdd:"Adição rápida (Estoque)",quantity:"Quantidade",stock:"Estoque",configured:"Configurado",spoolsCreated:"{{count}} carretéis criados",spoolCreated:"Carretel criado",spoolUpdated:"Carretel atualizado",spoolDeleted:"Carretel excluído",spoolArchived:"Carretel arquivado",spoolRestored:"Carretel restaurado",deleteConfirm:"Tem certeza de que deseja excluir este carretel? Esta ação não pode ser desfeita.",archiveConfirm:"Tem certeza de que deseja arquivar este carretel?",advancedSettings:"Configurações Avançadas",filamentInfoTab:"Informações do Filamento",paProfileTab:"Perfil PA",filamentInfo:"Filamento",additional:"Adicional",loadingPresets:"Carregando predefinições da nuvem...",cloudConnected:"Nuvem conectada",cloudNotConnected:"Nuvem não conectada (usando padrões)",recentColors:"Recentes",searchColors:"Pesquisar cores...",searchResults:"Resultados da pesquisa",allColors:"Todas as cores",commonColors:"Cores comuns",showLess:"Mostrar menos",showAll:"Mostrar tudo",noColorsFound:"Nenhuma cor corresponde à sua pesquisa",noResults:"Nenhum resultado encontrado",selectMaterialFirst:"Por favor, selecione um material primeiro na aba Informações do Filamento.",noPrintersConfigured:"Nenhuma impressora configurada. Adicione impressoras para usar perfis PA.",matchingFilter:"Correspondente",anyBrand:"Qualquer marca",anyVariant:"Qualquer variante",autoSelect:"Seleção automática",matches:"correspondências",match:"correspondência",noMatches:"Nenhuma correspondência",connected:"Conectado",offline:"Offline",printerOffline:"A impressora está offline. Conecte-se para visualizar os perfis de calibração.",noKProfilesMatch:"Nenhum K-perfil corresponde ao filamento selecionado.",leftNozzle:"Bico Esquerdo",rightNozzle:"Bico Direito",profilesSelected:"perfil(is) de calibração selecionado(s)",totalInventory:"Inventário Total",totalConsumed:"Total Consumido",byMaterial:"Por Material",inPrinter:"Na Impressora",lowStock:"Estoque Baixo",sinceTracking:"Desde o início do rastreamento",loadedInAms:"Carregado no AMS/Ext",remaining:"Restante",lowStockThreshold:"<20% restante",search:"Pesquisar carretéis...",showing:"Mostrando",to:"até",of:"de",show:"Mostrar",spools:"carretéis",spool:"carretel",page:"Página",noSpoolsMatch:"Nenhum resultado encontrado",noSpoolsMatchDesc:"Tente ajustar sua pesquisa ou filtros para encontrar o que você está procurando.",active:"Ativo",archived:"Arquivado",all:"Todos",used:"Usado",new:"Novo",clearFilters:"Limpar filtros",table:"Tabela",cards:"Cartões",net:"Líquido",columns:"Colunas",configureColumns:"Configurar Colunas",configureColumnsDesc:"Arraste para reordenar as colunas ou use as setas. Alterne a visibilidade com o ícone de olho.",visible:"Visível",reset:"Redefinir",cancel:"Cancelar",applyChanges:"Aplicar Alterações",moveUp:"Mover para cima",moveDown:"Mover para baixo",hideColumn:"Ocultar coluna",showColumn:"Mostrar coluna",linkToSpool:"Vincular ao Carretel",tagLinked:"Tag vinculada ao carretel",tagLinkFailed:"Falha ao vincular tag",tagAlreadyLinked:"Tag já vinculada a outro carretel",unknownTag:"Tag RFID desconhecida detectada",usageHistory:"Histórico de Uso",noUsageHistory:"Nenhum uso registrado ainda",printName:"Nome da Impressão",weightConsumed:"Peso Consumido",clearHistory:"Limpar",historyCleared:"Histórico de uso limpo",fillSourceLabel:"(Inv)"},timelapse:{title:"Timelapse",create:"Criar Timelapse",download:"Baixar",delete:"Excluir",preview:"Visualizar",frameRate:"Taxa de Quadros",quality:"Qualidade",processing:"Processando...",noTimelapses:"Nenhum timelapse disponível"},ams:{title:"AMS",slot:"Slot",empty:"Vazio",emptySlot:"Slot vazio",unknown:"Desconhecido",humidity:"Umidade",temperature:"Temperatura",filamentType:"Tipo de Filamento",filamentColor:"Cor",remaining:"Restante",history:"Histórico do AMS",noHistory:"Nenhum histórico disponível",configureSlot:"Configurar Slot",externalSpool:"Carretel Externo",profile:"Perfil",kFactor:"Fator K",fill:"Preencher",configure:"Configurar"},printModal:{title:"Iniciar Impressão",selectPrinter:"Selecionar Impressora",selectPlate:"Selecionar Placa",filamentMapping:"Mapeamento de Filamento",totalCost:"Custo total:",printSettings:"Configurações de Impressão",bedLeveling:"Nivelamento da Mesa",flowCalibration:"Calibração de Fluxo",vibrationCalibration:"Calibração de Vibração",layerInspection:"Inspeção da Primeira Camada",timelapse:"Timelapse",startPrint:"Iniciar Impressão",addToQueue:"Adicionar à Fila",cancel:"Cancelar",noPrintersAvailable:"Nenhuma impressora disponível",printerBusy:"Impressora ocupada",printerOffline:"Impressora offline",sameTypeDifferentColor:"Mesmo tipo, cor diferente",filamentTypeNotLoaded:"Tipo de filamento não carregado",openCalendar:"Abrir calendário",leftNozzle:"L",rightNozzle:"R",leftNozzleTooltip:"Bico esquerdo",rightNozzleTooltip:"Bico direito",filamentOverride:"Substituição de Filamento",filamentOverrideHint:"Substitua opcionalmente os filamentos para atribuição baseada em modelo. O agendador usará os filamentos selecionados em vez dos valores originais do 3MF.",originalFilament:"Original",overrideWith:"Substituir por",resetToOriginal:"Restaurar original"},backup:{title:"Bakup e Restauração",createBackup:"Criar Backup",restoreBackup:"Restaurar Backup",restoreDescription:"Substituir todos os dados a partir de um arquivo de backup",downloadBackup:"Baixar Backup",uploadBackup:"Enviar Backup",lastBackup:"Último Backup",autoBackup:"Auto Backup",backupNow:"Fazer Backup Agora",restoreWarning:"Aviso: Restaurar um backup substituirá todos os dados atuais.",includeArchives:"Incluir Arquivos",includeSettings:"Incluir Configurações",includeProfiles:"Incluir Perfis",backupSuccess:"Backup criado com sucesso",restoreSuccess:"Backup restaurado com sucesso",backupFailed:"Falha ao criar backup",restoreFailed:"Falha ao restaurar backup",restoreNote:"A impressora virtual será parada durante a restauração"},tags:{title:"Tags",addTag:"Adicionar Tag",editTag:"Editar Tag",deleteTag:"Excluir Tag",tagName:"Nome da Tag",tagColor:"Cor da Tag",noTags:"Nenhuma tag",deleteConfirm:"Tem certeza de que deseja excluir esta tag?",manageTags:"Gerenciar Tags"},uploadModal:{title:"Upload Arquivos 3MF",dragDrop:"Arraste e solte arquivos .3mf aqui",or:"ou",browseFiles:"Procurar Arquivos",extractionInfo:"O modelo da impressora será extraído automaticamente dos metadados do arquivo 3MF.",uploaded:"enviado",failed:"falhou",uploading:"Enviando...",upload:"Enviar",uploadFailed:"Falha no envio"},editArchive:{title:"Editar Arquivo",name:"Nome",namePlaceholder:"Nome da impressão",printer:"Impressora",noPrinter:"Nenhuma impressora",project:"Projeto",noProject:"Nenhum projeto",itemsPrinted:"Itens Impressos",itemsPrintedHelp:"Número de itens produzidos neste trabalho de impressão",notes:"Notas",notesPlaceholder:"Adicione notas sobre esta impressão...",externalLink:"Link Externo",externalLinkPlaceholder:"https://printables.com/model/...",externalLinkHelp:"Link para Printables, Thingiverse ou outra fonte",tags:"Tags",tagsPlaceholder:"Adicionar tags...",addMoreTags:"Adicionar mais tags...",matchingTags:'Correspondendo "{{query}}"',existingTags:"Tags existentes",clickToAdd:"(clique para adicionar)",status:"Status",failureReason:"Motivo da Falha",selectReason:"Selecione o motivo...",photos:"Fotos do Resultado da Impressão",photosHelp:"Clique em + para adicionar fotos do seu resultado impresso",printResult:"Resultado da Impressão",saving:"Salvando...",failureReasons:{adhesionFailure:"Falha de adesão",spaghettiDetached:"Spaghetti / Destacado",layerShift:"Deslocamento de camada",cloggedNozzle:"Bico entupido",filamentRunout:"Fim do filamento",warping:"Warping",stringing:"Stringing",underExtrusion:"Under-extrusion",powerFailure:"Falha de energia",userCancelled:"Cancelado pelo usuário",other:"Outro"},statuses:{completed:"Concluído",failed:"Falhou",aborted:"Cancelado",printing:"Imprimindo"}},kProfiles:{title:"K-Profiles",noPrintersConfigured:"Nenhuma impressora configurada",addPrinterInSettings:"Adicione uma impressora nas Configurações para gerenciar K-profiles",noActivePrinters:"Nenhuma impressora ativa",enablePrinterConnection:"Ative a conexão da impressora para visualizar seus K-profiles",loadingProfiles:"Carregando K-Profiles...",printerOffline:"Impressora Offline",printerOfflineDesc:"A impressora selecionada não está conectada. Ligue-a para visualizar os K-profiles.",noMatchingProfiles:"Nenhum Perfil Correspondente",noMatchingProfilesDesc:"Nenhum perfil corresponde aos seus critérios de pesquisa",noKProfiles:"Nenhum K-Profile",noKProfilesDesc:"Nenhum perfil de avanço de pressão encontrado para bico de {{diameter}}mm",createFirstProfile:"Criar Primeiro Perfil",printer:"Impressora",nozzle:"Bico",refresh:"Atualizar",addProfile:"Adicionar Perfil",export:"Exportar",import:"Importar",select:"Selecionar",selectAll:"Selecionar Todos",delete:"Excluir",searchPlaceholder:"Pesquisar por nome ou filamento...",allExtruders:"Todos os Extrusores",leftOnly:"Apenas Esquerdo",rightOnly:"Apenas Direito",allFlow:"Todo Fluxo",hfOnly:"Apenas HF",sOnly:"Apenas S",sortName:"Ordenar: Nome",sortKValue:"Ordenar: Valor K",sortFilament:"Ordenar: Filamento",leftExtruder:"Extrusor Esquerdo",rightExtruder:"Extrusor Direito",modal:{addTitle:"Adicionar K-Profile",editTitle:"Editar K-Profile",profileName:"Nome do Perfil",profileNamePlaceholder:"Meu Perfil PLA",kValue:"Valor K",kValuePlaceholder:"0.020",kValueHelp:"Faixa típica: 0.01 - 0.06 para PLA, 0.02 - 0.10 para PETG",filament:"Filamento",selectFilament:"Selecionar filamento...",noFilamentsHelp:"Nenhum filamento encontrado. Crie um K-profile no Bambu Studio primeiro.",flowType:"Tipo de Fluxo",highFlow:"Alto Fluxo",standard:"Padrão",nozzleSize:"Tamanho do Bico",extruder:"Extrusor",extruders:"Extrusores",left:"Esquerdo",right:"Direito",notes:"Notas (armazenadas localmente)",notesPlaceholder:"Adicione notas sobre este perfil...",notesHelp:"As notas são salvas no Bambuddy, não na impressora",syncing:"Sincronizando com a impressora...",savingExtruder:"Salvando no extrusor {{current}}/{{total}}...",pleaseWait:"Por favor, aguarde"},deleteConfirm:{title:"Excluir Perfil",cannotUndo:"Isso não pode ser desfeito",message:'Tem certeza de que deseja excluir "{{name}}" da impressora?'},bulkDelete:{title:"Excluir Perfis",cannotUndo:"Isso não pode ser desfeito",message:"Tem certeza de que deseja excluir {{count}} perfis selecionados da impressora?"},toast:{profileSaved:"K-profile salvo",profilesSaved:"K-profile salvo em {{count}} extrusores",selectAtLeastOneExtruder:"Por favor, selecione pelo menos um extrusor",profileDeleted:"K-profile excluído",profilesDeleted:"{{count}} perfis excluídos",exportedProfiles:"{{count}} perfis exportados",importedProfiles:"{{count}} de {{total}} perfis importados",noProfilesToExport:"Nenhum perfil para exportar",invalidFileFormat:"Formato de arquivo inválido",failedToParseImport:"Falha ao analisar o arquivo de importação",failedToSaveBatch:"Falha ao salvar K-profiles",noteSaved:"Nota salva",failedToSaveNote:"Falha ao salvar nota"},permission:{noRead:"Você não tem permissão para atualizar perfis",noCreate:"Você não tem permissão para adicionar perfis",noUpdate:"Você não tem permissão para atualizar K-profiles",noDelete:"Você não tem permissão para excluir K-profiles",noExport:"Você não tem permissão para exportar perfis",noImport:"Você não tem permissão para importar perfis"}},virtualPrinter:{title:"Impressora Virtual",running:"Em execução",stopped:"Parada",description:{default:"Ative uma impressora virtual que aparece no Bambu Studio e no OrcaSlicer. Os arquivos enviados para esta impressora serão arquivados diretamente sem impressão.",proxy:"Ative um proxy que retransmite o tráfego do slicer para uma impressora real, permitindo impressão remota em qualquer rede."},enable:{title:"Ativar Impressora Virtual",visibleInSlicer:'Visível como "Bambuddy" na descoberta do slicer',proxyingTo:"Proxy para {{name}}",notActive:"Não ativo"},model:{title:"Modelo da Impressora",description:"Selecione qual modelo de impressora emular.",restartWarning:"Alterar o modelo reiniciará a impressora virtual"},accessCode:{title:"Código de acesso",isSet:"O código de acesso está definido",notSet:"Nenhum código de acesso definido — necessário para ativar.",placeholder:"Digite um código de 8 caracteres",placeholderChange:"Digite um novo código para alterar",hint:"Deve ter exatamente 8 caracteres. Usado pelos slicers para autenticação.",charCount:"({{count}}/8)"},targetPrinter:{title:"Impressora Alvo",configured:"Proxy alvo configurado",notConfigured:"Nenhuma impressora alvo selecionada - necessário para o modo proxy",placeholder:"Selecione uma impressora...",hint:"Selecione a impressora para a qual o tráfego do slicer será enviado. A impressora deve estar no modo LAN.",noPrinters:"Nenhuma impressora configurada. Adicione uma impressora primeiro para usar o modo proxy."},remoteInterface:{title:"Substituição da Interface de Rede",configured:"Substituição da interface ativa",optional:"Opcional - use se o IP detectado automaticamente estiver errado (por exemplo, várias NICs, Docker, VPN)",placeholder:"Detecção automática (padrão)...",hint:"Substitua o endereço IP anunciado via SSDP e usado no certificado TLS. Útil quando o Bambuddy possui várias interfaces de rede."},mode:{title:"Modo",archive:"Arquivar",archiveDesc:"Arquivar arquivos imediatamente",review:"Revisar",reviewDesc:"Revisar antes de arquivar",queue:"Fila",queueDesc:"Arquivar e adicionar à fila",proxy:"Proxy",proxyDesc:"Retransmitir para impressora real"},setupRequired:{title:"Configuração Necessária",description:"O recurso de impressora virtual requer configuração adicional do sistema antes de funcionar. Isso inclui encaminhamento de portas, regras de firewall e configurações específicas da plataforma.",readGuide:"Leia o guia de configuração antes de ativar"},howItWorks:{title:"Como funciona",titleProxy:"Como funciona (Modo Proxy)",step1:"Complete o guia de configuração para sua plataforma",step2:"Ative a impressora virtual e defina um código de acesso",step3:'No Bambu Studio ou OrcaSlicer, vá para "Adicionar Impressora"',step4:'A impressora "Bambuddy" deve aparecer na lista de descoberta',step5:"Conecte-se usando o código de acesso que você definiu",step6:'Quando você "imprimir" para o Bambuddy, o arquivo 3MF será arquivado em vez disso',proxyStep1:"Selecione a impressora alvo (deve estar no modo LAN)",proxyStep2:"Para rede cruzada: selecione a interface de rede do slicer",proxyStep3:"Ative o proxy - a impressora aparece na descoberta do slicer via SSDP",proxyStep4:"Conecte-se usando o código de acesso da impressora",proxyStep5:"Imprima normalmente - o tráfego é retransmitido pelo Bambuddy",proxyStep6:"O streaming da câmera requer NAT/encaminhamento de IP (veja a documentação)"},status:{title:"Detalhes do Status",printerName:"Nome da Impressora",model:"Modelo",serialNumber:"Número de Série",mode:"Modo",pendingFiles:"Arquivos Pendentes",targetPrinter:"Impressora Alvo",ftpPort:"Porta FTP",mqttPort:"Porta MQTT",ftpConnections:"Conexões FTP",mqttConnections:"Conexões MQTT"},toast:{updated:"Configurações da impressora virtual atualizadas",failedToUpdate:"Falha ao atualizar as configurações",accessCodeRequired:"Defina um código de acesso primeiro",targetPrinterRequired:"Selecione uma impressora alvo primeiro",accessCodeEmpty:"O código de acesso não pode estar vazio",accessCodeLength:"O código de acesso deve ter exatamente 8 caracteres"}},modelViewer:{openInSlicer:"Abrir no Slicer",tabs:{model:"Modelo 3D",gcode:"Pré-visualização G-code"},notAvailable:"Não disponível",notSliced:"Não fatiado",plates:"Placas",allPlates:"Todas as Placas",plateNumber:"Placa {{number}}",plateCount:"{{count}} placa",plateCount_other:"{{count}} placas",objectCount:"{{count}} objeto",objectCount_other:"{{count}} objetos",filamentCount:"{{count}} filamento",filamentCount_other:"{{count}} filamentos",eta:"ETA {{minutes}} min",noPreview:"Pré-visualização não disponível para este arquivo",pagination:{pageOf:"Página {{current}} de {{total}}",prev:"Anterior",next:"Próximo"},errors:{failedToLoad:"Falha ao carregar o arquivo",noMeshes:"Nenhuma malha encontrada no arquivo 3MF",unsupportedFormat:"Formato de arquivo não suportado"}},maintenanceDescriptions:{lubricateCarbonRods:"Aplique lubrificante nos eixos de carbono para um movimento suave",lubricateRails:"Aplique lubrificante nos trilhos lineares para um movimento suave",cleanNozzle:"Limpe o hotend e o bico para evitar entupimentos",checkBelts:"Verifique a tensão das correias para impressões precisas",cleanBuildPlate:"Limpe a placa de construção para melhor adesão",checkExtruder:"Verifique as engrenagens do extrusor quanto ao desgaste",checkCooling:"Verifique se os ventiladores de resfriamento estão funcionando corretamente",generalInspection:"Inspeção geral da impressora",cleanCarbonRods:"Limpe os eixos de carbono para reduzir o atrito",cleanLinearRails:"Limpe os trilhos lineares para remover poeira e detritos",checkPtfeTube:"Verifique o tubo PTFE quanto ao desgaste ou danos",replaceHepaFilter:"Substitua o filtro HEPA para qualidade do ar",replaceCarbonFilter:"Substitua o filtro de carbono ativado",lubricateLeftNozzleRail:"Lubrifique o trilho do bico esquerdo (série H2)"},smartPlugs:{offline:"Offline",admin:"Admin",openPlugAdminPage:"Abrir o painel de administração da tomada inteligente",deleteSmartPlug:"Excluir Tomada Inteligente",turnOnSmartPlug:"Ligar Tomada Inteligente",turnOffSmartPlug:"Desligar Tomada Inteligente",turnOn:"Ligar",turnOff:"Desligar",addSmartPlug:{scanningNetwork:"Procurando na rede...",chooseEntity:"Escolha uma entidade...",connectionFailed:"Falha na conexão",searchEntities:"Pesquisar entidades...",searchPowerSensors:"Pesquisar sensores de energia...",searchEnergySensors:"Pesquisar sensores de energia...",placeholders:{plugName:"Tomada da Sala",mqttStateOnValue:"ON, true, 1",mqttSameAsPower:"Mesmo que o tópico de energia, ou diferente"}}},richTextEditor:{bold:"Negrito",italic:"Itálico",underline:"Sublinhado",bulletList:"Lista com marcadores",numberedList:"Lista numerada",alignLeft:"Alinhar à esquerda",alignCenter:"Centralizar",alignRight:"Alinhar à direita",addLink:"Adicionar link",removeLink:"Remover link"},externalLinks:{noLinksConfigured:"Nenhum link externo configurado",deleteLink:"Excluir link",removeCustomIcon:"Remover ícone personalizado",openInNewTab:"Abrir em nova aba",placeholders:{linkName:"Meu Link"}},keyboardShortcuts:{title:"Atalhos de Teclado",navigation:"Navegação",archivesSection:"Arquivos",kProfilesSection:"K-Profiles",generalSection:"Geral",shortcuts:{goToPrinters:"Ir para Impressoras",goToArchives:"Ir para Arquivos",goToQueue:"Ir para Fila",goToStats:"Ir para Estatísticas",goToProfiles:"Ir para Perfis na Nuvem",goToSettings:"Ir para Configurações",focusSearch:"Focar na pesquisa",openUploadModal:"Abrir modal de upload",clearSelection:"Limpar seleção / desfocar input",contextMenu:"Menu de contexto nos cartões",refreshProfiles:"Atualizar perfis",newProfile:"Novo perfil",exitSelectionMode:"Sair do modo de seleção",showHelp:"Mostrar esta ajuda"},footer:"Pressione Esc ou clique fora para fechar"},notificationLog:{title:"Registro de Notificações",events:{printStarted:"Impressão Iniciada",printComplete:"Impressão Concluída",printFailed:"Impressão Falhou",printStopped:"Impressão Interrompida",progress:"Progresso",printerOffline:"Impressora Offline",printerError:"Erro na Impressora",lowFilament:"Filamento Baixo",maintenanceDue:"Manutenção Pendente",test:"Teste"},timeAgo:{justNow:"Agora mesmo",minutesAgo:"há {{minutes}} minutos",hoursAgo:"há {{hours}} horas"}},restoreBackup:{title:"Restaurar Backup",restoring:"Restaurando...",restoreComplete:"Restauração Concluída",restoreFailed:"Falha na Restauração",importSettings:"Importar configurações de um arquivo de backup",pleaseWait:"Aguarde enquanto seus dados estão sendo restaurados",clickToSelect:"Clique para selecionar o arquivo de backup (.json ou .zip)",howDuplicateHandling:"Como funciona o tratamento de duplicatas:",categories:{printers:"Impressoras",smartPlugs:"Tomadas Inteligentes",notificationProviders:"Provedores de Notificação",filaments:"Filamentos",archives:"Arquivos",pendingUploads:"Uploads Pendentes",settingsTemplates:"Configurações e Modelos"},matchingInfo:{printers:"correspondem pelo número de série",smartPlugs:"correspondem pelo endereço IP",notificationProviders:"correspondem pelo nome",filaments:"correspondem pelo nome + tipo + marca",archives:"correspondem pelo hash do conteúdo",pendingUploads:"correspondem pelo nome do arquivo",settingsTemplates:"sempre sobrescrito"},replaceExisting:"Substituir dados existentes",keepExisting:"Manter dados existentes",replaceDescription:"Substituir itens que já existem com os dados do backup",keepDescription:"Restaurar apenas itens que não existem",caution:"Atenção:",cautionText:"Sobrescrever substituirá suas configurações atuais pelos dados do backup. Os códigos de acesso da impressora nunca são sobrescritos por segurança.",itemsRestored:"Itens Restaurados",itemsSkipped:"Itens Ignorados",restored:"Restaurado",skipped:"Ignorado (já existe)",filesLabel:"Arquivos (3MF, miniaturas, etc.)",newApiKeysGenerated:"Novas Chaves API Geradas",newApiKeysWarning:"Essas chaves são exibidas apenas uma vez. Copie-as agora!",processingBackup:"Processando arquivo de backup...",noDataFound:"Nenhum dado foi encontrado para restaurar no arquivo de backup.",failedToRestore:"Falha ao restaurar o backup. Verifique o formato do arquivo."},backupExport:{title:"Exportar Backup",selectData:"Selecione os dados a incluir",selectAll:"Selecionar Todos",selectNone:"Selecionar Nenhum",categoryDescriptions:{settings:"Idioma, tema, preferências de atualização",notifications:"ntfy, Pushover, Discord, etc.",templates:"Modelos de mensagens personalizadas",smartPlugs:"Configurações de tomadas Tasmota",externalLinks:"Links da barra lateral para serviços externos",printers:"Informações da impressora (códigos de acesso excluídos)",plateDetection:"Imagens de referência de placa vazia",filaments:"Tipos e custos de filamento",maintenance:"Cronogramas de manutenção personalizados",archives:"Todos os dados de impressão + arquivos (3MF, miniaturas, fotos)",projects:"Projetos, itens de BOM e anexos",pendingUploads:"Uploads de impressora virtual aguardando revisão",apiKeys:"Chaves API de webhook (novas chaves geradas na importação)"},requiresPrinters:"Requer que as impressoras sejam selecionadas",zipFileWarning:"Um arquivo ZIP será criado.",zipFileDescription:"Inclui todos os arquivos 3MF, miniaturas, timelapses e fotos. Isso pode levar algum tempo e resultar em um arquivo grande.",includeAccessCodes:"Incluir Códigos de Acesso",includeAccessCodesDescription:"Para transferir para outra máquina",includeAccessCodesWarning:"Os códigos de acesso serão incluídos em texto simples. Mantenha este arquivo de backup seguro!",categoriesSelected:"{{selectedCount}} categorias selecionadas"},pendingUploads:{placeholders:{notes:"Adicione notas sobre esta impressão..."},discardUpload:"Descartar Upload",archiveAllUploads:"Arquivar Todos os Uploads",discardAllUploads:"Descartar Todos os Uploads",archive:"Arquivar",timeAgo:{justNow:"Agora mesmo",minutesAgo:"há {{minutes}} minutos",hoursAgo:"há {{hours}} horas",daysAgo:"há {{days}} dias"}},apiBrowser:{placeholders:{requestBody:"Corpo da requisição JSON...",searchEndpoints:"Pesquisar endpoints..."}},configureAmsSlot:{title:"Configurar Slot AMS",slotConfigured:"Slot Configurado!",configuringSlot:"Configurando slot:",slotLabel:"{{ams}} Slot {{slot}}",searchPresets:"Pesquisar predefinições...",colorPlaceholder:"Nome da cor ou hex (ex.: marrom, FF8800)",clearCustomColor:"Limpar cor personalizada",noCloudPresets:"Nenhuma predefinição na nuvem. Faça login no Bambu Cloud para sincronizar.",noPresetsAvailable:"Nenhuma predefinição disponível. Faça login no Bambu Cloud ou importe perfis locais.",noMatchingPresets:"Nenhuma predefinição correspondente encontrada.",custom:"Personalizado",builtin:"Integrado",settingsSentToPrinter:"Configurações enviadas para a impressora",filamentProfile:"Perfil de Filamento",kProfileLabel:"Perfil K (Avanço de Pressão)",filteringFor:"Filtrando por: {{material}}",noKProfile:"Nenhum perfil K (usar padrão 0.020)",noMatchingKProfiles:"Nenhum perfil K correspondente encontrado. O K padrão=0.020 será usado.",selectFilamentFirst:"Selecione um perfil de filamento primeiro",kFromCalibration:"K={{value}} da calibração da impressora",customColorLabel:"Cor Personalizada (opcional)",presetColors:"Cores de {{name}}:",showLessColors:"Mostrar menos cores",showMoreColors:"Mostrar mais cores",clear:"Limpar",hexLabel:"Hex: #{{hex}}",resetting:"Redefinindo...",resetSlot:"Redefinir Slot",cancel:"Cancelar",configuring:"Configurando...",configureSlot:"Configurar Slot"},githubBackup:{title:"Backup do GitHub",history:"Histórico",downloadBackup:"Baixar Backup",restoreBackup:"Restaurar Backup",noBackupsYet:"Nenhum backup ainda"},emailSettings:{placeholders:{fromName:"BamBuddy"}},tagManagement:{searchTags:"Pesquisar tags...",renameTag:"Renomear tag",deleteTag:"Excluir tag"},notificationTemplates:{placeholders:{title:"Título da notificação...",body:"Corpo da notificação..."}},batchTag:{placeholders:{newTag:"Digite uma nova tag..."}},photoGallery:{deletePhoto:"Excluir foto"},filamentHoverCard:{copySpoolUuid:"Copiar UUID do carretel"},kProfilesView:{hasNote:"Possui nota",copyProfile:"Copiar perfil"},layout:{openMenu:"Abrir menu",noPermissionSystemInfo:"Você não tem permissão para visualizar informações do sistema"},dashboard:{dragToReorder:"Arrastar para reordenar",hideWidget:"Ocultar widget"},notificationProviderCard:{deleteNotificationProvider:"Excluir provedor de notificação"},fileManagerModal:{closeFileManager:"Fechar gerenciador de arquivos",sortFiles:"Ordenar arquivos",goToParentFolder:"Ir para a pasta pai",threeView:"Visualização 3D"},embeddedCameraViewer:{refreshStream:"Atualizar stream",close:"Fechar",zoomOut:"Reduzir zoom",resetZoom:"Redefinir zoom",zoomIn:"Aumentar zoom",dragToResize:"Arrastar para redimensionar"},timelapseViewer:{skipBack5s:"Voltar 5s",skipForward5s:"Avançar 5s"},notificationProviders:{descriptions:{email:"Notificações por email SMTP",telegram:"Notificações via bot do Telegram",discord:"Enviar para canal do Discord via webhook",ntfy:"Notificações push gratuitas e auto-hospedáveis",pushover:"Notificações push simples e confiáveis",callmebot:"Notificações gratuitas via WhatsApp pelo CallMeBot",webhook:"POST HTTP genérico para qualquer URL"}},logViewer:{searchPlaceholder:"Pesquisar mensagem ou nome do logger...",noLogEntries:"Nenhuma entrada de log encontrada"},switchbarPopover:{noSwitchesInSwitchbar:"Nenhum switch na barra de switches"},projectPageModal:{placeholders:{title:"Título",designer:"Designer",license:"Licença",description:"Digite a descrição...",profileTitle:"Título do perfil",profileDescription:"Descrição do perfil..."}},spoolmanSettings:{},spoolbuddy:{nav:{dashboard:"Painel",ams:"AMS",inventory:"Inventário",printers:"Impressoras",settings:"Configurações"},status:{nfcReady:"Pronto",nfcOff:"Desligado",offline:"Dispositivo offline"},dashboard:{idleMessage:"Coloque o carretel na balança e escaneie a tag NFC"},weight:{noReading:"Sem leitura",stable:"Estável",measuring:"Medindo",tare:"Tara",calibrate:"Calibrar",tareQueued:"Comando de tara enviado"},spool:{remaining:"Restante"},tag:{unknownTitle:"Tag desconhecida",linkExisting:"Vincular a carretel existente",createNew:"Criar novo carretel"},actions:{assignAms:"Atribuir AMS",updateWeight:"Atualizar peso",editSpool:"Editar carretel",viewHistory:"Ver histórico",weightUpdated:"Peso do carretel atualizado"},ams:{noData:"Nenhum dado AMS disponível"},inventory:{search:"Buscar carretéis...",empty:"Nenhum carretel encontrado"},printers:{noPrinters:"Nenhuma impressora configurada"},settings:{scaleCalibration:"Calibração da balança",currentWeight:"Peso atual",tareOffset:"Offset de tara",knownWeight:"Peso conhecido",calibrated:"Calibração atualizada",tareQueued:"Comando de tara na fila",nfcReader:"Leitor NFC",nfcConnected:"Conectado",nfcDisconnected:"Desconectado",deviceInfo:"Info do dispositivo",deviceId:"ID do dispositivo",uptime:"Tempo ativo",firmware:"Firmware"}}},fce={en:{translation:lce},de:{translation:cce},fr:{translation:uce},ja:{translation:dce},it:{translation:hce},"pt-BR":{translation:mce}};zs.use(kK).use(Ule).init({resources:fce,fallbackLng:"en",supportedLngs:["en","de","fr","ja","it","pt-BR"],detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:"bambutrack_language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!1}});const bB=[{code:"en",name:"English",nativeName:"English"},{code:"de",name:"German",nativeName:"Deutsch"},{code:"fr",name:"French",nativeName:"Français"},{code:"ja",name:"Japanese",nativeName:"日本語"},{code:"it",name:"Italian",nativeName:"Italiano"},{code:"pt-BR",name:"Portuguese (Brazil)",nativeName:"Português (Brasil)"}];var xB="popstate";function pce(t={}){function e(r,a){let{pathname:s,search:o,hash:l}=r.location;return V2("",{pathname:s,search:o,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function n(r,a){return typeof a=="string"?a:fv(a)}return bce(e,n,null,t)}function ua(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function xl(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function gce(){return Math.random().toString(36).substring(2,10)}function yB(t,e){return{usr:t.state,key:t.key,idx:e}}function V2(t,e,n=null,r){return{pathname:typeof t=="string"?t:t.pathname,search:"",hash:"",...typeof e=="string"?Ub(e):e,state:n,key:e&&e.key||r||gce()}}function fv({pathname:t="/",search:e="",hash:n=""}){return e&&e!=="?"&&(t+=e.charAt(0)==="?"?e:"?"+e),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function Ub(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substring(n),t=t.substring(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substring(r),t=t.substring(0,r)),t&&(e.pathname=t)}return e}function bce(t,e,n,r={}){let{window:a=document.defaultView,v5Compat:s=!1}=r,o=a.history,l="POP",c=null,u=d();u==null&&(u=0,o.replaceState({...o.state,idx:u},""));function d(){return(o.state||{idx:null}).idx}function h(){l="POP";let g=d(),y=g==null?null:g-u;u=g,c&&c({action:l,location:v.location,delta:y})}function f(g,y){l="PUSH";let _=V2(v.location,g,y);u=d()+1;let N=yB(_,u),k=v.createHref(_);try{o.pushState(N,"",k)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(k)}s&&c&&c({action:l,location:v.location,delta:1})}function p(g,y){l="REPLACE";let _=V2(v.location,g,y);u=d();let N=yB(_,u),k=v.createHref(_);o.replaceState(N,"",k),s&&c&&c({action:l,location:v.location,delta:0})}function x(g){return xce(g)}let v={get action(){return l},get location(){return t(a,o)},listen(g){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(xB,h),c=g,()=>{a.removeEventListener(xB,h),c=null}},createHref(g){return e(a,g)},createURL:x,encodeLocation(g){let y=x(g);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:f,replace:p,go(g){return o.go(g)}};return v}function xce(t,e=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ua(n,"No window.location.(origin|href) available to create URL");let r=typeof t=="string"?t:fv(t);return r=r.replace(/ $/,"%20"),!e&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function AK(t,e,n="/"){return yce(t,e,n,!1)}function yce(t,e,n,r){let a=typeof e=="string"?Ub(e):e,s=Zu(a.pathname||"/",n);if(s==null)return null;let o=TK(t);vce(o);let l=null;for(let c=0;l==null&&c<o.length;++c){let u=Ece(s);l=Mce(o[c],u,r)}return l}function TK(t,e=[],n=[],r="",a=!1){let s=(o,l,c=a,u)=>{let d={relativePath:u===void 0?o.path||"":u,caseSensitive:o.caseSensitive===!0,childrenIndex:l,route:o};if(d.relativePath.startsWith("/")){if(!d.relativePath.startsWith(r)&&c)return;ua(d.relativePath.startsWith(r),`Absolute route path "${d.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),d.relativePath=d.relativePath.slice(r.length)}let h=$u([r,d.relativePath]),f=n.concat(d);o.children&&o.children.length>0&&(ua(o.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${h}".`),TK(o.children,e,f,h,c)),!(o.path==null&&!o.index)&&e.push({path:h,score:Ace(h,o.index),routesMeta:f})};return t.forEach((o,l)=>{if(o.path===""||!o.path?.includes("?"))s(o,l);else for(let c of MK(o.path))s(o,l,!0,c)}),e}function MK(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,a=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return a?[s,""]:[s];let o=MK(r.join("/")),l=[];return l.push(...o.map(c=>c===""?s:[s,c].join("/"))),a&&l.push(...o),l.map(c=>t.startsWith("/")&&c===""?"/":c)}function vce(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:Tce(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var wce=/^:[\w-]+$/,Sce=3,_ce=2,Nce=1,Cce=10,kce=-2,vB=t=>t==="*";function Ace(t,e){let n=t.split("/"),r=n.length;return n.some(vB)&&(r+=kce),e&&(r+=_ce),n.filter(a=>!vB(a)).reduce((a,s)=>a+(wce.test(s)?Sce:s===""?Nce:Cce),r)}function Tce(t,e){return t.length===e.length&&t.slice(0,-1).every((r,a)=>r===e[a])?t[t.length-1]-e[e.length-1]:0}function Mce(t,e,n=!1){let{routesMeta:r}=t,a={},s="/",o=[];for(let l=0;l<r.length;++l){let c=r[l],u=l===r.length-1,d=s==="/"?e:e.slice(s.length)||"/",h=b1({path:c.relativePath,caseSensitive:c.caseSensitive,end:u},d),f=c.route;if(!h&&u&&n&&!r[r.length-1].route.index&&(h=b1({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},d)),!h)return null;Object.assign(a,h.params),o.push({params:a,pathname:$u([s,h.pathname]),pathnameBase:Fce($u([s,h.pathnameBase])),route:f}),h.pathnameBase!=="/"&&(s=$u([s,h.pathnameBase]))}return o}function b1(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=Pce(t.path,t.caseSensitive,t.end),a=e.match(n);if(!a)return null;let s=a[0],o=s.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((u,{paramName:d,isOptional:h},f)=>{if(d==="*"){let x=l[f]||"";o=s.slice(0,s.length-x.length).replace(/(.)\/+$/,"$1")}const p=l[f];return h&&!p?u[d]=void 0:u[d]=(p||"").replace(/%2F/g,"/"),u},{}),pathname:s,pathnameBase:o,pattern:t}}function Pce(t,e=!1,n=!0){xl(t==="*"||!t.endsWith("*")||t.endsWith("/*"),`Route path "${t}" will be treated as if it were "${t.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${t.replace(/\*$/,"/*")}".`);let r=[],a="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,l,c)=>(r.push({paramName:l,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return t.endsWith("*")?(r.push({paramName:"*"}),a+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":t!==""&&t!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,e?void 0:"i"),r]}function Ece(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return xl(!1,`The URL path "${t}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),t}}function Zu(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}var jce=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Dce(t,e="/"){let{pathname:n,search:r="",hash:a=""}=typeof t=="string"?Ub(t):t,s;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?s=wB(n.substring(1),"/"):s=wB(n,e)):s=e,{pathname:s,search:Lce(r),hash:Oce(a)}}function wB(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function LM(t,e,n,r){return`Cannot include a '${t}' character in a manually specified \`to.${e}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Rce(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function lF(t){let e=Rce(t);return e.map((n,r)=>r===e.length-1?n.pathname:n.pathnameBase)}function cF(t,e,n,r=!1){let a;typeof t=="string"?a=Ub(t):(a={...t},ua(!a.pathname||!a.pathname.includes("?"),LM("?","pathname","search",a)),ua(!a.pathname||!a.pathname.includes("#"),LM("#","pathname","hash",a)),ua(!a.search||!a.search.includes("#"),LM("#","search","hash",a)));let s=t===""||a.pathname==="",o=s?"/":a.pathname,l;if(o==null)l=n;else{let h=e.length-1;if(!r&&o.startsWith("..")){let f=o.split("/");for(;f[0]==="..";)f.shift(),h-=1;a.pathname=f.join("/")}l=h>=0?e[h]:"/"}let c=Dce(a,l),u=o&&o!=="/"&&o.endsWith("/"),d=(s||o===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||d)&&(c.pathname+="/"),c}var $u=t=>t.join("/").replace(/\/\/+/g,"/"),Fce=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),Lce=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,Oce=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t,Ice=class{constructor(t,e,n,r=!1){this.status=t,this.statusText=e||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function zce(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}function Uce(t){return t.map(e=>e.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var PK=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function EK(t,e){let n=t;if(typeof n!="string"||!jce.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(PK)try{let s=new URL(window.location.href),o=n.startsWith("//")?new URL(s.protocol+n):new URL(n),l=Zu(o.pathname,e);o.origin===s.origin&&l!=null?n=l+o.search+o.hash:a=!0}catch{xl(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var jK=["POST","PUT","PATCH","DELETE"];new Set(jK);var Bce=["GET",...jK];new Set(Bce);var Bb=w.createContext(null);Bb.displayName="DataRouter";var zC=w.createContext(null);zC.displayName="DataRouterState";var Hce=w.createContext(!1),DK=w.createContext({isTransitioning:!1});DK.displayName="ViewTransition";var $ce=w.createContext(new Map);$ce.displayName="Fetchers";var Vce=w.createContext(null);Vce.displayName="Await";var Io=w.createContext(null);Io.displayName="Navigation";var o0=w.createContext(null);o0.displayName="Location";var kl=w.createContext({outlet:null,matches:[],isDataRoute:!1});kl.displayName="Route";var uF=w.createContext(null);uF.displayName="RouteError";var RK="REACT_ROUTER_ERROR",qce="REDIRECT",Gce="ROUTE_ERROR_RESPONSE";function Wce(t){if(t.startsWith(`${RK}:${qce}:{`))try{let e=JSON.parse(t.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function Kce(t){if(t.startsWith(`${RK}:${Gce}:{`))try{let e=JSON.parse(t.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new Ice(e.status,e.statusText,e.data)}catch{}}function Xce(t,{relative:e}={}){ua(Hb(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=w.useContext(Io),{hash:a,pathname:s,search:o}=c0(t,{relative:e}),l=s;return n!=="/"&&(l=s==="/"?n:$u([n,s])),r.createHref({pathname:l,search:o,hash:a})}function Hb(){return w.useContext(o0)!=null}function Vc(){return ua(Hb(),"useLocation() may be used only in the context of a <Router> component."),w.useContext(o0).location}var FK="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function LK(t){w.useContext(Io).static||w.useLayoutEffect(t)}function rc(){let{isDataRoute:t}=w.useContext(kl);return t?cue():Yce()}function Yce(){ua(Hb(),"useNavigate() may be used only in the context of a <Router> component.");let t=w.useContext(Bb),{basename:e,navigator:n}=w.useContext(Io),{matches:r}=w.useContext(kl),{pathname:a}=Vc(),s=JSON.stringify(lF(r)),o=w.useRef(!1);return LK(()=>{o.current=!0}),w.useCallback((c,u={})=>{if(xl(o.current,FK),!o.current)return;if(typeof c=="number"){n.go(c);return}let d=cF(c,JSON.parse(s),a,u.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:$u([e,d.pathname])),(u.replace?n.replace:n.push)(d,u.state,u)},[e,n,s,a,t])}var OK=w.createContext(null);function IK(){return w.useContext(OK)}function Qce(t){let e=w.useContext(kl).outlet;return w.useMemo(()=>e&&w.createElement(OK.Provider,{value:t},e),[e,t])}function l0(){let{matches:t}=w.useContext(kl),e=t[t.length-1];return e?e.params:{}}function c0(t,{relative:e}={}){let{matches:n}=w.useContext(kl),{pathname:r}=Vc(),a=JSON.stringify(lF(n));return w.useMemo(()=>cF(t,JSON.parse(a),r,e==="path"),[t,a,r,e])}function Zce(t,e){return zK(t,e)}function zK(t,e,n,r,a){ua(Hb(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=w.useContext(Io),{matches:o}=w.useContext(kl),l=o[o.length-1],c=l?l.params:{},u=l?l.pathname:"/",d=l?l.pathnameBase:"/",h=l&&l.route;{let _=h&&h.path||"";BK(u,!h||_.endsWith("*")||_.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${_}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
  10. Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}/*`}">.`)}let f=Vc(),p;if(e){let _=typeof e=="string"?Ub(e):e;ua(d==="/"||_.pathname?.startsWith(d),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${d}" but pathname "${_.pathname}" was given in the \`location\` prop.`),p=_}else p=f;let x=p.pathname||"/",v=x;if(d!=="/"){let _=d.replace(/^\//,"").split("/");v="/"+x.replace(/^\//,"").split("/").slice(_.length).join("/")}let g=AK(t,{pathname:v});xl(h||g!=null,`No routes matched location "${p.pathname}${p.search}${p.hash}" `),xl(g==null||g[g.length-1].route.element!==void 0||g[g.length-1].route.Component!==void 0||g[g.length-1].route.lazy!==void 0,`Matched leaf route at location "${p.pathname}${p.search}${p.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let y=rue(g&&g.map(_=>Object.assign({},_,{params:Object.assign({},c,_.params),pathname:$u([d,s.encodeLocation?s.encodeLocation(_.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?d:$u([d,s.encodeLocation?s.encodeLocation(_.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathnameBase])})),o,n,r,a);return e&&y?w.createElement(o0.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...p},navigationType:"POP"}},y):y}function Jce(){let t=lue(),e=zce(t)?`${t.status} ${t.statusText}`:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},s={padding:"2px 4px",backgroundColor:r},o=null;return console.error("Error handled by React Router default ErrorBoundary:",t),o=w.createElement(w.Fragment,null,w.createElement("p",null,"💿 Hey developer 👋"),w.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",w.createElement("code",{style:s},"ErrorBoundary")," or"," ",w.createElement("code",{style:s},"errorElement")," prop on your route.")),w.createElement(w.Fragment,null,w.createElement("h2",null,"Unexpected Application Error!"),w.createElement("h3",{style:{fontStyle:"italic"}},e),n?w.createElement("pre",{style:a},n):null,o)}var eue=w.createElement(Jce,null),UK=class extends w.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,e){return e.location!==t.location||e.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:e.error,location:e.location,revalidation:t.revalidation||e.revalidation}}componentDidCatch(t,e){this.props.onError?this.props.onError(t,e):console.error("React Router caught the following error during render",t)}render(){let t=this.state.error;if(this.context&&typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){const n=Kce(t.digest);n&&(t=n)}let e=t!==void 0?w.createElement(kl.Provider,{value:this.props.routeContext},w.createElement(uF.Provider,{value:t,children:this.props.component})):this.props.children;return this.context?w.createElement(tue,{error:t},e):e}};UK.contextType=Hce;var OM=new WeakMap;function tue({children:t,error:e}){let{basename:n}=w.useContext(Io);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let r=Wce(e.digest);if(r){let a=OM.get(e);if(a)throw a;let s=EK(r.location,n);if(PK&&!OM.get(e))if(s.isExternal||r.reloadDocument)window.location.href=s.absoluteURL||s.to;else{const o=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(s.to,{replace:r.replace}));throw OM.set(e,o),o}return w.createElement("meta",{httpEquiv:"refresh",content:`0;url=${s.absoluteURL||s.to}`})}}return t}function nue({routeContext:t,match:e,children:n}){let r=w.useContext(Bb);return r&&r.static&&r.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=e.route.id),w.createElement(kl.Provider,{value:t},n)}function rue(t,e=[],n=null,r=null,a=null){if(t==null){if(!n)return null;if(n.errors)t=n.matches;else if(e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let s=t,o=n?.errors;if(o!=null){let d=s.findIndex(h=>h.route.id&&o?.[h.route.id]!==void 0);ua(d>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),s=s.slice(0,Math.min(s.length,d+1))}let l=!1,c=-1;if(n)for(let d=0;d<s.length;d++){let h=s[d];if((h.route.HydrateFallback||h.route.hydrateFallbackElement)&&(c=d),h.route.id){let{loaderData:f,errors:p}=n,x=h.route.loader&&!f.hasOwnProperty(h.route.id)&&(!p||p[h.route.id]===void 0);if(h.route.lazy||x){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}let u=n&&r?(d,h)=>{r(d,{location:n.location,params:n.matches?.[0]?.params??{},unstable_pattern:Uce(n.matches),errorInfo:h})}:void 0;return s.reduceRight((d,h,f)=>{let p,x=!1,v=null,g=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,v=h.route.errorElement||eue,l&&(c<0&&f===0?(BK("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),x=!0,g=null):c===f&&(x=!0,g=h.route.hydrateFallbackElement||null)));let y=e.concat(s.slice(0,f+1)),_=()=>{let N;return p?N=v:x?N=g:h.route.Component?N=w.createElement(h.route.Component,null):h.route.element?N=h.route.element:N=d,w.createElement(nue,{match:h,routeContext:{outlet:d,matches:y,isDataRoute:n!=null},children:N})};return n&&(h.route.ErrorBoundary||h.route.errorElement||f===0)?w.createElement(UK,{location:n.location,revalidation:n.revalidation,component:v,error:p,children:_(),routeContext:{outlet:null,matches:y,isDataRoute:!0},onError:u}):_()},null)}function dF(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function aue(t){let e=w.useContext(Bb);return ua(e,dF(t)),e}function iue(t){let e=w.useContext(zC);return ua(e,dF(t)),e}function sue(t){let e=w.useContext(kl);return ua(e,dF(t)),e}function hF(t){let e=sue(t),n=e.matches[e.matches.length-1];return ua(n.route.id,`${t} can only be used on routes that contain a unique "id"`),n.route.id}function oue(){return hF("useRouteId")}function lue(){let t=w.useContext(uF),e=iue("useRouteError"),n=hF("useRouteError");return t!==void 0?t:e.errors?.[n]}function cue(){let{router:t}=aue("useNavigate"),e=hF("useNavigate"),n=w.useRef(!1);return LK(()=>{n.current=!0}),w.useCallback(async(a,s={})=>{xl(n.current,FK),n.current&&(typeof a=="number"?await t.navigate(a):await t.navigate(a,{fromRouteId:e,...s}))},[t,e])}var SB={};function BK(t,e,n){!e&&!SB[t]&&(SB[t]=!0,xl(!1,n))}w.memo(uue);function uue({routes:t,future:e,state:n,onError:r}){return zK(t,void 0,n,r,e)}function ob({to:t,replace:e,state:n,relative:r}){ua(Hb(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=w.useContext(Io);xl(!a,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:s}=w.useContext(kl),{pathname:o}=Vc(),l=rc(),c=cF(t,lF(s),o,r==="path"),u=JSON.stringify(c);return w.useEffect(()=>{l(JSON.parse(u),{replace:e,state:n,relative:r})},[l,u,r,e,n]),null}function HK(t){return Qce(t.context)}function Nr(t){ua(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function due({basename:t="/",children:e=null,location:n,navigationType:r="POP",navigator:a,static:s=!1,unstable_useTransitions:o}){ua(!Hb(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=t.replace(/^\/*/,"/"),c=w.useMemo(()=>({basename:l,navigator:a,static:s,unstable_useTransitions:o,future:{}}),[l,a,s,o]);typeof n=="string"&&(n=Ub(n));let{pathname:u="/",search:d="",hash:h="",state:f=null,key:p="default"}=n,x=w.useMemo(()=>{let v=Zu(u,l);return v==null?null:{location:{pathname:v,search:d,hash:h,state:f,key:p},navigationType:r}},[l,u,d,h,f,p,r]);return xl(x!=null,`<Router basename="${l}"> is not able to match the URL "${u}${d}${h}" because it does not start with the basename, so the <Router> won't render anything.`),x==null?null:w.createElement(Io.Provider,{value:c},w.createElement(o0.Provider,{children:e,value:x}))}function hue({children:t,location:e}){return Zce(q2(t),e)}function q2(t,e=[]){let n=[];return w.Children.forEach(t,(r,a)=>{if(!w.isValidElement(r))return;let s=[...e,a];if(r.type===w.Fragment){n.push.apply(n,q2(r.props.children,s));return}ua(r.type===Nr,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ua(!r.props.index||!r.props.children,"An index route cannot have child routes.");let o={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=q2(r.props.children,s)),n.push(o)}),n}var U_="get",B_="application/x-www-form-urlencoded";function UC(t){return typeof HTMLElement<"u"&&t instanceof HTMLElement}function mue(t){return UC(t)&&t.tagName.toLowerCase()==="button"}function fue(t){return UC(t)&&t.tagName.toLowerCase()==="form"}function pue(t){return UC(t)&&t.tagName.toLowerCase()==="input"}function gue(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function bue(t,e){return t.button===0&&(!e||e==="_self")&&!gue(t)}function G2(t=""){return new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let r=t[n];return e.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function xue(t,e){let n=G2(t);return e&&e.forEach((r,a)=>{n.has(a)||e.getAll(a).forEach(s=>{n.append(a,s)})}),n}var nS=null;function yue(){if(nS===null)try{new FormData(document.createElement("form"),0),nS=!1}catch{nS=!0}return nS}var vue=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function IM(t){return t!=null&&!vue.has(t)?(xl(!1,`"${t}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${B_}"`),null):t}function wue(t,e){let n,r,a,s,o;if(fue(t)){let l=t.getAttribute("action");r=l?Zu(l,e):null,n=t.getAttribute("method")||U_,a=IM(t.getAttribute("enctype"))||B_,s=new FormData(t)}else if(mue(t)||pue(t)&&(t.type==="submit"||t.type==="image")){let l=t.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=t.getAttribute("formaction")||l.getAttribute("action");if(r=c?Zu(c,e):null,n=t.getAttribute("formmethod")||l.getAttribute("method")||U_,a=IM(t.getAttribute("formenctype"))||IM(l.getAttribute("enctype"))||B_,s=new FormData(l,t),!yue()){let{name:u,type:d,value:h}=t;if(d==="image"){let f=u?`${u}.`:"";s.append(`${f}x`,"0"),s.append(`${f}y`,"0")}else u&&s.append(u,h)}}else{if(UC(t))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=U_,r=null,a=B_,o=t}return s&&a==="text/plain"&&(o=s,s=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:s,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function mF(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function Sue(t,e,n,r){let a=typeof t=="string"?new URL(t,typeof window>"u"?"server://singlefetch/":window.location.origin):t;return n?a.pathname.endsWith("/")?a.pathname=`${a.pathname}_.${r}`:a.pathname=`${a.pathname}.${r}`:a.pathname==="/"?a.pathname=`_root.${r}`:e&&Zu(a.pathname,e)==="/"?a.pathname=`${e.replace(/\/$/,"")}/_root.${r}`:a.pathname=`${a.pathname.replace(/\/$/,"")}.${r}`,a}async function _ue(t,e){if(t.id in e)return e[t.id];try{let n=await import(t.module);return e[t.id]=n,n}catch(n){return console.error(`Error loading route module \`${t.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function Nue(t){return t==null?!1:t.href==null?t.rel==="preload"&&typeof t.imageSrcSet=="string"&&typeof t.imageSizes=="string":typeof t.rel=="string"&&typeof t.href=="string"}async function Cue(t,e,n){let r=await Promise.all(t.map(async a=>{let s=e.routes[a.route.id];if(s){let o=await _ue(s,n);return o.links?o.links():[]}return[]}));return Mue(r.flat(1).filter(Nue).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function _B(t,e,n,r,a,s){let o=(c,u)=>n[u]?c.route.id!==n[u].route.id:!0,l=(c,u)=>n[u].pathname!==c.pathname||n[u].route.path?.endsWith("*")&&n[u].params["*"]!==c.params["*"];return s==="assets"?e.filter((c,u)=>o(c,u)||l(c,u)):s==="data"?e.filter((c,u)=>{let d=r.routes[c.route.id];if(!d||!d.hasLoader)return!1;if(o(c,u)||l(c,u))return!0;if(c.route.shouldRevalidate){let h=c.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(t,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof h=="boolean")return h}return!0}):[]}function kue(t,e,{includeHydrateFallback:n}={}){return Aue(t.map(r=>{let a=e.routes[r.route.id];if(!a)return[];let s=[a.module];return a.clientActionModule&&(s=s.concat(a.clientActionModule)),a.clientLoaderModule&&(s=s.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(s=s.concat(a.hydrateFallbackModule)),a.imports&&(s=s.concat(a.imports)),s}).flat(1))}function Aue(t){return[...new Set(t)]}function Tue(t){let e={},n=Object.keys(t).sort();for(let r of n)e[r]=t[r];return e}function Mue(t,e){let n=new Set;return new Set(e),t.reduce((r,a)=>{let s=JSON.stringify(Tue(a));return n.has(s)||(n.add(s),r.push({key:s,link:a})),r},[])}function $K(){let t=w.useContext(Bb);return mF(t,"You must render this element inside a <DataRouterContext.Provider> element"),t}function Pue(){let t=w.useContext(zC);return mF(t,"You must render this element inside a <DataRouterStateContext.Provider> element"),t}var fF=w.createContext(void 0);fF.displayName="FrameworkContext";function VK(){let t=w.useContext(fF);return mF(t,"You must render this element inside a <HydratedRouter> element"),t}function Eue(t,e){let n=w.useContext(fF),[r,a]=w.useState(!1),[s,o]=w.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:u,onMouseLeave:d,onTouchStart:h}=e,f=w.useRef(null);w.useEffect(()=>{if(t==="render"&&o(!0),t==="viewport"){let v=y=>{y.forEach(_=>{o(_.isIntersecting)})},g=new IntersectionObserver(v,{threshold:.5});return f.current&&g.observe(f.current),()=>{g.disconnect()}}},[t]),w.useEffect(()=>{if(r){let v=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(v)}}},[r]);let p=()=>{a(!0)},x=()=>{a(!1),o(!1)};return n?t!=="intent"?[s,f,{}]:[s,f,{onFocus:Jx(l,p),onBlur:Jx(c,x),onMouseEnter:Jx(u,p),onMouseLeave:Jx(d,x),onTouchStart:Jx(h,p)}]:[!1,f,{}]}function Jx(t,e){return n=>{t&&t(n),n.defaultPrevented||e(n)}}function jue({page:t,...e}){let{router:n}=$K(),r=w.useMemo(()=>AK(n.routes,t,n.basename),[n.routes,t,n.basename]);return r?w.createElement(Rue,{page:t,matches:r,...e}):null}function Due(t){let{manifest:e,routeModules:n}=VK(),[r,a]=w.useState([]);return w.useEffect(()=>{let s=!1;return Cue(t,e,n).then(o=>{s||a(o)}),()=>{s=!0}},[t,e,n]),r}function Rue({page:t,matches:e,...n}){let r=Vc(),{future:a,manifest:s,routeModules:o}=VK(),{basename:l}=$K(),{loaderData:c,matches:u}=Pue(),d=w.useMemo(()=>_B(t,e,u,s,r,"data"),[t,e,u,s,r]),h=w.useMemo(()=>_B(t,e,u,s,r,"assets"),[t,e,u,s,r]),f=w.useMemo(()=>{if(t===r.pathname+r.search+r.hash)return[];let v=new Set,g=!1;if(e.forEach(_=>{let N=s.routes[_.route.id];!N||!N.hasLoader||(!d.some(k=>k.route.id===_.route.id)&&_.route.id in c&&o[_.route.id]?.shouldRevalidate||N.hasClientLoader?g=!0:v.add(_.route.id))}),v.size===0)return[];let y=Sue(t,l,a.unstable_trailingSlashAwareDataRequests,"data");return g&&v.size>0&&y.searchParams.set("_routes",e.filter(_=>v.has(_.route.id)).map(_=>_.route.id).join(",")),[y.pathname+y.search]},[l,a.unstable_trailingSlashAwareDataRequests,c,r,s,d,e,t,o]),p=w.useMemo(()=>kue(h,s),[h,s]),x=Due(h);return w.createElement(w.Fragment,null,f.map(v=>w.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),p.map(v=>w.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),x.map(({key:v,link:g})=>w.createElement("link",{key:v,nonce:n.nonce,...g,crossOrigin:g.crossOrigin??n.crossOrigin})))}function Fue(...t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var Lue=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Lue&&(window.__reactRouterVersion="7.13.0")}catch{}function Oue({basename:t,children:e,unstable_useTransitions:n,window:r}){let a=w.useRef();a.current==null&&(a.current=pce({window:r,v5Compat:!0}));let s=a.current,[o,l]=w.useState({action:s.action,location:s.location}),c=w.useCallback(u=>{n===!1?l(u):w.startTransition(()=>l(u))},[n]);return w.useLayoutEffect(()=>s.listen(c),[s,c]),w.createElement(due,{basename:t,children:e,location:o.location,navigationType:o.action,navigator:s,unstable_useTransitions:n})}var qK=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ks=w.forwardRef(function({onClick:e,discover:n="render",prefetch:r="none",relative:a,reloadDocument:s,replace:o,state:l,target:c,to:u,preventScrollReset:d,viewTransition:h,unstable_defaultShouldRevalidate:f,...p},x){let{basename:v,unstable_useTransitions:g}=w.useContext(Io),y=typeof u=="string"&&qK.test(u),_=EK(u,v);u=_.to;let N=Xce(u,{relative:a}),[k,A,M]=Eue(r,p),C=Uue(u,{replace:o,state:l,target:c,preventScrollReset:d,relative:a,viewTransition:h,unstable_defaultShouldRevalidate:f,unstable_useTransitions:g});function j(E){e&&e(E),E.defaultPrevented||C(E)}let P=w.createElement("a",{...p,...M,href:_.absoluteURL||N,onClick:_.isExternal||s?e:j,ref:Fue(x,A),target:c,"data-discover":!y&&n==="render"?"true":void 0});return k&&!y?w.createElement(w.Fragment,null,P,w.createElement(jue,{page:N})):P});Ks.displayName="Link";var Zm=w.forwardRef(function({"aria-current":e="page",caseSensitive:n=!1,className:r="",end:a=!1,style:s,to:o,viewTransition:l,children:c,...u},d){let h=c0(o,{relative:u.relative}),f=Vc(),p=w.useContext(zC),{navigator:x,basename:v}=w.useContext(Io),g=p!=null&&que(h)&&l===!0,y=x.encodeLocation?x.encodeLocation(h).pathname:h.pathname,_=f.pathname,N=p&&p.navigation&&p.navigation.location?p.navigation.location.pathname:null;n||(_=_.toLowerCase(),N=N?N.toLowerCase():null,y=y.toLowerCase()),N&&v&&(N=Zu(N,v)||N);const k=y!=="/"&&y.endsWith("/")?y.length-1:y.length;let A=_===y||!a&&_.startsWith(y)&&_.charAt(k)==="/",M=N!=null&&(N===y||!a&&N.startsWith(y)&&N.charAt(y.length)==="/"),C={isActive:A,isPending:M,isTransitioning:g},j=A?e:void 0,P;typeof r=="function"?P=r(C):P=[r,A?"active":null,M?"pending":null,g?"transitioning":null].filter(Boolean).join(" ");let E=typeof s=="function"?s(C):s;return w.createElement(Ks,{...u,"aria-current":j,className:P,ref:d,style:E,to:o,viewTransition:l},typeof c=="function"?c(C):c)});Zm.displayName="NavLink";var Iue=w.forwardRef(({discover:t="render",fetcherKey:e,navigate:n,reloadDocument:r,replace:a,state:s,method:o=U_,action:l,onSubmit:c,relative:u,preventScrollReset:d,viewTransition:h,unstable_defaultShouldRevalidate:f,...p},x)=>{let{unstable_useTransitions:v}=w.useContext(Io),g=$ue(),y=Vue(l,{relative:u}),_=o.toLowerCase()==="get"?"get":"post",N=typeof l=="string"&&qK.test(l),k=A=>{if(c&&c(A),A.defaultPrevented)return;A.preventDefault();let M=A.nativeEvent.submitter,C=M?.getAttribute("formmethod")||o,j=()=>g(M||A.currentTarget,{fetcherKey:e,method:C,navigate:n,replace:a,state:s,relative:u,preventScrollReset:d,viewTransition:h,unstable_defaultShouldRevalidate:f});v&&n!==!1?w.startTransition(()=>j()):j()};return w.createElement("form",{ref:x,method:_,action:y,onSubmit:r?c:k,...p,"data-discover":!N&&t==="render"?"true":void 0})});Iue.displayName="Form";function zue(t){return`${t} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function GK(t){let e=w.useContext(Bb);return ua(e,zue(t)),e}function Uue(t,{target:e,replace:n,state:r,preventScrollReset:a,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l,unstable_useTransitions:c}={}){let u=rc(),d=Vc(),h=c0(t,{relative:s});return w.useCallback(f=>{if(bue(f,e)){f.preventDefault();let p=n!==void 0?n:fv(d)===fv(h),x=()=>u(t,{replace:p,state:r,preventScrollReset:a,relative:s,viewTransition:o,unstable_defaultShouldRevalidate:l});c?w.startTransition(()=>x()):x()}},[d,u,h,n,r,e,t,a,s,o,l,c])}function BC(t){xl(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let e=w.useRef(G2(t)),n=w.useRef(!1),r=Vc(),a=w.useMemo(()=>xue(r.search,n.current?null:e.current),[r.search]),s=rc(),o=w.useCallback((l,c)=>{const u=G2(typeof l=="function"?l(new URLSearchParams(a)):l);n.current=!0,s("?"+u,c)},[s,a]);return[a,o]}var Bue=0,Hue=()=>`__${String(++Bue)}__`;function $ue(){let{router:t}=GK("useSubmit"),{basename:e}=w.useContext(Io),n=oue(),r=t.fetch,a=t.navigate;return w.useCallback(async(s,o={})=>{let{action:l,method:c,encType:u,formData:d,body:h}=wue(s,e);if(o.navigate===!1){let f=o.fetcherKey||Hue();await r(f,n,o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:d,body:h,formMethod:o.method||c,formEncType:o.encType||u,flushSync:o.flushSync})}else await a(o.action||l,{unstable_defaultShouldRevalidate:o.unstable_defaultShouldRevalidate,preventScrollReset:o.preventScrollReset,formData:d,body:h,formMethod:o.method||c,formEncType:o.encType||u,replace:o.replace,state:o.state,fromRouteId:n,flushSync:o.flushSync,viewTransition:o.viewTransition})},[r,a,e,n])}function Vue(t,{relative:e}={}){let{basename:n}=w.useContext(Io),r=w.useContext(kl);ua(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),s={...c0(t||".",{relative:e})},o=Vc();if(t==null){s.search=o.search;let l=new URLSearchParams(s.search),c=l.getAll("index");if(c.some(d=>d==="")){l.delete("index"),c.filter(h=>h).forEach(h=>l.append("index",h));let d=l.toString();s.search=d?`?${d}`:""}}return(!t||t===".")&&a.route.index&&(s.search=s.search?s.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(s.pathname=s.pathname==="/"?n:$u([n,s.pathname])),fv(s)}function que(t,{relative:e}={}){let n=w.useContext(DK);ua(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=GK("useViewTransitionState"),a=c0(t,{relative:e});if(!n.isTransitioning)return!1;let s=Zu(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Zu(n.nextLocation.pathname,r)||n.nextLocation.pathname;return b1(a.pathname,o)!=null||b1(a.pathname,s)!=null}var Fu=gK();const Gue=nc(Fu);var ep=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Wue={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},Kue=class{#t=Wue;#e=!1;setTimeoutProvider(t){this.#t=t}setTimeout(t,e){return this.#t.setTimeout(t,e)}clearTimeout(t){this.#t.clearTimeout(t)}setInterval(t,e){return this.#t.setInterval(t,e)}clearInterval(t){this.#t.clearInterval(t)}},Jm=new Kue;function Xue(t){setTimeout(t,0)}var Af=typeof window>"u"||"Deno"in globalThis;function ms(){}function Yue(t,e){return typeof t=="function"?t(e):t}function W2(t){return typeof t=="number"&&t>=0&&t!==1/0}function WK(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Ah(t,e){return typeof t=="function"?t(e):t}function tl(t,e){return typeof t=="function"?t(e):t}function NB(t,e){const{type:n="all",exact:r,fetchStatus:a,predicate:s,queryKey:o,stale:l}=t;if(o){if(r){if(e.queryHash!==pF(o,e.options))return!1}else if(!pv(e.queryKey,o))return!1}if(n!=="all"){const c=e.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||a&&a!==e.state.fetchStatus||s&&!s(e))}function CB(t,e){const{exact:n,status:r,predicate:a,mutationKey:s}=t;if(s){if(!e.options.mutationKey)return!1;if(n){if(Tf(e.options.mutationKey)!==Tf(s))return!1}else if(!pv(e.options.mutationKey,s))return!1}return!(r&&e.state.status!==r||a&&!a(e))}function pF(t,e){return(e?.queryKeyHashFn||Tf)(t)}function Tf(t){return JSON.stringify(t,(e,n)=>K2(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function pv(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>pv(t[n],e[n])):!1}var Que=Object.prototype.hasOwnProperty;function gF(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=kB(t)&&kB(e);if(!r&&!(K2(t)&&K2(e)))return e;const s=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),l=o.length,c=r?new Array(l):{};let u=0;for(let d=0;d<l;d++){const h=r?d:o[d],f=t[h],p=e[h];if(f===p){c[h]=f,(r?d<s:Que.call(t,h))&&u++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}const x=gF(f,p,n+1);c[h]=x,x===f&&u++}return s===l&&u===s?t:c}function gv(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const n in t)if(t[n]!==e[n])return!1;return!0}function kB(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function K2(t){if(!AB(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!AB(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function AB(t){return Object.prototype.toString.call(t)==="[object Object]"}function Zue(t){return new Promise(e=>{Jm.setTimeout(e,t)})}function X2(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?gF(t,e):e}function Jue(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function ede(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var bF=Symbol();function KK(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===bF?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function xF(t,e){return typeof t=="function"?t(...e):!!t}function tde(t,e,n){let r=!1,a;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(a??=e(),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),t}var nde=class extends ep{#t;#e;#n;constructor(){super(),this.#n=t=>{if(!Af&&window.addEventListener){const e=()=>t();return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#n=t,this.#e?.(),this.#e=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#t!==t&&(this.#t=t,this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},yF=new nde;function Y2(){let t,e;const n=new Promise((a,s)=>{t=a,e=s});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),t(a)},n.reject=a=>{r({status:"rejected",reason:a}),e(a)},n}var rde=Xue;function ade(){let t=[],e=0,n=l=>{l()},r=l=>{l()},a=rde;const s=l=>{e?t.push(l):a(()=>{n(l)})},o=()=>{const l=t;t=[],l.length&&a(()=>{r(()=>{l.forEach(c=>{n(c)})})})};return{batch:l=>{let c;e++;try{c=l()}finally{e--,e||o()}return c},batchCalls:l=>(...c)=>{s(()=>{l(...c)})},schedule:s,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{a=l}}}var Ea=ade(),ide=class extends ep{#t=!0;#e;#n;constructor(){super(),this.#n=t=>{if(!Af&&window.addEventListener){const e=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",e,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(t){this.#n=t,this.#e?.(),this.#e=t(this.setOnline.bind(this))}setOnline(t){this.#t!==t&&(this.#t=t,this.listeners.forEach(n=>{n(t)}))}isOnline(){return this.#t}},x1=new ide;function sde(t){return Math.min(1e3*2**t,3e4)}function XK(t){return(t??"online")==="online"?x1.isOnline():!0}var Q2=class extends Error{constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function YK(t){let e=!1,n=0,r;const a=Y2(),s=()=>a.status!=="pending",o=v=>{if(!s()){const g=new Q2(v);f(g),t.onCancel?.(g)}},l=()=>{e=!0},c=()=>{e=!1},u=()=>yF.isFocused()&&(t.networkMode==="always"||x1.isOnline())&&t.canRun(),d=()=>XK(t.networkMode)&&t.canRun(),h=v=>{s()||(r?.(),a.resolve(v))},f=v=>{s()||(r?.(),a.reject(v))},p=()=>new Promise(v=>{r=g=>{(s()||u())&&v(g)},t.onPause?.()}).then(()=>{r=void 0,s()||t.onContinue?.()}),x=()=>{if(s())return;let v;const g=n===0?t.initialPromise:void 0;try{v=g??t.fn()}catch(y){v=Promise.reject(y)}Promise.resolve(v).then(h).catch(y=>{if(s())return;const _=t.retry??(Af?0:3),N=t.retryDelay??sde,k=typeof N=="function"?N(n,y):N,A=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,y);if(e||!A){f(y);return}n++,t.onFail?.(n,y),Zue(k).then(()=>u()?void 0:p()).then(()=>{e?f(y):x()})})};return{promise:a,status:()=>a.status,cancel:o,continue:()=>(r?.(),a),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?x():p().then(x),a)}}var QK=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),W2(this.gcTime)&&(this.#t=Jm.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Af?1/0:300*1e3))}clearGcTimeout(){this.#t&&(Jm.clearTimeout(this.#t),this.#t=void 0)}},ode=class extends QK{#t;#e;#n;#a;#r;#i;#o;constructor(t){super(),this.#o=!1,this.#i=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#a=t.client,this.#n=this.#a.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=MB(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(t){if(this.options={...this.#i,...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const e=MB(this.options);e.data!==void 0&&(this.setState(TB(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(t,e){const n=X2(this.state.data,t,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),n}setState(t,e){this.#s({type:"setState",state:t,setStateOptions:e})}cancel(t){const e=this.#r?.promise;return this.#r?.cancel(t),e?e.then(ms).catch(ms):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(t=>tl(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===bF||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Ah(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!WK(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(t&&this.setOptions(t),!this.options.queryFn){const l=this.observers.find(c=>c.options.queryFn);l&&this.setOptions(l.options)}const n=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},a=()=>{const l=KK(this.options,e),u=(()=>{const d={client:this.#a,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(l,u,this):l(u)},o=(()=>{const l={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#a,state:this.state,fetchFn:a};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#s({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=YK({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof Q2&&l.revert&&this.setState({...this.#e,fetchStatus:"idle"}),n.abort()},onFail:(l,c)=>{this.#s({type:"failed",failureCount:l,error:c})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const l=await this.#r.start();if(l===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#n.config.onSuccess?.(l,this),this.#n.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof Q2){if(l.silent)return this.#r.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#s({type:"error",error:l}),this.#n.config.onError?.(l,this),this.#n.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#s(t){const e=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...ZK(n.data,this.options),fetchMeta:t.meta??null};case"success":const r={...n,...TB(t.data,t.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#e=t.manual?r:void 0,r;case"error":const a=t.error;return{...n,error:a,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=e(this.state),Ea.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:t})})}};function ZK(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:XK(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function TB(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function MB(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var vF=class extends ep{constructor(t,e){super(),this.options=e,this.#t=t,this.#s=null,this.#o=Y2(),this.bindMethods(),this.setOptions(e)}#t;#e=void 0;#n=void 0;#a=void 0;#r;#i;#o;#s;#f;#d;#h;#c;#u;#l;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),PB(this.#e,this.options)?this.#p():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Z2(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Z2(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#v(),this.#w(),this.#e.removeObserver(this)}setOptions(t){const e=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof tl(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),e._defaulted&&!gv(this.options,e)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&EB(this.#e,n,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#e!==n||tl(this.options.enabled,this.#e)!==tl(e.enabled,this.#e)||Ah(this.options.staleTime,this.#e)!==Ah(e.staleTime,this.#e))&&this.#g();const a=this.#b();r&&(this.#e!==n||tl(this.options.enabled,this.#e)!==tl(e.enabled,this.#e)||a!==this.#l)&&this.#x(a)}getOptimisticResult(t){const e=this.#t.getQueryCache().build(this.#t,t),n=this.createResult(e,t);return cde(this,n)&&(this.#a=n,this.#i=this.options,this.#r=this.#e.state),n}getCurrentResult(){return this.#a}trackResult(t,e){return new Proxy(t,{get:(n,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#e}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const e=this.#t.defaultQueryOptions(t),n=this.#t.getQueryCache().build(this.#t,e);return n.fetch().then(()=>this.createResult(n,e))}fetch(t){return this.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#p(t){this.#S();let e=this.#e.fetch(this.options,t);return t?.throwOnError||(e=e.catch(ms)),e}#g(){this.#v();const t=Ah(this.options.staleTime,this.#e);if(Af||this.#a.isStale||!W2(t))return;const n=WK(this.#a.dataUpdatedAt,t)+1;this.#c=Jm.setTimeout(()=>{this.#a.isStale||this.updateResult()},n)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#x(t){this.#w(),this.#l=t,!(Af||tl(this.options.enabled,this.#e)===!1||!W2(this.#l)||this.#l===0)&&(this.#u=Jm.setInterval(()=>{(this.options.refetchIntervalInBackground||yF.isFocused())&&this.#p()},this.#l))}#y(){this.#g(),this.#x(this.#b())}#v(){this.#c&&(Jm.clearTimeout(this.#c),this.#c=void 0)}#w(){this.#u&&(Jm.clearInterval(this.#u),this.#u=void 0)}createResult(t,e){const n=this.#e,r=this.options,a=this.#a,s=this.#r,o=this.#i,c=t!==n?t.state:this.#n,{state:u}=t;let d={...u},h=!1,f;if(e._optimisticResults){const j=this.hasListeners(),P=!j&&PB(t,e),E=j&&EB(t,n,e,r);(P||E)&&(d={...d,...ZK(u.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:p,errorUpdatedAt:x,status:v}=d;f=d.data;let g=!1;if(e.placeholderData!==void 0&&f===void 0&&v==="pending"){let j;a?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(j=a.data,g=!0):j=typeof e.placeholderData=="function"?e.placeholderData(this.#h?.state.data,this.#h):e.placeholderData,j!==void 0&&(v="success",f=X2(a?.data,j,e),h=!0)}if(e.select&&f!==void 0&&!g)if(a&&f===s?.data&&e.select===this.#f)f=this.#d;else try{this.#f=e.select,f=e.select(f),f=X2(a?.data,f,e),this.#d=f,this.#s=null}catch(j){this.#s=j}this.#s&&(p=this.#s,f=this.#d,x=Date.now(),v="error");const y=d.fetchStatus==="fetching",_=v==="pending",N=v==="error",k=_&&y,A=f!==void 0,C={status:v,fetchStatus:d.fetchStatus,isPending:_,isSuccess:v==="success",isError:N,isInitialLoading:k,isLoading:k,data:f,dataUpdatedAt:d.dataUpdatedAt,error:p,errorUpdatedAt:x,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:y,isRefetching:y&&!_,isLoadingError:N&&!A,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&A,isStale:wF(t,e),refetch:this.refetch,promise:this.#o,isEnabled:tl(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const j=C.data!==void 0,P=C.status==="error"&&!j,E=B=>{P?B.reject(C.error):j&&B.resolve(C.data)},U=()=>{const B=this.#o=C.promise=Y2();E(B)},L=this.#o;switch(L.status){case"pending":t.queryHash===n.queryHash&&E(L);break;case"fulfilled":(P||C.data!==L.value)&&U();break;case"rejected":(!P||C.error!==L.reason)&&U();break}}return C}updateResult(){const t=this.#a,e=this.createResult(this.#e,this.options);if(this.#r=this.#e.state,this.#i=this.options,this.#r.data!==void 0&&(this.#h=this.#e),gv(e,t))return;this.#a=e;const n=()=>{if(!t)return!0;const{notifyOnChangeProps:r}=this.options,a=typeof r=="function"?r():r;if(a==="all"||!a&&!this.#m.size)return!0;const s=new Set(a??this.#m);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(o=>{const l=o;return this.#a[l]!==t[l]&&s.has(l)})};this.#_({listeners:n()})}#S(){const t=this.#t.getQueryCache().build(this.#t,this.options);if(t===this.#e)return;const e=this.#e;this.#e=t,this.#n=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#_(t){Ea.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#a)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function lde(t,e){return tl(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function PB(t,e){return lde(t,e)||t.state.data!==void 0&&Z2(t,e,e.refetchOnMount)}function Z2(t,e,n){if(tl(e.enabled,t)!==!1&&Ah(e.staleTime,t)!=="static"){const r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&wF(t,e)}return!1}function EB(t,e,n,r){return(t!==e||tl(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&wF(t,n)}function wF(t,e){return tl(e.enabled,t)!==!1&&t.isStaleByTime(Ah(e.staleTime,t))}function cde(t,e){return!gv(t.getCurrentResult(),e)}function jB(t){return{onFetch:(e,n)=>{const r=e.options,a=e.fetchOptions?.meta?.fetchMore?.direction,s=e.state.data?.pages||[],o=e.state.data?.pageParams||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let d=!1;const h=x=>{tde(x,()=>e.signal,()=>d=!0)},f=KK(e.options,e.fetchOptions),p=async(x,v,g)=>{if(d)return Promise.reject();if(v==null&&x.pages.length)return Promise.resolve(x);const _=(()=>{const M={client:e.client,queryKey:e.queryKey,pageParam:v,direction:g?"backward":"forward",meta:e.options.meta};return h(M),M})(),N=await f(_),{maxPages:k}=e.options,A=g?ede:Jue;return{pages:A(x.pages,N,k),pageParams:A(x.pageParams,v,k)}};if(a&&s.length){const x=a==="backward",v=x?ude:DB,g={pages:s,pageParams:o},y=v(r,g);l=await p(g,y,x)}else{const x=t??s.length;do{const v=c===0?o[0]??r.initialPageParam:DB(r,l);if(c>0&&v==null)break;l=await p(l,v),c++}while(c<x)}return l};e.options.persister?e.fetchFn=()=>e.options.persister?.(u,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n):e.fetchFn=u}}}function DB(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function ude(t,{pages:e,pageParams:n}){return e.length>0?t.getPreviousPageParam?.(e[0],e,n[0],n):void 0}var dde=class extends QK{#t;#e;#n;#a;constructor(t){super(),this.#t=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#e=[],this.state=t.state||JK(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#e.includes(t)||(this.#e.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#e=this.#e.filter(e=>e!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??this.execute(this.state.variables)}async execute(t){const e=()=>{this.#r({type:"continue"})},n={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#a=YK({fn:()=>this.options.mutationFn?this.options.mutationFn(t,n):Promise.reject(new Error("No mutationFn found")),onFail:(s,o)=>{this.#r({type:"failed",failureCount:s,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",a=!this.#a.canStart();try{if(r)e();else{this.#r({type:"pending",variables:t,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,n);const o=await this.options.onMutate?.(t,n);o!==this.state.context&&this.#r({type:"pending",context:o,variables:t,isPaused:a})}const s=await this.#a.start();return await this.#n.config.onSuccess?.(s,t,this.state.context,this,n),await this.options.onSuccess?.(s,t,this.state.context,n),await this.#n.config.onSettled?.(s,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(s,null,t,this.state.context,n),this.#r({type:"success",data:s}),s}catch(s){try{await this.#n.config.onError?.(s,t,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onError?.(s,t,this.state.context,n)}catch(o){Promise.reject(o)}try{await this.#n.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this,n)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,s,t,this.state.context,n)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:s}),s}finally{this.#n.runNext(this)}}#r(t){const e=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=e(this.state),Ea.batch(()=>{this.#e.forEach(n=>{n.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function JK(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var hde=class extends ep{constructor(t={}){super(),this.config=t,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(t,e,n){const r=new dde({client:t,mutationCache:this,mutationId:++this.#n,options:t.defaultMutationOptions(e),state:n});return this.add(r),r}add(t){this.#t.add(t);const e=rS(t);if(typeof e=="string"){const n=this.#e.get(e);n?n.push(t):this.#e.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#t.delete(t)){const e=rS(t);if(typeof e=="string"){const n=this.#e.get(e);if(n)if(n.length>1){const r=n.indexOf(t);r!==-1&&n.splice(r,1)}else n[0]===t&&this.#e.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){const e=rS(t);if(typeof e=="string"){const r=this.#e.get(e)?.find(a=>a.state.status==="pending");return!r||r===t}else return!0}runNext(t){const e=rS(t);return typeof e=="string"?this.#e.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ea.batch(()=>{this.#t.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(t){const e={exact:!0,...t};return this.getAll().find(n=>CB(e,n))}findAll(t={}){return this.getAll().filter(e=>CB(t,e))}notify(t){Ea.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){const t=this.getAll().filter(e=>e.state.isPaused);return Ea.batch(()=>Promise.all(t.map(e=>e.continue().catch(ms))))}};function rS(t){return t.options.scope?.id}var mde=class extends ep{#t;#e=void 0;#n;#a;constructor(e,n){super(),this.#t=e,this.setOptions(n),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const n=this.options;this.options=this.#t.defaultMutationOptions(e),gv(this.options,n)||this.#t.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&Tf(n.mutationKey)!==Tf(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#i(e)}getCurrentResult(){return this.#e}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#r(),this.#i()}mutate(e,n){return this.#a=n,this.#n?.removeObserver(this),this.#n=this.#t.getMutationCache().build(this.#t,this.options),this.#n.addObserver(this),this.#n.execute(e)}#r(){const e=this.#n?.state??JK();this.#e={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#i(e){Ea.batch(()=>{if(this.#a&&this.hasListeners()){const n=this.#e.variables,r=this.#e.context,a={client:this.#t,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#a.onSuccess?.(e.data,n,r,a)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(e.data,null,n,r,a)}catch(s){Promise.reject(s)}}else if(e?.type==="error"){try{this.#a.onError?.(e.error,n,r,a)}catch(s){Promise.reject(s)}try{this.#a.onSettled?.(void 0,e.error,n,r,a)}catch(s){Promise.reject(s)}}}this.listeners.forEach(n=>{n(this.#e)})})}};function RB(t,e){const n=new Set(e);return t.filter(r=>!n.has(r))}function fde(t,e,n){const r=t.slice(0);return r[e]=n,r}var pde=class extends ep{#t;#e;#n;#a;#r;#i;#o;#s;#f;#d=[];constructor(t,e,n){super(),this.#t=t,this.#a=n,this.#n=[],this.#r=[],this.#e=[],this.setQueries(e)}onSubscribe(){this.listeners.size===1&&this.#r.forEach(t=>{t.subscribe(e=>{this.#l(t,e)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#r.forEach(t=>{t.destroy()})}setQueries(t,e){this.#n=t,this.#a=e,Ea.batch(()=>{const n=this.#r,r=this.#u(this.#n);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const a=r.map(d=>d.observer),s=a.map(d=>d.getCurrentResult()),o=n.length!==a.length,l=a.some((d,h)=>d!==n[h]),c=o||l,u=c?!0:s.some((d,h)=>{const f=this.#e[h];return!f||!gv(d,f)});!c&&!u||(c&&(this.#d=r,this.#r=a),this.#e=s,this.hasListeners()&&(c&&(RB(n,a).forEach(d=>{d.destroy()}),RB(a,n).forEach(d=>{d.subscribe(h=>{this.#l(d,h)})})),this.#m()))})}getCurrentResult(){return this.#e}getQueries(){return this.#r.map(t=>t.getCurrentQuery())}getObservers(){return this.#r}getOptimisticResult(t,e){const n=this.#u(t),r=n.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions)),a=n.map(s=>s.defaultedQueryOptions.queryHash);return[r,s=>this.#c(s??r,e,a),()=>this.#h(r,n)]}#h(t,e){return e.map((n,r)=>{const a=t[r];return n.defaultedQueryOptions.notifyOnChangeProps?a:n.observer.trackResult(a,s=>{e.forEach(o=>{o.observer.trackProp(s)})})})}#c(t,e,n){if(e){const r=this.#f,a=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((s,o)=>s!==r[o]));return(!this.#i||this.#e!==this.#s||a||e!==this.#o)&&(this.#o=e,this.#s=this.#e,n!==void 0&&(this.#f=n),this.#i=gF(this.#i,e(t))),this.#i}return t}#u(t){const e=new Map;this.#r.forEach(r=>{const a=r.options.queryHash;if(!a)return;const s=e.get(a);s?s.push(r):e.set(a,[r])});const n=[];return t.forEach(r=>{const a=this.#t.defaultQueryOptions(r),o=e.get(a.queryHash)?.shift()??new vF(this.#t,a);n.push({defaultedQueryOptions:a,observer:o})}),n}#l(t,e){const n=this.#r.indexOf(t);n!==-1&&(this.#e=fde(this.#e,n,e),this.#m())}#m(){if(this.hasListeners()){const t=this.#i,e=this.#h(this.#e,this.#d),n=this.#c(e,this.#a?.combine);t!==n&&Ea.batch(()=>{this.listeners.forEach(r=>{r(this.#e)})})}}},gde=class extends ep{constructor(t={}){super(),this.config=t,this.#t=new Map}#t;build(t,e,n){const r=e.queryKey,a=e.queryHash??pF(r,e);let s=this.get(a);return s||(s=new ode({client:t,queryKey:r,queryHash:a,options:t.defaultQueryOptions(e),state:n,defaultOptions:t.getQueryDefaults(r)}),this.add(s)),s}add(t){this.#t.has(t.queryHash)||(this.#t.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const e=this.#t.get(t.queryHash);e&&(t.destroy(),e===t&&this.#t.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ea.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#t.get(t)}getAll(){return[...this.#t.values()]}find(t){const e={exact:!0,...t};return this.getAll().find(n=>NB(e,n))}findAll(t={}){const e=this.getAll();return Object.keys(t).length>0?e.filter(n=>NB(t,n)):e}notify(t){Ea.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){Ea.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ea.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},bde=class{#t;#e;#n;#a;#r;#i;#o;#s;constructor(t={}){this.#t=t.queryCache||new gde,this.#e=t.mutationCache||new hde,this.#n=t.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=yF.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#s=x1.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(t){return this.#t.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#e.findAll({...t,status:"pending"}).length}getQueryData(t){const e=this.defaultQueryOptions({queryKey:t});return this.#t.get(e.queryHash)?.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=this.#t.build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(Ah(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#t.findAll(t).map(({queryKey:e,state:n})=>{const r=n.data;return[e,r]})}setQueryData(t,e,n){const r=this.defaultQueryOptions({queryKey:t}),s=this.#t.get(r.queryHash)?.state.data,o=Yue(e,s);if(o!==void 0)return this.#t.build(this,r).setData(o,{...n,manual:!0})}setQueriesData(t,e,n){return Ea.batch(()=>this.#t.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){const e=this.defaultQueryOptions({queryKey:t});return this.#t.get(e.queryHash)?.state}removeQueries(t){const e=this.#t;Ea.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=this.#t;return Ea.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=Ea.batch(()=>this.#t.findAll(t).map(a=>a.cancel(n)));return Promise.all(r).then(ms).catch(ms)}invalidateQueries(t,e={}){return Ea.batch(()=>(this.#t.findAll(t).forEach(n=>{n.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=Ea.batch(()=>this.#t.findAll(t).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let s=a.fetch(void 0,n);return n.throwOnError||(s=s.catch(ms)),a.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(ms)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=this.#t.build(this,e);return n.isStaleByTime(Ah(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(ms).catch(ms)}fetchInfiniteQuery(t){return t.behavior=jB(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(ms).catch(ms)}ensureInfiniteQueryData(t){return t.behavior=jB(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return x1.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(t){this.#n=t}setQueryDefaults(t,e){this.#a.set(Tf(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...this.#a.values()],n={};return e.forEach(r=>{pv(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){this.#r.set(Tf(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...this.#r.values()],n={};return e.forEach(r=>{pv(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...this.#n.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=pF(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===bF&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#n.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},eX=w.createContext(void 0),en=t=>{const e=w.useContext(eX);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},xde=({client:t,children:e})=>(w.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),i.jsx(eX.Provider,{value:t,children:e})),tX=w.createContext(!1),nX=()=>w.useContext(tX);tX.Provider;function yde(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var vde=w.createContext(yde()),rX=()=>w.useContext(vde),aX=(t,e,n)=>{const r=n?.state.error&&typeof t.throwOnError=="function"?xF(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},iX=t=>{w.useEffect(()=>{t.clearReset()},[t])},sX=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:a})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(a&&t.data===void 0||xF(n,[t.error,r])),oX=t=>{if(t.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},lX=(t,e)=>t.isLoading&&t.isFetching&&!e,J2=(t,e)=>t?.suspense&&e.isPending,y1=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function SF({queries:t,...e},n){const r=en(),a=nX(),s=rX(),o=w.useMemo(()=>t.map(v=>{const g=r.defaultQueryOptions(v);return g._optimisticResults=a?"isRestoring":"optimistic",g}),[t,r,a]);o.forEach(v=>{oX(v);const g=r.getQueryCache().get(v.queryHash);aX(v,s,g)}),iX(s);const[l]=w.useState(()=>new pde(r,o,e)),[c,u,d]=l.getOptimisticResult(o,e.combine),h=!a&&e.subscribed!==!1;w.useSyncExternalStore(w.useCallback(v=>h?l.subscribe(Ea.batchCalls(v)):ms,[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),w.useEffect(()=>{l.setQueries(o,e)},[o,e,l]);const p=c.some((v,g)=>J2(o[g],v))?c.flatMap((v,g)=>{const y=o[g];if(y){const _=new vF(r,y);if(J2(y,v))return y1(y,_,s);lX(v,a)&&y1(y,_,s)}return[]}):[];if(p.length>0)throw Promise.all(p);const x=c.find((v,g)=>{const y=o[g];return y&&sX({result:v,errorResetBoundary:s,throwOnError:y.throwOnError,query:r.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(x?.error)throw x.error;return u(d())}function wde(t,e,n){const r=nX(),a=rX(),s=en(),o=s.defaultQueryOptions(t);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=s.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",oX(o),aX(o,a,l),iX(a);const c=!s.getQueryCache().get(o.queryHash),[u]=w.useState(()=>new e(s,o)),d=u.getOptimisticResult(o),h=!r&&t.subscribed!==!1;if(w.useSyncExternalStore(w.useCallback(f=>{const p=h?u.subscribe(Ea.batchCalls(f)):ms;return u.updateResult(),p},[u,h]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),w.useEffect(()=>{u.setOptions(o)},[o,u]),J2(o,d))throw y1(o,u,a);if(sX({result:d,errorResetBoundary:a,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw d.error;return s.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Af&&lX(d,r)&&(c?y1(o,u,a):l?.promise)?.catch(ms).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function Je(t,e){return wde(t,vF)}function st(t,e){const n=en(),[r]=w.useState(()=>new mde(n,t));w.useEffect(()=>{r.setOptions(t)},[r,t]);const a=w.useSyncExternalStore(w.useCallback(o=>r.subscribe(Ea.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),s=w.useCallback((o,l)=>{r.mutate(o,l).catch(ms)},[r]);if(a.error&&xF(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:s,mutateAsync:a.mutate}}const Sde=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_de=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase()),FB=t=>{const e=_de(t);return e.charAt(0).toUpperCase()+e.slice(1)},cX=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim(),Nde=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};var Cde={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const kde=w.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:s,iconNode:o,...l},c)=>w.createElement("svg",{ref:c,...Cde,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:cX("lucide",a),...!s&&!Nde(l)&&{"aria-hidden":"true"},...l},[...o.map(([u,d])=>w.createElement(u,d)),...Array.isArray(s)?s:[s]]));const et=(t,e)=>{const n=w.forwardRef(({className:r,...a},s)=>w.createElement(kde,{ref:s,iconNode:e,className:cX(`lucide-${Sde(FB(t))}`,`lucide-${t}`,r),...a}));return n.displayName=FB(t),n};const Ade=[["path",{d:"M18 17.5a2.5 2.5 0 1 1-4 2.03V12",key:"yd12zl"}],["path",{d:"M6 12H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"larmp2"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"M6.6 15.572A2 2 0 1 0 10 17v-5",key:"1x1kqn"}]],Tde=et("air-vent",Ade);const Mde=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],js=et("archive",Mde);const Pde=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]],Ede=et("arrow-down-wide-narrow",Pde);const jde=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],lb=et("arrow-down",jde);const Dde=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],_F=et("arrow-left",Dde);const Rde=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],e3=et("arrow-right-left",Rde);const Fde=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],t3=et("arrow-right",Fde);const Lde=[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]],NF=et("arrow-up-down",Lde);const Ode=[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h4",key:"q8tih4"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h10",key:"jvxblo"}]],Ide=et("arrow-up-narrow-wide",Ode);const zde=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Mf=et("arrow-up",zde);const Ude=[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]],Bde=et("beaker",Ude);const Hde=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],qg=et("bell",Hde);const $de=[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]],Vde=et("bold",$de);const qde=[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]],Gde=et("book",qde);const Wde=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Kde=et("bookmark",Wde);const Xde=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],Ja=et("box",Xde);const Yde=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],uX=et("briefcase",Yde);const Qde=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],HC=et("bug",Qde);const Zde=[["path",{d:"M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z",key:"trhst0"}],["path",{d:"M17 21v-2",key:"ds4u3f"}],["path",{d:"M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10",key:"1mo9zo"}],["path",{d:"M21 21v-2",key:"eo0ou"}],["path",{d:"M3 5V3",key:"1k5hjh"}],["path",{d:"M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z",key:"1dd30t"}],["path",{d:"M7 5V3",key:"1t1388"}]],Jde=et("cable",Zde);const ehe=[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]],the=et("calculator",ehe);const nhe=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],rhe=et("calendar-days",nhe);const ahe=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],ra=et("calendar",ahe);const ihe=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],cb=et("camera",ihe);const she=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],ohe=et("chart-column",she);const lhe=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],aa=et("check",lhe);const che=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Pn=et("chevron-down",che);const uhe=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],pi=et("chevron-right",uhe);const dhe=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Xl=et("chevron-left",dhe);const hhe=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],yl=et("chevron-up",hhe);const mhe=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],dX=et("chevrons-left",mhe);const fhe=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],hX=et("chevrons-right",fhe);const phe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Ba=et("circle-alert",phe);const ghe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]],zM=et("circle-arrow-up",ghe);const bhe=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],pr=et("circle-check-big",bhe);const xhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ub=et("circle-check",xhe);const yhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],vhe=et("circle-dot",yhe);const whe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],She=et("circle-stop",whe);const _he=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],mi=et("circle-x",_he);const Nhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],v1=et("circle",Nhe);const Che=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],khe=et("clipboard-list",Che);const Ahe=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Wn=et("clock",Ahe);const The=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]],Mhe=et("cloud-off",The);const Phe=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],$b=et("cloud",Phe);const Ehe=[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]],jhe=et("code-xml",Ehe);const Dhe=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],mX=et("code",Dhe);const Rhe=[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]],Fhe=et("coffee",Rhe);const Lhe=[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]],Ohe=et("coins",Lhe);const Ihe=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],zhe=et("cog",Ihe);const Uhe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Bhe=et("columns-2",Uhe);const Hhe=[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],$he=et("compass",Hhe);const Vhe=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Yl=et("copy",Vhe);const qhe=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],Og=et("cpu",qhe);const Ghe=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]],Whe=et("cylinder",Ghe);const Khe=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Ec=et("database",Khe);const Xhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M6 12c0-1.7.7-3.2 1.8-4.2",key:"oqkarx"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M18 12c0 1.7-.7 3.2-1.8 4.2",key:"1eah9h"}]],Yhe=et("disc-3",Xhe);const Qhe=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],n3=et("dollar-sign",Qhe);const Zhe=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],da=et("download",Zhe);const Jhe=[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]],$C=et("droplet",Jhe);const eme=[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]],CF=et("droplets",eme);const tme=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Th=et("ellipsis-vertical",tme);const nme=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]],UM=et("equal",nme);const rme=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Xr=et("external-link",rme);const ame=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],u0=et("eye-off",ame);const ime=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ql=et("eye",ime);const sme=[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]],fX=et("fan",sme);const ome=[["path",{d:"M14.5 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.8",key:"1kchwa"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11.7 14.2 7 17l-4.7-2.8",key:"1yk8tc"}],["path",{d:"M3 13.1a2 2 0 0 0-.999 1.76v3.24a2 2 0 0 0 .969 1.78L6 21.7a2 2 0 0 0 2.03.01L11 19.9a2 2 0 0 0 1-1.76V14.9a2 2 0 0 0-.97-1.78L8 11.3a2 2 0 0 0-2.03-.01z",key:"19flxy"}],["path",{d:"M7 17v5",key:"1yj1jh"}]],hf=et("file-box",ome);const lme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],w1=et("file-code",lme);const cme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],ume=et("file-exclamation-point",cme);const dme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],S1=et("file-spreadsheet",dme);const hme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ms=et("file-text",hme);const mme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],VC=et("file",mme);const fme=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]],Mh=et("film",fme);const pme=[["path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",key:"1slcih"}]],gme=et("flame",pme);const bme=[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]],gs=et("folder-kanban",bme);const xme=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Zl=et("folder-open",xme);const yme=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],vme=et("folder-plus",yme);const wme=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],Sme=et("folder-tree",wme);const _me=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],pX=et("folder",_me);const Nme=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]],Cme=et("fullscreen",Nme);const kme=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],qC=et("funnel",kme);const Ame=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],GC=et("gauge",Ame);const Tme=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],Mme=et("gift",Tme);const Pme=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]],Gg=et("git-compare",Pme);const Eme=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],r3=et("github",Eme);const jme=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Ph=et("globe",jme);const Dme=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],Eh=et("grip-vertical",Dme);const Rme=[["path",{d:"M3 7V5c0-1.1.9-2 2-2h2",key:"adw53z"}],["path",{d:"M17 3h2c1.1 0 2 .9 2 2v2",key:"an4l38"}],["path",{d:"M21 17v2c0 1.1-.9 2-2 2h-2",key:"144t0e"}],["path",{d:"M7 21H5c-1.1 0-2-.9-2-2v-2",key:"rtnfgi"}],["rect",{width:"7",height:"5",x:"7",y:"7",rx:"1",key:"1eyiv7"}],["rect",{width:"7",height:"5",x:"10",y:"12",rx:"1",key:"1qlmkx"}]],Fme=et("group",Rme);const Lme=[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]],gX=et("hand",Lme);const Ome=[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]],Vb=et("hard-drive",Ome);const Ime=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],zme=et("hash",Ime);const Ume=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]],Bme=et("headphones",Ume);const Hme=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],$me=et("heart",Hme);const Vme=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],db=et("history",Vme);const qme=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],d0=et("house",qme);const Gme=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Ju=et("image",Gme);const Wme=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Zs=et("info",Wme);const Kme=[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]],Xme=et("italic",Kme);const Yme=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],nl=et("key",Yme);const Qme=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],a3=et("keyboard",Qme);const Zme=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],fi=et("layers",Zme);const Jme=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],h0=et("layout-grid",Jme);const efe=[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]],tfe=et("link-2-off",efe);const nfe=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],jh=et("link-2",nfe);const rfe=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],qb=et("link",rfe);const afe=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],bX=et("list-ordered",afe);const ife=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["rect",{x:"3",y:"4",width:"6",height:"6",rx:"1",key:"cif1o7"}]],i3=et("list-todo",ife);const sfe=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],WC=et("list",sfe);const ofe=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],it=et("loader-circle",ofe);const lfe=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]],H_=et("lock-open",lfe);const cfe=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],zm=et("lock",cfe);const ufe=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],LB=et("log-in",ufe);const dfe=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],s3=et("log-out",dfe);const hfe=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],bv=et("mail",hfe);const mfe=[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]],ffe=et("map",mfe);const pfe=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],KC=et("maximize-2",pfe);const gfe=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],bfe=et("maximize",gfe);const xfe=[["path",{d:"M6 19v-3",key:"1nvgqn"}],["path",{d:"M10 19v-3",key:"iu8nkm"}],["path",{d:"M14 19v-3",key:"kcehxu"}],["path",{d:"M18 19v-3",key:"1vh91z"}],["path",{d:"M8 11V9",key:"63erz4"}],["path",{d:"M16 11V9",key:"fru6f3"}],["path",{d:"M12 11V9",key:"ha00sb"}],["path",{d:"M2 15h20",key:"16ne18"}],["path",{d:"M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.837V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.837Z",key:"lhddv3"}]],yfe=et("memory-stick",xfe);const vfe=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],wfe=et("menu",vfe);const Sfe=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],kF=et("minimize-2",Sfe);const _fe=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],xX=et("minimize",_fe);const Nfe=[["path",{d:"M5 12h14",key:"1ays0h"}]],_1=et("minus",Nfe);const Cfe=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],kfe=et("monitor",Cfe);const Afe=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],N1=et("moon",Afe);const Tfe=[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]],Mfe=et("move-right",Tfe);const Pfe=[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]],o3=et("music",Pfe);const Efe=[["path",{d:"M6 8.32a7.43 7.43 0 0 1 0 7.36",key:"9iaqei"}],["path",{d:"M9.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"1yha7l"}],["path",{d:"M12.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"4iu2gk"}],["path",{d:"M16.37 2a20.16 20.16 0 0 1 0 20",key:"sap9u2"}]],yX=et("nfc",Efe);const jfe=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],ni=et("package",jfe);const Dfe=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],XC=et("palette",Dfe);const Rfe=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],YC=et("pause",Rfe);const Ffe=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],Pf=et("pen-line",Ffe);const Lfe=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],ef=et("pen",Lfe);const Ofe=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],$a=et("pencil",Ofe);const Ife=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],zfe=et("phone",Ife);const Ufe=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],io=et("play",Ufe);const Bfe=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],fl=et("plug",Bfe);const Hfe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gn=et("plus",Hfe);const $fe=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],QC=et("power-off",$fe);const Vfe=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],md=et("power",Vfe);const qfe=[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]],gr=et("printer",qfe);const Gfe=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],vX=et("qr-code",Gfe);const Wfe=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],AF=et("radio",Wfe);const Kfe=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Ar=et("refresh-cw",Kfe);const Xfe=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],so=et("rotate-ccw",Xfe);const Yfe=[["path",{d:"M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z",key:"icamh8"}],["path",{d:"m14.5 12.5 2-2",key:"inckbg"}],["path",{d:"m11.5 9.5 2-2",key:"fmmyf7"}],["path",{d:"m8.5 6.5 2-2",key:"vc6u1g"}],["path",{d:"m17.5 15.5 2-2",key:"wo5hmg"}]],Qfe=et("ruler",Yfe);const Zfe=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],ps=et("save",Zfe);const Jfe=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"m19 8 3 8a5 5 0 0 1-6 0zV7",key:"zcdpyk"}],["path",{d:"M3 7h1a17 17 0 0 0 8-2 17 17 0 0 0 8 2h1",key:"1yorad"}],["path",{d:"m5 8 3 8a5 5 0 0 1-6 0zV7",key:"eua70x"}],["path",{d:"M7 21h10",key:"1b0cd5"}]],m0=et("scale",Jfe);const epe=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],C1=et("scan-search",epe);const tpe=[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]],npe=et("scissors",tpe);const rpe=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],xr=et("search",rpe);const ape=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],ZC=et("send",ape);const ipe=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Um=et("server",ipe);const spe=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],ed=et("settings-2",spe);const ope=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],f0=et("settings",ope);const lpe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],cpe=et("shield-alert",lpe);const upe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],l3=et("shield",upe);const dpe=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],wX=et("shopping-cart",dpe);const hpe=[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}],["path",{d:"M22 4v16",key:"sih9yq"}]],mpe=et("signal",hpe);const fpe=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],ppe=et("skip-back",fpe);const gpe=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],TF=et("skip-forward",gpe);const bpe=[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],OB=et("sliders-vertical",bpe);const xpe=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],hb=et("sparkles",xpe);const ype=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],oo=et("square-check-big",ype);const vpe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]],wpe=et("square-minus",vpe);const Spe=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],_pe=et("square-pen",Spe);const Npe=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],vl=et("square",Npe);const Cpe=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],Ef=et("star",Cpe);const kpe=[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}]],SX=et("sticky-note",kpe);const Ape=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],IB=et("sun",Ape);const Tpe=[["path",{d:"M15 3v18",key:"14nvp0"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]],Mpe=et("table-properties",Tpe);const Ppe=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],Vh=et("tag",Ppe);const Epe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],_X=et("target",Epe);const jpe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],NX=et("terminal",jpe);const Dpe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],Rpe=et("text-align-center",Dpe);const Fpe=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],Lpe=et("text-align-end",Fpe);const Ope=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],Ipe=et("text-align-start",Ope);const zpe=[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]],JC=et("thermometer",zpe);const Upe=[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]],Lu=et("timer",Upe);const Bpe=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Jt=et("trash-2",Bpe);const Hpe=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],MF=et("trending-down",Hpe);const $pe=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],c3=et("trending-up",$pe);const Vpe=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Tn=et("triangle-alert",Vpe);const qpe=[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]],Gpe=et("underline",qpe);const Wpe=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],ek=et("unlink",Wpe);const Kpe=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Ra=et("upload",Kpe);const Xpe=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],td=et("user",Xpe);const Ype=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],mh=et("users",Ype);const Qpe=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],PF=et("video",Qpe);const Zpe=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],Jpe=et("volume-2",Zpe);const ege=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],tge=et("volume-x",ege);const nge=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],rge=et("wand-sparkles",nge);const age=[["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}],["path",{d:"M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z",key:"56o5sh"}]],CX=et("weight",age);const ige=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],jf=et("wifi-off",ige);const sge=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],Wg=et("wifi",sge);const oge=[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]],kX=et("wind",oge);const lge=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Df=et("wrench",lge);const cge=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Lt=et("x",cge);const uge=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],EF=et("zoom-in",uge);const dge=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],nd=et("zap",dge);const hge=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],jF=et("zoom-out",hge),nn="/api/v1";let ln=localStorage.getItem("auth_token");function ky(t){ln=t,t?localStorage.setItem("auth_token",t):localStorage.removeItem("auth_token")}function rd(){return ln}function Bm(t){if(!t)return null;const e=t.match(/filename\*=(?:UTF-8|utf-8)''(.+?)(?:;|$)/);if(e)try{return decodeURIComponent(e[1])}catch{}return t.match(/filename="?([^";\n]+)"?/)?.[1]||null}async function Me(t,e={}){const n={"Content-Type":"application/json",...e.headers};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}${t}`,{...e,cache:"no-store",headers:n});if(!r.ok){const o=(await r.json().catch(()=>({}))).detail,l=typeof o=="string"?o:o?JSON.stringify(o):`HTTP ${r.status}`;throw r.status===401&&["Could not validate credentials","Token has expired","User not found or inactive","Invalid API key","API key has expired"].some(u=>l.includes(u))&&ky(null),new Error(l)}const a=r.headers.get("content-length");if(!(r.status===204||a==="0"))return await r.json()}const ne={getAuthStatus:()=>Me("/auth/status"),setupAuth:t=>Me("/auth/setup",{method:"POST",body:JSON.stringify(t)}),login:t=>Me("/auth/login",{method:"POST",body:JSON.stringify(t)}),logout:()=>Me("/auth/logout",{method:"POST"}),getCurrentUser:()=>Me("/auth/me"),disableAuth:()=>Me("/auth/disable",{method:"POST"}),testSMTP:t=>Me("/auth/smtp/test",{method:"POST",body:JSON.stringify(t)}),getSMTPSettings:()=>Me("/auth/smtp"),saveSMTPSettings:t=>Me("/auth/smtp",{method:"POST",body:JSON.stringify(t)}),enableAdvancedAuth:()=>Me("/auth/advanced-auth/enable",{method:"POST"}),disableAdvancedAuth:()=>Me("/auth/advanced-auth/disable",{method:"POST"}),getAdvancedAuthStatus:()=>Me("/auth/advanced-auth/status"),forgotPassword:t=>Me("/auth/forgot-password",{method:"POST",body:JSON.stringify(t)}),resetUserPassword:t=>Me("/auth/reset-password",{method:"POST",body:JSON.stringify(t)}),getUsers:()=>Me("/users/"),getUser:t=>Me(`/users/${t}`),createUser:t=>Me("/users/",{method:"POST",body:JSON.stringify(t)}),updateUser:(t,e)=>Me(`/users/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteUser:(t,e=!1)=>Me(`/users/${t}?delete_items=${e}`,{method:"DELETE"}),getUserItemsCount:t=>Me(`/users/${t}/items-count`),changePassword:(t,e)=>Me("/users/me/change-password",{method:"POST",body:JSON.stringify({current_password:t,new_password:e})}),getPermissions:()=>Me("/groups/permissions"),getGroups:()=>Me("/groups/"),getGroup:t=>Me(`/groups/${t}`),createGroup:t=>Me("/groups/",{method:"POST",body:JSON.stringify(t)}),updateGroup:(t,e)=>Me(`/groups/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteGroup:t=>Me(`/groups/${t}`,{method:"DELETE"}),addUserToGroup:(t,e)=>Me(`/groups/${t}/users/${e}`,{method:"POST"}),removeUserFromGroup:(t,e)=>Me(`/groups/${t}/users/${e}`,{method:"DELETE"}),getPrinters:()=>Me("/printers/"),getPrinter:t=>Me(`/printers/${t}`),createPrinter:t=>Me("/printers/",{method:"POST",body:JSON.stringify(t)}),updatePrinter:(t,e)=>Me(`/printers/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deletePrinter:(t,e=!0)=>Me(`/printers/${t}?delete_archives=${e}`,{method:"DELETE"}),getDeveloperModeWarnings:()=>Me("/printers/developer-mode-warnings"),getAvailableFilaments:(t,e)=>{const n=new URLSearchParams({model:t});return e&&n.set("location",e),Me(`/printers/available-filaments?${n}`)},getPrinterStatus:t=>Me(`/printers/${t}/status`),refreshPrinterStatus:t=>Me(`/printers/${t}/refresh-status`,{method:"POST"}),connectPrinter:t=>Me(`/printers/${t}/connect`,{method:"POST"}),disconnectPrinter:t=>Me(`/printers/${t}/disconnect`,{method:"POST"}),testExternalCamera:(t,e,n)=>Me(`/printers/${t}/camera/external/test?url=${encodeURIComponent(e)}&camera_type=${encodeURIComponent(n)}`,{method:"POST"}),stopPrint:t=>Me(`/printers/${t}/print/stop`,{method:"POST"}),pausePrint:t=>Me(`/printers/${t}/print/pause`,{method:"POST"}),resumePrint:t=>Me(`/printers/${t}/print/resume`,{method:"POST"}),clearPlate:t=>Me(`/printers/${t}/clear-plate`,{method:"POST"}),getCurrentPrintUser:t=>Me(`/printers/${t}/current-print-user`),setChamberLight:(t,e)=>Me(`/printers/${t}/chamber-light?on=${e}`,{method:"POST"}),getPrintableObjects:t=>Me(`/printers/${t}/print/objects`),skipObjects:(t,e)=>Me(`/printers/${t}/print/skip-objects`,{method:"POST",body:JSON.stringify(e)}),clearHMSErrors:t=>Me(`/printers/${t}/hms/clear`,{method:"POST"}),refreshAmsSlot:(t,e,n)=>Me(`/printers/${t}/ams/${e}/slot/${n}/refresh`,{method:"POST"}),enableMQTTLogging:t=>Me(`/printers/${t}/logging/enable`,{method:"POST"}),disableMQTTLogging:t=>Me(`/printers/${t}/logging/disable`,{method:"POST"}),getMQTTLogs:t=>Me(`/printers/${t}/logging`),clearMQTTLogs:t=>Me(`/printers/${t}/logging`,{method:"DELETE"}),getPrinterFiles:(t,e="/")=>Me(`/printers/${t}/files?path=${encodeURIComponent(e)}`),getPrinterFileDownloadUrl:(t,e)=>`${nn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,getPrinterFileGcodeUrl:(t,e)=>`${nn}/printers/${t}/files/gcode?path=${encodeURIComponent(e)}`,getPrinterFilePlates:(t,e)=>Me(`/printers/${t}/files/plates?path=${encodeURIComponent(e)}`),getPrinterFilePlateThumbnail:(t,e,n)=>`${nn}/printers/${t}/files/plate-thumbnail/${e}?path=${encodeURIComponent(n)}`,downloadPrinterFile:async(t,e)=>{const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/printers/${t}/files/download?path=${encodeURIComponent(e)}`,{headers:n});if(!r.ok){const u=await r.json().catch(()=>({}));throw new Error(u.detail||`HTTP ${r.status}`)}const a=r.headers.get("Content-Disposition"),s=Bm(a)||e.split("/").pop()||"download",o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},downloadPrinterFilesAsZip:async(t,e)=>{const n={"Content-Type":"application/json"};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/printers/${t}/files/download-zip`,{method:"POST",headers:n,body:JSON.stringify({paths:e})});if(!r.ok){const a=await r.json().catch(()=>({}));throw new Error(a.detail||`HTTP ${r.status}`)}return r.blob()},deletePrinterFile:(t,e)=>Me(`/printers/${t}/files?path=${encodeURIComponent(e)}`,{method:"DELETE"}),getPrinterStorage:t=>Me(`/printers/${t}/storage`),getArchives:(t,e,n=50,r=0)=>{const a=new URLSearchParams;return t&&a.set("printer_id",String(t)),e&&a.set("project_id",String(e)),a.set("limit",String(n)),a.set("offset",String(r)),Me(`/archives/?${a}`)},getArchive:t=>Me(`/archives/${t}`),searchArchives:(t,e)=>{const n=new URLSearchParams;return n.set("q",t),e?.printerId&&n.set("printer_id",String(e.printerId)),e?.projectId&&n.set("project_id",String(e.projectId)),e?.status&&n.set("status",e.status),e?.limit&&n.set("limit",String(e.limit)),e?.offset&&n.set("offset",String(e.offset)),Me(`/archives/search?${n}`)},rebuildSearchIndex:()=>Me("/archives/search/rebuild-index",{method:"POST"}),updateArchive:(t,e)=>Me(`/archives/${t}`,{method:"PATCH",body:JSON.stringify(e)}),toggleFavorite:t=>Me(`/archives/${t}/favorite`,{method:"POST"}),deleteArchive:t=>Me(`/archives/${t}`,{method:"DELETE"}),getArchiveStats:()=>Me("/archives/stats"),getTags:()=>Me("/archives/tags"),renameTag:(t,e)=>Me(`/archives/tags/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({new_name:e})}),deleteTag:t=>Me(`/archives/tags/${encodeURIComponent(t)}`,{method:"DELETE"}),recalculateCosts:()=>Me("/archives/recalculate-costs",{method:"POST"}),getFailureAnalysis:t=>{const e=new URLSearchParams;return t?.days&&e.set("days",String(t.days)),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.projectId&&e.set("project_id",String(t.projectId)),Me(`/archives/analysis/failures?${e}`)},compareArchives:t=>Me(`/archives/compare?archive_ids=${t.join(",")}`),findSimilarArchives:(t,e=10)=>Me(`/archives/${t}/similar?limit=${e}`),exportArchives:async t=>{const e=new URLSearchParams;t?.format&&e.set("format",t.format),t?.fields&&e.set("fields",t.fields.join(",")),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.projectId&&e.set("project_id",String(t.projectId)),t?.status&&e.set("status",t.status),t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.search&&e.set("search",t.search);const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/archives/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const a=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"archives_export.xlsx":"archives_export.csv";if(a){const l=a.match(/filename="?([^"]+)"?/);l&&(s=l[1])}return{blob:await r.blob(),filename:s}},exportStats:async t=>{const e=new URLSearchParams;t?.format&&e.set("format",t.format),t?.days&&e.set("days",String(t.days)),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.projectId&&e.set("project_id",String(t.projectId));const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/archives/stats/export?${e}`,{headers:n});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${r.status}`)}const a=r.headers.get("Content-Disposition");let s=t?.format==="xlsx"?"stats_export.xlsx":"stats_export.csv";if(a){const l=a.match(/filename="?([^"]+)"?/);l&&(s=l[1])}return{blob:await r.blob(),filename:s}},getArchiveDuplicates:t=>Me(`/archives/${t}/duplicates`),backfillContentHashes:()=>Me("/archives/backfill-hashes",{method:"POST"}),getArchiveThumbnail:t=>`${nn}/archives/${t}/thumbnail?v=${Date.now()}`,getArchivePlateThumbnail:(t,e)=>`${nn}/archives/${t}/plate-thumbnail/${e}`,getArchiveDownload:t=>`${nn}/archives/${t}/download`,downloadArchive:async(t,e)=>{const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/archives/${t}/download`,{headers:n});if(!r.ok){const u=await r.json().catch(()=>({}));throw new Error(u.detail||`HTTP ${r.status}`)}const a=r.headers.get("Content-Disposition"),s=Bm(a)||e||`archive_${t}.3mf`,o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},getArchiveGcode:t=>`${nn}/archives/${t}/gcode`,getArchivePlatePreview:t=>`${nn}/archives/${t}/plate-preview`,getArchiveTimelapse:t=>`${nn}/archives/${t}/timelapse?v=${Date.now()}`,scanArchiveTimelapse:t=>Me(`/archives/${t}/timelapse/scan`,{method:"POST"}),selectArchiveTimelapse:(t,e)=>Me(`/archives/${t}/timelapse/select?filename=${encodeURIComponent(e)}`,{method:"POST"}),deleteArchiveTimelapse:t=>Me(`/archives/${t}/timelapse`,{method:"DELETE"}),uploadArchiveTimelapse:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/archives/${t}/timelapse/upload`,{method:"POST",headers:r,body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},getTimelapseInfo:t=>Me(`/archives/${t}/timelapse/info`),getTimelapseThumbnails:(t,e=10)=>Me(`/archives/${t}/timelapse/thumbnails?count=${e}`),processTimelapse:async(t,e,n)=>{const r=new FormData;r.append("trim_start",String(e.trimStart??0)),e.trimEnd!==void 0&&r.append("trim_end",String(e.trimEnd)),r.append("speed",String(e.speed??1)),r.append("save_mode",e.saveMode),e.outputFilename&&r.append("output_filename",e.outputFilename),n&&r.append("audio",n);const a={};ln&&(a.Authorization=`Bearer ${ln}`);const s=await fetch(`${nn}/archives/${t}/timelapse/process`,{method:"POST",headers:a,body:r});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},getArchivePhotoUrl:(t,e)=>`${nn}/archives/${t}/photos/${encodeURIComponent(e)}`,uploadArchivePhoto:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/archives/${t}/photos`,{headers:r,method:"POST",body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},deleteArchivePhoto:(t,e)=>Me(`/archives/${t}/photos/${encodeURIComponent(e)}`,{method:"DELETE"}),getSource3mfDownloadUrl:t=>`${nn}/archives/${t}/source`,downloadSource3mf:async t=>{const e={};ln&&(e.Authorization=`Bearer ${ln}`);const n=await fetch(`${nn}/archives/${t}/source`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),a=Bm(r)||`source_${t}.3mf`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=a,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(o)},getSource3mfForSlicer:(t,e)=>`${nn}/archives/${t}/source/${encodeURIComponent(e.endsWith(".3mf")?e:e+".3mf")}`,createSourceSlicerToken:t=>Me(`/archives/${t}/source-slicer-token`,{method:"POST"}),getSourceSlicerDownloadUrl:(t,e,n)=>`${nn}/archives/${t}/source-dl/${e}/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`,uploadSource3mf:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/archives/${t}/source`,{method:"POST",headers:r,body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},deleteSource3mf:t=>Me(`/archives/${t}/source`,{method:"DELETE"}),getF3dDownloadUrl:t=>`${nn}/archives/${t}/f3d`,downloadF3d:async t=>{const e={};ln&&(e.Authorization=`Bearer ${ln}`);const n=await fetch(`${nn}/archives/${t}/f3d`,{headers:e});if(!n.ok){const c=await n.json().catch(()=>({}));throw new Error(c.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),a=Bm(r)||`archive_${t}.f3d`,s=await n.blob(),o=window.URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=a,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(o)},uploadF3d:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/archives/${t}/f3d`,{method:"POST",headers:r,body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},deleteF3d:t=>Me(`/archives/${t}/f3d`,{method:"DELETE"}),getArchiveQRCodeUrl:(t,e=200)=>`${nn}/archives/${t}/qrcode?size=${e}`,getArchiveCapabilities:t=>Me(`/archives/${t}/capabilities`),getArchiveProjectPage:t=>Me(`/archives/${t}/project-page`),updateArchiveProjectPage:(t,e)=>Me(`/archives/${t}/project-page`,{method:"PATCH",body:JSON.stringify(e)}),getArchiveProjectImageUrl:(t,e)=>`${nn}/archives/${t}/project-image/${encodeURIComponent(e)}`,getArchiveForSlicer:(t,e)=>`${nn}/archives/${t}/file/${encodeURIComponent(e.endsWith(".3mf")?e:e+".3mf")}`,createArchiveSlicerToken:t=>Me(`/archives/${t}/slicer-token`,{method:"POST"}),getArchiveSlicerDownloadUrl:(t,e,n)=>`${nn}/archives/${t}/dl/${e}/${encodeURIComponent(n.endsWith(".3mf")?n:n+".3mf")}`,getArchivePlates:t=>Me(`/archives/${t}/plates`),getArchiveFilamentRequirements:(t,e)=>Me(`/archives/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),reprintArchive:(t,e,n)=>Me(`/archives/${t}/reprint?printer_id=${e}`,{method:"POST",headers:n?{"Content-Type":"application/json"}:void 0,body:n?JSON.stringify(n):void 0}),uploadArchive:async(t,e)=>{const n=new FormData;n.append("file",t);const r=e?`${nn}/archives/upload?printer_id=${e}`:`${nn}/archives/upload`,a={};ln&&(a.Authorization=`Bearer ${ln}`);const s=await fetch(r,{method:"POST",headers:a,body:n});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},uploadArchivesBulk:async(t,e)=>{const n=new FormData;t.forEach(o=>n.append("files",o));const r=e?`${nn}/archives/upload-bulk?printer_id=${e}`:`${nn}/archives/upload-bulk`,a={};ln&&(a.Authorization=`Bearer ${ln}`);const s=await fetch(r,{method:"POST",headers:a,body:n});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${s.status}`)}return s.json()},getPrintLog:t=>{const e=new URLSearchParams;return t?.search&&e.set("search",t.search),t?.printerId&&e.set("printer_id",String(t.printerId)),t?.username&&e.set("created_by_username",t.username),t?.status&&e.set("status",t.status),t?.dateFrom&&e.set("date_from",t.dateFrom),t?.dateTo&&e.set("date_to",t.dateTo),t?.limit&&e.set("limit",String(t.limit)),t?.offset!==void 0&&e.set("offset",String(t.offset)),Me(`/print-log/?${e}`)},getPrintLogThumbnail:t=>`${nn}/print-log/${t}/thumbnail`,clearPrintLog:()=>Me("/print-log/",{method:"DELETE"}),getSettings:()=>Me("/settings/"),updateSettings:t=>Me("/settings/",{method:"PUT",body:JSON.stringify(t)}),getMQTTStatus:()=>Me("/settings/mqtt/status"),resetSettings:()=>Me("/settings/reset",{method:"POST"}),exportBackup:async()=>{const t=`${nn}/settings/backup`,e={};ln&&(e.Authorization=`Bearer ${ln}`);const n=await fetch(t,{headers:e});if(!n.ok){const o=await n.text();throw new Error(o||`Backup failed with status ${n.status}`)}const r=n.headers.get("Content-Disposition");let a="bambuddy-backup.zip";if(r){const o=r.match(/filename=([^;]+)/);o&&(a=o[1].trim())}return{blob:await n.blob(),filename:a}},importBackup:async t=>{const e=new FormData;e.append("file",t);const n=`${nn}/settings/restore`,r={};return ln&&(r.Authorization=`Bearer ${ln}`),(await fetch(n,{method:"POST",headers:r,body:e})).json()},checkFfmpeg:()=>Me("/settings/check-ffmpeg"),getNetworkInterfaces:()=>Me("/settings/network-interfaces"),getCloudStatus:()=>Me("/cloud/status"),cloudLogin:(t,e,n="global")=>Me("/cloud/login",{method:"POST",body:JSON.stringify({email:t,password:e,region:n})}),cloudVerify:(t,e,n)=>Me("/cloud/verify",{method:"POST",body:JSON.stringify({email:t,code:e,tfa_key:n})}),cloudSetToken:t=>Me("/cloud/token",{method:"POST",body:JSON.stringify({access_token:t})}),cloudLogout:()=>Me("/cloud/logout",{method:"POST"}),getCloudSettings:(t="02.04.00.70")=>Me(`/cloud/settings?version=${t}`),getBuiltinFilaments:()=>Me("/cloud/builtin-filaments"),getFilamentIdMap:()=>Me("/cloud/filament-id-map"),getCloudSettingDetail:t=>Me(`/cloud/settings/${t}`),createCloudSetting:t=>Me("/cloud/settings",{method:"POST",body:JSON.stringify(t)}),updateCloudSetting:(t,e)=>Me(`/cloud/settings/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCloudSetting:t=>Me(`/cloud/settings/${t}`,{method:"DELETE"}),getCloudDevices:()=>Me("/cloud/devices"),getCloudFields:t=>Me(`/cloud/fields/${t}`),getAllCloudFields:()=>Me("/cloud/fields"),getFilamentInfo:t=>Me("/cloud/filament-info",{method:"POST",body:JSON.stringify(t)}),getSmartPlugs:()=>Me("/smart-plugs/"),getSmartPlug:t=>Me(`/smart-plugs/${t}`),getSmartPlugByPrinter:t=>Me(`/smart-plugs/by-printer/${t}`),getScriptPlugsByPrinter:t=>Me(`/smart-plugs/by-printer/${t}/scripts`),createSmartPlug:t=>Me("/smart-plugs/",{method:"POST",body:JSON.stringify(t)}),updateSmartPlug:(t,e)=>Me(`/smart-plugs/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSmartPlug:t=>Me(`/smart-plugs/${t}`,{method:"DELETE"}),controlSmartPlug:(t,e)=>Me(`/smart-plugs/${t}/control`,{method:"POST",body:JSON.stringify({action:e})}),getSmartPlugStatus:t=>Me(`/smart-plugs/${t}/status`),testSmartPlugConnection:(t,e,n)=>Me("/smart-plugs/test-connection",{method:"POST",body:JSON.stringify({ip_address:t,username:e,password:n})}),startTasmotaScan:()=>Me("/smart-plugs/discover/scan",{method:"POST"}),getTasmotaScanStatus:()=>Me("/smart-plugs/discover/status"),stopTasmotaScan:()=>Me("/smart-plugs/discover/stop",{method:"POST"}),getDiscoveredTasmotaDevices:()=>Me("/smart-plugs/discover/devices"),testHAConnection:(t,e)=>Me("/smart-plugs/ha/test-connection",{method:"POST",body:JSON.stringify({url:t,token:e})}),getHAEntities:t=>{const e=t?`?search=${encodeURIComponent(t)}`:"";return Me(`/smart-plugs/ha/entities${e}`)},getHASensorEntities:()=>Me("/smart-plugs/ha/sensors"),getQueue:(t,e,n)=>{const r=new URLSearchParams;return t&&r.set("printer_id",String(t)),e&&r.set("status",e),n&&r.set("target_model",n),Me(`/queue/?${r}`)},getQueueItem:t=>Me(`/queue/${t}`),addToQueue:t=>Me("/queue/",{method:"POST",body:JSON.stringify(t)}),updateQueueItem:(t,e)=>Me(`/queue/${t}`,{method:"PATCH",body:JSON.stringify(e)}),removeFromQueue:t=>Me(`/queue/${t}`,{method:"DELETE"}),reorderQueue:t=>Me("/queue/reorder",{method:"POST",body:JSON.stringify({items:t})}),cancelQueueItem:t=>Me(`/queue/${t}/cancel`,{method:"POST"}),stopQueueItem:t=>Me(`/queue/${t}/stop`,{method:"POST"}),startQueueItem:t=>Me(`/queue/${t}/start`,{method:"POST"}),bulkUpdateQueue:t=>Me("/queue/bulk",{method:"PATCH",body:JSON.stringify(t)}),getKProfiles:(t,e="0.4")=>Me(`/printers/${t}/kprofiles/?nozzle_diameter=${e}`),setKProfile:(t,e)=>Me(`/printers/${t}/kprofiles/`,{method:"POST",body:JSON.stringify(e)}),deleteKProfile:(t,e)=>Me(`/printers/${t}/kprofiles/`,{method:"DELETE",body:JSON.stringify(e)}),setKProfilesBatch:(t,e)=>Me(`/printers/${t}/kprofiles/batch`,{method:"POST",body:JSON.stringify(e)}),getKProfileNotes:t=>Me(`/printers/${t}/kprofiles/notes`),setKProfileNote:(t,e,n)=>Me(`/printers/${t}/kprofiles/notes`,{method:"PUT",body:JSON.stringify({setting_id:e,note:n})}),deleteKProfileNote:(t,e)=>Me(`/printers/${t}/kprofiles/notes/${encodeURIComponent(e)}`,{method:"DELETE"}),getSlotPresets:t=>Me(`/printers/${t}/slot-presets`),getSlotPreset:(t,e,n)=>Me(`/printers/${t}/slot-presets/${e}/${n}`),saveSlotPreset:(t,e,n,r,a,s="cloud")=>Me(`/printers/${t}/slot-presets/${e}/${n}?preset_id=${encodeURIComponent(r)}&preset_name=${encodeURIComponent(a)}&preset_source=${encodeURIComponent(s)}`,{method:"PUT"}),deleteSlotPreset:(t,e,n)=>Me(`/printers/${t}/slot-presets/${e}/${n}`,{method:"DELETE"}),configureAmsSlot:(t,e,n,r)=>{const a=new URLSearchParams({tray_info_idx:r.tray_info_idx,tray_type:r.tray_type,tray_sub_brands:r.tray_sub_brands,tray_color:r.tray_color,nozzle_temp_min:r.nozzle_temp_min.toString(),nozzle_temp_max:r.nozzle_temp_max.toString(),cali_idx:r.cali_idx.toString(),nozzle_diameter:r.nozzle_diameter});return r.setting_id&&a.set("setting_id",r.setting_id),r.kprofile_filament_id&&a.set("kprofile_filament_id",r.kprofile_filament_id),r.kprofile_setting_id&&a.set("kprofile_setting_id",r.kprofile_setting_id),r.k_value!==void 0&&r.k_value>0&&a.set("k_value",r.k_value.toString()),Me(`/printers/${t}/slots/${e}/${n}/configure?${a}`,{method:"POST"})},resetAmsSlot:(t,e,n)=>Me(`/printers/${t}/ams/${e}/tray/${n}/reset`,{method:"POST"}),listFilaments:()=>Me("/filament-catalog/"),getFilament:t=>Me(`/filament-catalog/${t}`),getFilamentsByType:t=>Me(`/filament-catalog/by-type/${t}`),getNotificationProviders:()=>Me("/notifications/"),getNotificationProvider:t=>Me(`/notifications/${t}`),createNotificationProvider:t=>Me("/notifications/",{method:"POST",body:JSON.stringify(t)}),updateNotificationProvider:(t,e)=>Me(`/notifications/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteNotificationProvider:t=>Me(`/notifications/${t}`,{method:"DELETE"}),testNotificationProvider:t=>Me(`/notifications/${t}/test`,{method:"POST"}),testNotificationConfig:t=>Me("/notifications/test-config",{method:"POST",body:JSON.stringify(t)}),testAllNotificationProviders:()=>Me("/notifications/test-all",{method:"POST"}),getNotificationTemplates:()=>Me("/notification-templates"),getNotificationTemplate:t=>Me(`/notification-templates/${t}`),updateNotificationTemplate:(t,e)=>Me(`/notification-templates/${t}`,{method:"PUT",body:JSON.stringify(e)}),resetNotificationTemplate:t=>Me(`/notification-templates/${t}/reset`,{method:"POST"}),getTemplateVariables:()=>Me("/notification-templates/variables"),previewTemplate:t=>Me("/notification-templates/preview",{method:"POST",body:JSON.stringify(t)}),getNotificationLogs:t=>{const e=new URLSearchParams;return t?.limit&&e.set("limit",String(t.limit)),t?.offset&&e.set("offset",String(t.offset)),t?.provider_id&&e.set("provider_id",String(t.provider_id)),t?.event_type&&e.set("event_type",t.event_type),t?.success!==void 0&&e.set("success",String(t.success)),t?.days&&e.set("days",String(t.days)),Me(`/notifications/logs?${e}`)},getNotificationLogStats:(t=7)=>Me(`/notifications/logs/stats?days=${t}`),clearNotificationLogs:(t=30)=>Me(`/notifications/logs?older_than_days=${t}`,{method:"DELETE"}),getSpoolmanStatus:()=>Me("/spoolman/status"),connectSpoolman:()=>Me("/spoolman/connect",{method:"POST"}),disconnectSpoolman:()=>Me("/spoolman/disconnect",{method:"POST"}),syncPrinterAms:t=>Me(`/spoolman/sync/${t}`,{method:"POST"}),syncAllPrintersAms:()=>Me("/spoolman/sync-all",{method:"POST"}),getSpoolmanSpools:()=>Me("/spoolman/spools"),getSpoolmanFilaments:()=>Me("/spoolman/filaments"),getUnlinkedSpools:()=>Me("/spoolman/spools/unlinked"),getLinkedSpools:()=>Me("/spoolman/spools/linked"),linkSpool:(t,e)=>Me(`/spoolman/spools/${t}/link`,{method:"POST",body:JSON.stringify({tray_uuid:e})}),getSpoolmanSettings:()=>Me("/settings/spoolman"),updateSpoolmanSettings:t=>Me("/settings/spoolman",{method:"PUT",body:JSON.stringify(t)}),getSpools:(t=!1)=>Me(`/inventory/spools?include_archived=${t}`),getSpool:t=>Me(`/inventory/spools/${t}`),createSpool:t=>Me("/inventory/spools",{method:"POST",body:JSON.stringify(t)}),bulkCreateSpools:(t,e)=>Me("/inventory/spools/bulk",{method:"POST",body:JSON.stringify({spool:t,quantity:e})}),updateSpool:(t,e)=>Me(`/inventory/spools/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteSpool:t=>Me(`/inventory/spools/${t}`,{method:"DELETE"}),archiveSpool:t=>Me(`/inventory/spools/${t}/archive`,{method:"POST"}),restoreSpool:t=>Me(`/inventory/spools/${t}/restore`,{method:"POST"}),getSpoolKProfiles:t=>Me(`/inventory/spools/${t}/k-profiles`),saveSpoolKProfiles:(t,e)=>Me(`/inventory/spools/${t}/k-profiles`,{method:"PUT",body:JSON.stringify(e)}),getAssignments:t=>Me(`/inventory/assignments${t?`?printer_id=${t}`:""}`),assignSpool:t=>Me("/inventory/assignments",{method:"POST",body:JSON.stringify(t)}),unassignSpool:(t,e,n)=>Me(`/inventory/assignments/${t}/${e}/${n}`,{method:"DELETE"}),getSpoolCatalog:()=>Me("/inventory/catalog"),addCatalogEntry:t=>Me("/inventory/catalog",{method:"POST",body:JSON.stringify(t)}),updateCatalogEntry:(t,e)=>Me(`/inventory/catalog/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteCatalogEntry:t=>Me(`/inventory/catalog/${t}`,{method:"DELETE"}),resetSpoolCatalog:()=>Me("/inventory/catalog/reset",{method:"POST"}),getColorCatalog:()=>Me("/inventory/colors"),addColorEntry:t=>Me("/inventory/colors",{method:"POST",body:JSON.stringify(t)}),updateColorEntry:(t,e)=>Me(`/inventory/colors/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteColorEntry:t=>Me(`/inventory/colors/${t}`,{method:"DELETE"}),resetColorCatalog:()=>Me("/inventory/colors/reset",{method:"POST"}),lookupColor:(t,e,n)=>Me(`/inventory/colors/lookup?manufacturer=${encodeURIComponent(t)}&color_name=${encodeURIComponent(e)}${n?`&material=${encodeURIComponent(n)}`:""}`),searchColors:(t,e)=>Me(`/inventory/colors/search?${t?`manufacturer=${encodeURIComponent(t)}`:""}${t&&e?"&":""}${e?`material=${encodeURIComponent(e)}`:""}`),linkTagToSpool:(t,e)=>Me(`/inventory/spools/${t}/link-tag`,{method:"PATCH",body:JSON.stringify(e)}),getSpoolUsageHistory:(t,e=50)=>Me(`/inventory/spools/${t}/usage?limit=${e}`),getAllUsageHistory:(t=100,e)=>Me(`/inventory/usage?limit=${t}${e?`&printer_id=${e}`:""}`),clearSpoolUsageHistory:t=>Me(`/inventory/spools/${t}/usage`,{method:"DELETE"}),syncWeightsFromAms:()=>Me("/inventory/sync-ams-weights",{method:"POST"}),getFilamentPresets:()=>Me("/cloud/filaments"),getVersion:()=>Me("/updates/version"),checkForUpdates:()=>Me("/updates/check"),applyUpdate:()=>Me("/updates/apply",{method:"POST"}),getUpdateStatus:()=>Me("/updates/status"),getMaintenanceTypes:()=>Me("/maintenance/types"),createMaintenanceType:t=>Me("/maintenance/types",{method:"POST",body:JSON.stringify(t)}),updateMaintenanceType:(t,e)=>Me(`/maintenance/types/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteMaintenanceType:t=>Me(`/maintenance/types/${t}`,{method:"DELETE"}),restoreDefaultMaintenanceTypes:()=>Me("/maintenance/types/restore-defaults",{method:"POST"}),getMaintenanceOverview:()=>Me("/maintenance/overview"),getPrinterMaintenance:t=>Me(`/maintenance/printers/${t}`),updateMaintenanceItem:(t,e)=>Me(`/maintenance/items/${t}`,{method:"PATCH",body:JSON.stringify(e)}),performMaintenance:(t,e)=>Me(`/maintenance/items/${t}/perform`,{method:"POST",body:JSON.stringify({notes:e})}),getMaintenanceHistory:t=>Me(`/maintenance/items/${t}/history`),getMaintenanceSummary:()=>Me("/maintenance/summary"),setPrinterHours:(t,e)=>Me(`/maintenance/printers/${t}/hours?total_hours=${e}`,{method:"PATCH"}),assignMaintenanceType:(t,e)=>Me(`/maintenance/printers/${t}/assign/${e}`,{method:"POST"}),removeMaintenanceItem:t=>Me(`/maintenance/items/${t}`,{method:"DELETE"}),getCameraStreamUrl:(t,e=10)=>`${nn}/printers/${t}/camera/stream?fps=${e}`,getCameraSnapshotUrl:t=>`${nn}/printers/${t}/camera/snapshot`,testCameraConnection:t=>Me(`/printers/${t}/camera/test`),getCameraStatus:t=>Me(`/printers/${t}/camera/status`),checkPlateEmpty:(t,e)=>{const n=new URLSearchParams;return n.set("use_external",String(e?.useExternal??!1)),n.set("include_debug_image",String(e?.includeDebugImage??!1)),Me(`/printers/${t}/camera/check-plate?${n.toString()}`)},getPlateDetectionStatus:t=>Me(`/printers/${t}/camera/plate-detection/status`),calibratePlateDetection:(t,e)=>{const n=new URLSearchParams;return e?.label&&n.set("label",e.label),n.set("use_external",String(e?.useExternal??!1)),Me(`/printers/${t}/camera/plate-detection/calibrate?${n.toString()}`,{method:"POST"})},deletePlateCalibration:t=>Me(`/printers/${t}/camera/plate-detection/calibrate`,{method:"DELETE"}),getPlateReferences:t=>Me(`/printers/${t}/camera/plate-detection/references`),getPlateReferenceThumbnailUrl:(t,e)=>`${nn}/printers/${t}/camera/plate-detection/references/${e}/thumbnail`,updatePlateReferenceLabel:(t,e,n)=>{const r=new URLSearchParams;return r.set("label",n),Me(`/printers/${t}/camera/plate-detection/references/${e}?${r.toString()}`,{method:"PUT"})},deletePlateReference:(t,e)=>Me(`/printers/${t}/camera/plate-detection/references/${e}`,{method:"DELETE"}),getExternalLinks:()=>Me("/external-links/"),getExternalLink:t=>Me(`/external-links/${t}`),createExternalLink:t=>Me("/external-links/",{method:"POST",body:JSON.stringify(t)}),updateExternalLink:(t,e)=>Me(`/external-links/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteExternalLink:t=>Me(`/external-links/${t}`,{method:"DELETE"}),reorderExternalLinks:t=>Me("/external-links/reorder",{method:"PUT",body:JSON.stringify({ids:t})}),uploadExternalLinkIcon:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/external-links/${t}/icon`,{method:"POST",headers:r,body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},deleteExternalLinkIcon:t=>Me(`/external-links/${t}/icon`,{method:"DELETE"}),getExternalLinkIconUrl:t=>`${nn}/external-links/${t}/icon`,getProjects:t=>{const e=new URLSearchParams;return t&&e.set("status",t),Me(`/projects/?${e}`)},getProject:t=>Me(`/projects/${t}`),createProject:t=>Me("/projects/",{method:"POST",body:JSON.stringify(t)}),updateProject:(t,e)=>Me(`/projects/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteProject:t=>Me(`/projects/${t}`,{method:"DELETE"}),getProjectArchives:(t,e=100,n=0)=>Me(`/projects/${t}/archives?limit=${e}&offset=${n}`),addArchivesToProject:(t,e)=>Me(`/projects/${t}/add-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),removeArchivesFromProject:(t,e)=>Me(`/projects/${t}/remove-archives`,{method:"POST",body:JSON.stringify({archive_ids:e})}),addQueueItemsToProject:(t,e)=>Me(`/projects/${t}/add-queue`,{method:"POST",body:JSON.stringify({queue_item_ids:e})}),uploadProjectAttachment:async(t,e)=>{const n=new FormData;n.append("file",e);const r={};ln&&(r.Authorization=`Bearer ${ln}`);const a=await fetch(`${nn}/projects/${t}/attachments`,{method:"POST",headers:r,body:n});if(!a.ok){const s=await a.json().catch(()=>({}));throw new Error(s.detail||`HTTP ${a.status}`)}return a.json()},getProjectAttachmentUrl:(t,e)=>`${nn}/projects/${t}/attachments/${encodeURIComponent(e)}`,deleteProjectAttachment:(t,e)=>Me(`/projects/${t}/attachments/${encodeURIComponent(e)}`,{method:"DELETE"}),getProjectBOM:t=>Me(`/projects/${t}/bom`),createBOMItem:(t,e)=>Me(`/projects/${t}/bom`,{method:"POST",body:JSON.stringify(e)}),updateBOMItem:(t,e,n)=>Me(`/projects/${t}/bom/${e}`,{method:"PATCH",body:JSON.stringify(n)}),deleteBOMItem:(t,e)=>Me(`/projects/${t}/bom/${e}`,{method:"DELETE"}),getTemplates:()=>Me("/projects/templates/"),createTemplateFromProject:t=>Me(`/projects/${t}/create-template`,{method:"POST"}),createProjectFromTemplate:(t,e)=>Me(`/projects/from-template/${t}${e?`?name=${encodeURIComponent(e)}`:""}`,{method:"POST"}),getProjectTimeline:(t,e=50)=>Me(`/projects/${t}/timeline?limit=${e}`),exportProjectJson:t=>Me(`/projects/${t}/export?format=json`),importProject:t=>Me("/projects/import",{method:"POST",body:JSON.stringify(t)}),importProjectFile:async t=>{const e=new FormData;e.append("file",t);const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/projects/import/file`,{method:"POST",headers:n,body:e});if(!r.ok){const a=await r.json().catch(()=>({}));throw new Error(a.detail||`HTTP ${r.status}`)}return r.json()},exportProjectZip:async t=>{const e={};ln&&(e.Authorization=`Bearer ${ln}`);const n=await fetch(`${nn}/projects/${t}/export`,{headers:e});if(!n.ok){const o=await n.json().catch(()=>({}));throw new Error(o.detail||`HTTP ${n.status}`)}const r=n.headers.get("Content-Disposition"),a=Bm(r)||`project_${t}.zip`;return{blob:await n.blob(),filename:a}},getAPIKeys:()=>Me("/api-keys/"),createAPIKey:t=>Me("/api-keys/",{method:"POST",body:JSON.stringify(t)}),updateAPIKey:(t,e)=>Me(`/api-keys/${t}`,{method:"PATCH",body:JSON.stringify(e)}),deleteAPIKey:t=>Me(`/api-keys/${t}`,{method:"DELETE"}),getAMSHistory:(t,e,n=24)=>Me(`/ams-history/${t}/${e}?hours=${n}`),getSystemInfo:()=>Me("/system/info"),getStorageUsage:t=>{const e=new URLSearchParams;t?.refresh&&e.set("refresh","true");const n=e.toString();return Me(`/system/storage-usage${n?`?${n}`:""}`)},getLibraryFolders:()=>Me("/library/folders"),createLibraryFolder:t=>Me("/library/folders",{method:"POST",body:JSON.stringify(t)}),updateLibraryFolder:(t,e)=>Me(`/library/folders/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFolder:t=>Me(`/library/folders/${t}`,{method:"DELETE"}),getLibraryFoldersByProject:t=>Me(`/library/folders/by-project/${t}`),getLibraryFoldersByArchive:t=>Me(`/library/folders/by-archive/${t}`),getLibraryFiles:(t,e=!0)=>{const n=new URLSearchParams;return t!=null&&n.set("folder_id",String(t)),n.set("include_root",String(e)),Me(`/library/files?${n}`)},getLibraryFile:t=>Me(`/library/files/${t}`),uploadLibraryFile:async(t,e,n=!0)=>{const r=new FormData;r.append("file",t);const a=new URLSearchParams;e&&a.set("folder_id",String(e)),a.set("generate_stl_thumbnails",String(n));const s={};ln&&(s.Authorization=`Bearer ${ln}`);const o=await fetch(`${nn}/library/files?${a}`,{method:"POST",headers:s,body:r});if(!o.ok){const l=await o.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${o.status}`)}return o.json()},extractZipFile:async(t,e,n=!0,r=!1,a=!0)=>{const s=new FormData;s.append("file",t);const o=new URLSearchParams;e&&o.set("folder_id",String(e)),o.set("preserve_structure",String(n)),o.set("create_folder_from_zip",String(r)),o.set("generate_stl_thumbnails",String(a));const l={};ln&&(l.Authorization=`Bearer ${ln}`);const c=await fetch(`${nn}/library/files/extract-zip?${o}`,{method:"POST",headers:l,body:s});if(!c.ok){const u=await c.json().catch(()=>({}));throw new Error(u.detail||`HTTP ${c.status}`)}return c.json()},updateLibraryFile:(t,e)=>Me(`/library/files/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLibraryFile:t=>Me(`/library/files/${t}`,{method:"DELETE"}),getLibraryFileDownloadUrl:t=>`${nn}/library/files/${t}/download`,createLibrarySlicerToken:t=>Me(`/library/files/${t}/slicer-token`,{method:"POST"}),getLibrarySlicerDownloadUrl:(t,e,n)=>`${nn}/library/files/${t}/dl/${e}/${encodeURIComponent(n)}`,downloadLibraryFile:async(t,e)=>{const n={};ln&&(n.Authorization=`Bearer ${ln}`);const r=await fetch(`${nn}/library/files/${t}/download`,{headers:n});if(!r.ok){const u=await r.json().catch(()=>({}));throw new Error(u.detail||`HTTP ${r.status}`)}const a=r.headers.get("Content-Disposition"),s=Bm(a)||e||`file_${t}`,o=await r.blob(),l=window.URL.createObjectURL(o),c=document.createElement("a");c.href=l,c.download=s,document.body.appendChild(c),c.click(),document.body.removeChild(c),window.URL.revokeObjectURL(l)},getLibraryFileThumbnailUrl:t=>`${nn}/library/files/${t}/thumbnail`,getLibraryFilePlateThumbnail:(t,e)=>`${nn}/library/files/${t}/plate-thumbnail/${e}`,getLibraryFileGcodeUrl:t=>`${nn}/library/files/${t}/gcode`,moveLibraryFiles:(t,e)=>Me("/library/files/move",{method:"POST",body:JSON.stringify({file_ids:t,folder_id:e})}),bulkDeleteLibrary:(t,e)=>Me("/library/bulk-delete",{method:"POST",body:JSON.stringify({file_ids:t,folder_ids:e})}),getLibraryStats:()=>Me("/library/stats"),batchGenerateStlThumbnails:t=>Me("/library/generate-stl-thumbnails",{method:"POST",body:JSON.stringify(t)}),addLibraryFilesToQueue:t=>Me("/library/files/add-to-queue",{method:"POST",body:JSON.stringify({file_ids:t})}),printLibraryFile:(t,e,n)=>Me(`/library/files/${t}/print?printer_id=${e}`,{method:"POST",body:n?JSON.stringify(n):void 0}),cancelBackgroundDispatchJob:t=>Me(`/background-dispatch/${t}`,{method:"DELETE"}),getLibraryFilePlates:t=>Me(`/library/files/${t}/plates`),getLibraryFileFilamentRequirements:(t,e)=>Me(`/library/files/${t}/filament-requirements${e!==void 0?`?plate_id=${e}`:""}`),getGitHubBackupConfig:()=>Me("/github-backup/config"),saveGitHubBackupConfig:t=>Me("/github-backup/config",{method:"POST",body:JSON.stringify(t)}),updateGitHubBackupConfig:t=>Me("/github-backup/config",{method:"PATCH",body:JSON.stringify(t)}),deleteGitHubBackupConfig:()=>Me("/github-backup/config",{method:"DELETE"}),testGitHubConnection:(t,e)=>Me(`/github-backup/test?repo_url=${encodeURIComponent(t)}&token=${encodeURIComponent(e)}`,{method:"POST"}),testGitHubStoredConnection:()=>Me("/github-backup/test-stored",{method:"POST"}),triggerGitHubBackup:()=>Me("/github-backup/run",{method:"POST"}),getGitHubBackupStatus:()=>Me("/github-backup/status"),getGitHubBackupLogs:(t=50)=>Me(`/github-backup/logs?limit=${t}`),clearGitHubBackupLogs:(t=10)=>Me(`/github-backup/logs?keep_last=${t}`,{method:"DELETE"}),getLocalPresets:()=>Me("/local-presets/"),getLocalPresetDetail:t=>Me(`/local-presets/${t}`),importLocalPresets:t=>fetch(`${nn}/local-presets/import`,{method:"POST",headers:ln?{Authorization:`Bearer ${ln}`}:{},body:t}).then(async e=>{if(!e.ok){const n=await e.json().catch(()=>({}));throw new Error(n.detail||`HTTP ${e.status}`)}return e.json()}),createLocalPreset:t=>Me("/local-presets/",{method:"POST",body:JSON.stringify(t)}),updateLocalPreset:(t,e)=>Me(`/local-presets/${t}`,{method:"PUT",body:JSON.stringify(e)}),deleteLocalPreset:t=>Me(`/local-presets/${t}`,{method:"DELETE"}),refreshBaseProfileCache:()=>Me("/local-presets/base-cache/refresh",{method:"POST"})},dc={getInfo:()=>Me("/discovery/info"),getStatus:()=>Me("/discovery/status"),startDiscovery:(t=10)=>Me(`/discovery/start?duration=${t}`,{method:"POST"}),stopDiscovery:()=>Me("/discovery/stop",{method:"POST"}),getDiscoveredPrinters:()=>Me("/discovery/printers"),startSubnetScan:(t,e=1)=>Me("/discovery/scan",{method:"POST",body:JSON.stringify({subnet:t,timeout:e})}),getScanStatus:()=>Me("/discovery/scan/status"),stopSubnetScan:()=>Me("/discovery/scan/stop",{method:"POST"})},mge={getSettings:()=>Me("/settings/virtual-printer")},k1={list:()=>Me("/virtual-printers"),get:t=>Me(`/virtual-printers/${t}`),create:t=>Me("/virtual-printers",{method:"POST",body:JSON.stringify(t)}),update:(t,e)=>Me(`/virtual-printers/${t}`,{method:"PUT",body:JSON.stringify(e)}),remove:t=>Me(`/virtual-printers/${t}`,{method:"DELETE"})},Eg={list:()=>Me("/pending-uploads/"),getCount:()=>Me("/pending-uploads/count"),get:t=>Me(`/pending-uploads/${t}`),archive:(t,e)=>Me(`/pending-uploads/${t}/archive`,{method:"POST",body:JSON.stringify(e||{})}),discard:t=>Me(`/pending-uploads/${t}`,{method:"DELETE"}),archiveAll:()=>Me("/pending-uploads/archive-all",{method:"POST"}),discardAll:()=>Me("/pending-uploads/discard-all",{method:"DELETE"})},$_={checkUpdates:()=>Me("/firmware/updates"),checkPrinterUpdate:t=>Me(`/firmware/updates/${t}`),prepareUpload:t=>Me(`/firmware/updates/${t}/prepare`),startUpload:t=>Me(`/firmware/updates/${t}/upload`,{method:"POST"}),getUploadStatus:t=>Me(`/firmware/updates/${t}/upload/status`)},Kg={getDebugLoggingState:()=>Me("/support/debug-logging"),setDebugLogging:t=>Me("/support/debug-logging",{method:"POST",body:JSON.stringify({enabled:t})}),downloadSupportBundle:async()=>{const t={};ln&&(t.Authorization=`Bearer ${ln}`);const e=await fetch(`${nn}/support/bundle`,{headers:t});if(!e.ok){const l=await e.json().catch(()=>({}));throw new Error(l.detail||`HTTP ${e.status}`)}const n=e.headers.get("Content-Disposition"),r=Bm(n)||"bambuddy-support.zip",a=await e.blob(),s=window.URL.createObjectURL(a),o=document.createElement("a");o.href=s,o.download=r,document.body.appendChild(o),o.click(),document.body.removeChild(o),window.URL.revokeObjectURL(s)},getLogs:t=>{const e=new URLSearchParams;t?.limit&&e.set("limit",t.limit.toString()),t?.level&&e.set("level",t.level),t?.search&&e.set("search",t.search);const n=e.toString();return Me(`/support/logs${n?`?${n}`:""}`)},clearLogs:()=>Me("/support/logs",{method:"DELETE"})},$y={getDevices:()=>Me("/spoolbuddy/devices"),registerDevice:t=>Me("/spoolbuddy/devices/register",{method:"POST",body:JSON.stringify(t)}),tare:t=>Me(`/spoolbuddy/devices/${t}/calibration/tare`,{method:"POST",body:JSON.stringify({})}),setCalibrationFactor:(t,e,n)=>Me(`/spoolbuddy/devices/${t}/calibration/set-factor`,{method:"POST",body:JSON.stringify({known_weight_grams:e,raw_adc:n})}),getCalibration:t=>Me(`/spoolbuddy/devices/${t}/calibration`),updateSpoolWeight:(t,e)=>Me("/spoolbuddy/scale/update-spool-weight",{method:"POST",body:JSON.stringify({spool_id:t,weight_grams:e})})},AX=w.createContext(void 0);function fge({children:t}){const[e,n]=w.useState(()=>{const C=localStorage.getItem("theme-mode"),j=localStorage.getItem("theme");return C||j||"dark"}),[r,a]=w.useState(()=>localStorage.getItem("dark-style")||"classic"),[s,o]=w.useState(()=>localStorage.getItem("dark-background")||"neutral"),[l,c]=w.useState(()=>localStorage.getItem("dark-accent")||"green"),[u,d]=w.useState(()=>localStorage.getItem("light-style")||"classic"),[h,f]=w.useState(()=>localStorage.getItem("light-background")||"neutral"),[p,x]=w.useState(()=>localStorage.getItem("light-accent")||"green");w.useEffect(()=>{ne.getSettings().then(C=>{C.dark_style&&(a(C.dark_style),localStorage.setItem("dark-style",C.dark_style)),C.dark_background&&(o(C.dark_background),localStorage.setItem("dark-background",C.dark_background)),C.dark_accent&&(c(C.dark_accent),localStorage.setItem("dark-accent",C.dark_accent)),C.light_style&&(d(C.light_style),localStorage.setItem("light-style",C.light_style)),C.light_background&&(f(C.light_background),localStorage.setItem("light-background",C.light_background)),C.light_accent&&(x(C.light_accent),localStorage.setItem("light-accent",C.light_accent))}).catch(()=>{})},[]),w.useEffect(()=>{const C=document.documentElement;C.classList.remove("dark","style-classic","style-glow","style-vibrant","bg-neutral","bg-warm","bg-cool","bg-oled","bg-slate","bg-forest","accent-green","accent-teal","accent-blue","accent-orange","accent-purple","accent-red"),e==="dark"?(C.classList.add("dark"),C.classList.add(`style-${r}`),C.classList.add(`bg-${s}`),C.classList.add(`accent-${l}`)):(C.classList.add(`style-${u}`),C.classList.add(`bg-${h}`),C.classList.add(`accent-${p}`)),localStorage.setItem("theme-mode",e),localStorage.removeItem("theme")},[e,r,s,l,u,h,p]);const v=()=>n(C=>C==="dark"?"light":"dark"),g=C=>n(C),y=C=>{a(C),localStorage.setItem("dark-style",C),ne.updateSettings({dark_style:C}).catch(()=>{})},_=C=>{o(C),localStorage.setItem("dark-background",C),ne.updateSettings({dark_background:C}).catch(()=>{})},N=C=>{c(C),localStorage.setItem("dark-accent",C),ne.updateSettings({dark_accent:C}).catch(()=>{})},k=C=>{d(C),localStorage.setItem("light-style",C),ne.updateSettings({light_style:C}).catch(()=>{})},A=C=>{f(C),localStorage.setItem("light-background",C),ne.updateSettings({light_background:C}).catch(()=>{})},M=C=>{x(C),localStorage.setItem("light-accent",C),ne.updateSettings({light_accent:C}).catch(()=>{})};return i.jsx(AX.Provider,{value:{mode:e,darkStyle:r,darkBackground:s,darkAccent:l,lightStyle:u,lightBackground:h,lightAccent:p,toggleMode:v,setMode:g,setDarkStyle:y,setDarkBackground:_,setDarkAccent:N,setLightStyle:k,setLightBackground:A,setLightAccent:M},children:t})}function tp(){const t=w.useContext(AX);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}function wt({children:t,className:e="",onClick:n,onContextMenu:r,...a}){return i.jsx("div",{className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary card-shadow ${e}`,onClick:n,onContextMenu:r,...a,children:t})}function zn({children:t,className:e=""}){return i.jsx("div",{className:`px-6 py-4 border-b border-bambu-dark-tertiary ${e}`,children:t})}function _t({children:t,className:e=""}){return i.jsx("div",{className:`p-6 ${e}`,children:t})}function pge(t,e,n){return[{category:"Navigation",items:t?t.slice(0,9).map((a,s)=>({keys:[String(s+1)],description:a.type==="external"?`Open ${a.label}`:`Go to ${a.labelKey?n(a.labelKey):a.label}`,isExternal:a.type==="external"})):e?e.map((a,s)=>({keys:[String(s+1)],description:`Go to ${n(a.labelKey)}`,isExternal:!1})):[{keys:["1"],description:"Go to Printers",isExternal:!1},{keys:["2"],description:"Go to Archives",isExternal:!1},{keys:["3"],description:"Go to Queue",isExternal:!1},{keys:["4"],description:"Go to Statistics",isExternal:!1},{keys:["5"],description:"Go to Cloud Profiles",isExternal:!1},{keys:["6"],description:"Go to Settings",isExternal:!1}]},{category:"Archives",items:[{keys:["/"],description:"Focus search",isExternal:!1},{keys:["U"],description:"Open upload modal",isExternal:!1},{keys:["Esc"],description:"Clear selection / blur input",isExternal:!1},{keys:["Right-click"],description:"Context menu on cards",isExternal:!1}]},{category:"K-Profiles",items:[{keys:["R"],description:"Refresh profiles",isExternal:!1},{keys:["N"],description:"New profile",isExternal:!1},{keys:["Esc"],description:"Exit selection mode",isExternal:!1}]},{category:"General",items:[{keys:["?"],description:"Show this help",isExternal:!1}]}]}function zB({children:t}){return i.jsx("kbd",{className:"px-2 py-1 text-xs font-mono bg-bambu-dark border border-bambu-dark-tertiary rounded text-white",children:t})}function gge({onClose:t,navItems:e,sidebarItems:n}){const{t:r}=Ot(),a=pge(n,e,r);return w.useEffect(()=>{const s=o=>{o.key==="Escape"&&t()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:i.jsx(wt,{className:"w-full max-w-md",onClick:s=>s.stopPropagation(),children:i.jsxs(_t,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(a3,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Keyboard Shortcuts"})]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4 space-y-6 max-h-[60vh] overflow-y-auto",children:a.map(s=>i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:s.category}),i.jsx("div",{className:"space-y-2",children:s.items.map(o=>i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"text-white text-sm flex items-center gap-1.5",children:[o.description,o.isExternal&&i.jsx(Xr,{className:"w-3 h-3 text-bambu-gray"})]}),i.jsx("div",{className:"flex gap-1",children:o.keys.map(l=>i.jsx(zB,{children:l},l))})]},o.description))})]},s.category))}),i.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("p",{className:"text-xs text-bambu-gray text-center",children:["Press ",i.jsx(zB,{children:"Esc"})," or click outside to close"]})})]})})})}function Ce({variant:t="primary",size:e="md",className:n="",children:r,...a}){const s="inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-bambu-dark disabled:opacity-50 disabled:cursor-not-allowed",o={primary:"bg-bambu-green hover:bg-bambu-green-light text-white focus:ring-bambu-green",secondary:"bg-bambu-dark-tertiary hover:bg-bambu-gray-dark text-white focus:ring-bambu-gray",danger:"bg-red-600 hover:bg-red-700 text-white focus:ring-red-500",ghost:"bg-transparent hover:bg-bambu-dark-tertiary text-bambu-gray-light hover:text-white"},l={sm:"px-3 py-1.5 text-sm gap-1.5 min-h-[44px] md:min-h-0",md:"px-4 py-2 text-sm gap-2 min-h-[44px] md:min-h-0",lg:"px-6 py-3 text-base gap-2 min-h-[48px] md:min-h-0"};return i.jsx("button",{className:`${s} ${o[t]} ${l[e]} ${n}`,...a,children:r})}function gn({title:t,message:e,confirmText:n,cancelText:r,cancelVariant:a,cardClassName:s,variant:o="default",isLoading:l=!1,loadingText:c,onConfirm:u,onCancel:d}){const{t:h}=Ot(),f=n??h("common.confirm"),p=r??h("common.cancel"),x=c??h("common.loading");w.useEffect(()=>{const y=_=>{_.key==="Escape"&&!l&&d()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[d,l]);const g={danger:{icon:"text-red-400",button:"bg-red-500 hover:bg-red-600"},warning:{icon:"text-yellow-400",button:"bg-yellow-500 hover:bg-yellow-600"},default:{icon:"text-bambu-green",button:"bg-bambu-green hover:bg-bambu-green-dark"}}[o];return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l?void 0:d,children:i.jsx(wt,{className:`w-full max-w-md ${s??""}`,onClick:y=>y.stopPropagation(),children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:`p-2 rounded-full bg-bambu-dark ${g.icon}`,children:i.jsx(Tn,{className:"w-6 h-6"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t}),i.jsx("p",{className:"text-bambu-gray text-sm",children:e})]})]}),i.jsxs("div",{className:"flex gap-3 mt-6",children:[i.jsx(Ce,{variant:a??"secondary",onClick:d,className:"flex-1",disabled:l,children:p}),i.jsx(Ce,{onClick:u,className:`flex-1 ${g.button}`,disabled:l,children:l?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),x]}):f})]})]})})})}function bge({plug:t}){const e=en(),[n,r]=w.useState(null),{data:a,isLoading:s}=Je({queryKey:["smart-plug-status",t.id],queryFn:()=>ne.getSmartPlugStatus(t.id),refetchInterval:1e4}),o=st({mutationFn:p=>ne.controlSmartPlug(t.id,p),onSuccess:()=>{e.invalidateQueries({queryKey:["smart-plug-status",t.id]})}}),l=a?.state==="ON",c=t.plug_type==="mqtt"&&a?.energy?.power!==null&&a?.energy?.power!==void 0,u=(a?.reachable??!1)||c,d=o.isPending,h=t.plug_type==="mqtt",f=()=>{n&&(o.mutate(n),r(null))};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between py-2 px-3 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`p-1.5 rounded ${h?u?"bg-teal-500/20":"bg-red-500/20":u?l?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:h?i.jsx(AF,{className:`w-4 h-4 ${u?"text-teal-400":"text-red-400"}`}):i.jsx(fl,{className:`w-4 h-4 ${u?l?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white font-medium",children:t.name}),i.jsx("div",{className:"flex items-center gap-1 text-xs",children:s?i.jsx(it,{className:"w-3 h-3 text-bambu-gray animate-spin"}):h?u?i.jsxs(i.Fragment,{children:[i.jsx(nd,{className:"w-3 h-3 text-teal-400"}),i.jsxs("span",{className:"text-teal-400",children:[Math.round(a?.energy?.power??0),"W"]}),i.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),i.jsx(Ql,{className:"w-3 h-3 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:"Monitor"})]}):i.jsxs(i.Fragment,{children:[i.jsx(jf,{className:"w-3 h-3 text-status-error"}),i.jsx("span",{className:"text-status-error",children:"Waiting"})]}):u?i.jsxs(i.Fragment,{children:[i.jsx(Wg,{className:"w-3 h-3 text-status-ok"}),i.jsx("span",{className:l?"text-status-ok":"text-bambu-gray",children:a?.state||"Unknown"}),a?.energy?.power!==null&&a?.energy?.power!==void 0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-bambu-gray mx-1",children:"|"}),i.jsx(nd,{className:"w-3 h-3 text-yellow-400"}),i.jsxs("span",{className:"text-yellow-400",children:[Math.round(a.energy.power),"W"]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx(jf,{className:"w-3 h-3 text-status-error"}),i.jsx("span",{className:"text-status-error",children:"Offline"})]})})]})]}),!h&&i.jsxs("div",{className:"flex gap-1",children:[i.jsx("button",{onClick:()=>r("on"),disabled:!u||d,className:`p-1.5 rounded transition-colors ${l?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"} disabled:opacity-50 disabled:cursor-not-allowed`,title:"Turn On",children:d?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(md,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("off"),disabled:!u||d,className:`p-1.5 rounded transition-colors ${!l&&u?"bg-bambu-dark-tertiary text-white":"bg-bambu-dark text-bambu-gray hover:text-white"} disabled:opacity-50 disabled:cursor-not-allowed`,title:"Turn Off",children:d?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(QC,{className:"w-4 h-4"})})]})]}),n&&i.jsx(gn,{title:`Turn ${n==="on"?"On":"Off"} Smart Plug`,message:`Are you sure you want to turn ${n==="on"?"on":"off"} "${t.name}"?`,confirmText:n==="on"?"Turn On":"Turn Off",variant:n==="off"?"warning":"default",onConfirm:f,onCancel:()=>r(null)})]})}function UB({onClose:t}){const{data:e,isLoading:n}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),r=e?.filter(a=>a.show_in_switchbar)||[];return i.jsxs("div",{className:"absolute bottom-full left-0 mb-2 w-72 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-xl z-50",onMouseLeave:t,children:[i.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary",children:i.jsxs("h3",{className:"text-sm font-semibold text-white flex items-center gap-2",children:[i.jsx(fl,{className:"w-4 h-4 text-bambu-green"}),"Smart Switches"]})}),i.jsx("div",{className:"p-2 max-h-80 overflow-y-auto",children:n?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-gray animate-spin"})}):r.length===0?i.jsxs("div",{className:"text-center py-6 px-4",children:[i.jsx(fl,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"No switches in switchbar"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:'Enable "Show in Switchbar" in Settings > Smart Plugs'})]}):i.jsx("div",{className:"space-y-1",children:r.map(a=>i.jsx(bge,{plug:a},a.id))})})]})}const TX=[{name:"globe",icon:Ph},{name:"link",icon:qb},{name:"external-link",icon:Xr},{name:"book",icon:Gde},{name:"file-text",icon:Ms},{name:"home",icon:d0},{name:"star",icon:Ef},{name:"heart",icon:$me},{name:"bookmark",icon:Kde},{name:"shopping-cart",icon:wX},{name:"music",icon:o3},{name:"video",icon:PF},{name:"image",icon:Ju},{name:"camera",icon:cb},{name:"map",icon:ffe},{name:"compass",icon:$he},{name:"coffee",icon:Fhe},{name:"gift",icon:Mme},{name:"wrench",icon:Df},{name:"zap",icon:nd},{name:"cloud",icon:$b},{name:"database",icon:Ec},{name:"folder",icon:pX},{name:"mail",icon:bv},{name:"phone",icon:zfe},{name:"user",icon:td},{name:"users",icon:mh},{name:"server",icon:Um},{name:"terminal",icon:NX},{name:"code",icon:mX}];function tk(t){return TX.find(n=>n.name===t)?.icon||qb}function xge({value:t,onChange:e}){const[n,r]=w.useState(!1),a=tk(t);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{type:"button",onClick:()=>r(!n),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white hover:border-bambu-gray focus:border-bambu-green focus:outline-none w-full",children:[i.jsx(a,{className:"w-5 h-5"}),i.jsx("span",{className:"text-sm text-bambu-gray flex-1 text-left",children:t})]}),n&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>r(!1)}),i.jsx("div",{className:"absolute z-50 mt-1 w-full max-h-64 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg",children:i.jsx("div",{className:"grid grid-cols-5 gap-1 p-2",children:TX.map(({name:s,icon:o})=>i.jsx("button",{type:"button",onClick:()=>{e(s),r(!1)},className:`p-2 rounded-lg transition-colors flex items-center justify-center ${t===s?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:s,children:i.jsx(o,{className:"w-5 h-5"})},s))})})]})]})}const BB=1144;function yge(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<BB:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${BB-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}const MX=w.createContext(void 0);function vge({children:t}){const[e,n]=w.useState(null),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!0),u=w.useRef(!1),d=w.useRef(!0),h=async()=>{try{const M=await ne.getAuthStatus();if(!d.current)return;if(a(M.auth_enabled),o(M.requires_setup),M.auth_enabled)if(rd())try{const j=await ne.getCurrentUser();if(!d.current)return;n(j)}catch{if(ky(null),!d.current)return;n(null)}else n(null);else n(null)}catch{if(!d.current)return;a(!1),n(null)}finally{d.current&&c(!1)}};w.useEffect(()=>(d.current=!0,h(),()=>{d.current=!1}),[]),w.useEffect(()=>{if(!l&&s&&!r){const M=window.location.pathname;M!=="/setup"&&!M.startsWith("/camera/")&&!u.current&&(u.current=!0,window.location.href="/setup")}else s||(u.current=!1)},[l,s,r]);const f=async(M,C)=>{const j=await ne.login({username:M,password:C});ky(j.access_token),n(j.user)},p=()=>{ky(null),n(null),ne.logout().catch(()=>{}),window.location.href="/login"},x=async()=>{if(r&&rd())try{const M=await ne.getCurrentUser();d.current&&n(M)}catch{ky(null),d.current&&n(null)}},v=async()=>{await h()},g=w.useMemo(()=>new Set(e?.permissions??[]),[e?.permissions]),y=w.useMemo(()=>r?e?.is_admin??!1:!0,[r,e?.is_admin]),_=w.useCallback(M=>!r||y?!0:g.has(M),[r,y,g]),N=w.useCallback((...M)=>!r||y?!0:M.some(C=>g.has(C)),[r,y,g]),k=w.useCallback((...M)=>!r||y?!0:M.every(C=>g.has(C)),[r,y,g]),A=w.useCallback((M,C,j)=>{if(!r||y)return!0;const P=`${M}:${C}_all`,E=`${M}:${C}_own`;return g.has(P)?!0:g.has(E)?j==null?!1:j===e?.id:!1},[r,y,g,e?.id]);return i.jsx(MX.Provider,{value:{user:e,authEnabled:r,requiresSetup:s,loading:l,isAdmin:y,login:f,logout:p,refreshUser:x,refreshAuth:v,hasPermission:_,hasAnyPermission:N,hasAllPermissions:k,canModify:A},children:t})}function Ir(){const t=w.useContext(MX);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t}const PX=w.createContext(void 0);function an(){const t=w.useContext(PX);if(!t)throw new Error("useToast must be used within a ToastProvider");return t}const HB={success:i.jsx(pr,{className:"w-5 h-5 text-green-400"}),error:i.jsx(mi,{className:"w-5 h-5 text-red-400"}),warning:i.jsx(Ba,{className:"w-5 h-5 text-yellow-400"}),info:i.jsx(Zs,{className:"w-5 h-5 text-blue-400"}),loading:i.jsx(it,{className:"w-5 h-5 text-bambu-green animate-spin"})},wge={success:"bg-green-500/10 border-green-500/30",error:"bg-red-500/10 border-red-500/30",warning:"bg-yellow-500/10 border-yellow-500/30",info:"bg-blue-500/10 border-blue-500/30",loading:"bg-bambu-green/10 border-bambu-green/30"};function Sge({children:t}){const{t:e}=Ot(),[n,r]=w.useState([]),[a,s]=w.useState(!1),[o,l]=w.useState(new Set),c=w.useRef(new Map),u="background-dispatch",d=w.useRef(null),h=w.useCallback(g=>!Number.isFinite(g)||g<0?"0 B":g<1024?`${g} B`:g<1024*1024?`${(g/1024).toFixed(1)} KB`:g<1024*1024*1024?`${(g/(1024*1024)).toFixed(1)} MB`:`${(g/(1024*1024*1024)).toFixed(1)} GB`,[]);w.useEffect(()=>{const g=c.current;return()=>{g.forEach(y=>clearTimeout(y)),g.clear()}},[]);const f=w.useCallback((g,y="success")=>{const _=Math.random().toString(36).substr(2,9);r(k=>[...k,{id:_,message:g,type:y}]);const N=setTimeout(()=>{r(k=>k.filter(A=>A.id!==_)),c.current.delete(_)},3e3);c.current.set(_,N)},[]),p=w.useCallback((g,y,_="info")=>{r(N=>N.find(A=>A.id===g)?N.map(A=>A.id===g?{...A,message:y,type:_,persistent:!0}:A):[...N,{id:g,message:y,type:_,persistent:!0}])},[]),x=w.useCallback(g=>{const y=c.current.get(g);y&&(clearTimeout(y),c.current.delete(g)),r(_=>_.filter(N=>N.id!==g))},[]),v=w.useCallback(async g=>{l(y=>{const _=new Set(y);return _.add(g),_});try{const y=await ne.cancelBackgroundDispatchJob(g);f(y.status==="cancelling"?e("backgroundDispatch.toast.cancellingUpload"):e("backgroundDispatch.toast.cancelled"),"info")}catch(y){const _=y instanceof Error?y.message:e("backgroundDispatch.toast.cancelFailed");f(_,"error")}finally{l(y=>{const _=new Set(y);return _.delete(g),_})}},[f,e]);return w.useEffect(()=>{const g=(N,k,A)=>{const M=N.findIndex(j=>j.jobId===k);if(M===-1)return[...N,{jobId:k,...A}];const C=[...N];return C[M]={...C[M],...A},C},y=N=>{switch(N){case"failed":return 0;case"processing":return 1;case"dispatched":return 2;case"completed":return 3;case"cancelled":return 4}},_=N=>{const k=N.detail||{},A=k.total??0,M=k.dispatched??0,C=k.processing??0,j=k.completed??0,P=k.failed??0,E=M+C>0,U=A>0&&j+P>=A&&!E;if(E){r(B=>{const $=B.find(Z=>Z.id===u)?.dispatchData?.jobs||[],G=(k.dispatched_jobs||[]).map(Z=>({jobId:Z.job_id,sourceName:Z.source_name||e("backgroundDispatch.unknownFile"),printerName:Z.printer_name||e("backgroundDispatch.unknownPrinter"),status:"dispatched"})),W=(k.active_jobs&&k.active_jobs.length>0?k.active_jobs:k.active_job?.job_id?[k.active_job]:[]).filter(Z=>typeof Z.job_id=="number").map(Z=>({jobId:Z.job_id,sourceName:Z.source_name||e("backgroundDispatch.unknownFile"),printerName:Z.printer_name||e("backgroundDispatch.unknownPrinter"),status:"processing",message:Z.message,uploadBytes:Z.upload_bytes,uploadTotalBytes:Z.upload_total_bytes,uploadProgressPct:Z.upload_progress_pct})),X=new Set([...G,...W].map(Z=>Z.jobId)),ae=$.filter(Z=>!X.has(Z.jobId)&&["completed","failed","cancelled"].includes(Z.status));let H=[...G,...W,...ae];if(k.recent_event?.job_id&&k.recent_event?.status){const Z=k.recent_event.status,ve=Z==="cancelled"?"cancelled":Z==="cancelling"?"processing":Z,ce=k.recent_event.source_name||e("backgroundDispatch.unknownFile"),ee=k.recent_event.printer_name||e("backgroundDispatch.unknownPrinter");H=g(H,k.recent_event.job_id,{status:ve,sourceName:ce,printerName:ee,message:k.recent_event.message})}W.forEach(Z=>{H=g(H,Z.jobId,{status:"processing",sourceName:Z.sourceName,printerName:Z.printerName,message:Z.message,uploadBytes:Z.uploadBytes,uploadTotalBytes:Z.uploadTotalBytes,uploadProgressPct:Z.uploadProgressPct})});const K={total:A,dispatched:M,processing:C,completed:j,failed:P,jobs:[...H].sort((Z,ve)=>{const ce=y(Z.status)-y(ve.status);return ce!==0?ce:Z.jobId-ve.jobId})};return B.find(Z=>Z.id===u)?B.map(Z=>Z.id===u?{...Z,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:K}:Z):[...B,{id:u,message:e("backgroundDispatch.startingPrints"),type:"loading",persistent:!0,dispatchData:K}]});return}const L=k.recent_event?.status;if(!E&&L&&["cancelled","failed","completed","idle"].includes(L)&&r(B=>B.filter(D=>D.id!==u)),U){const B=`${j}:${P}`;if(d.current===B)return;d.current=B,r(z=>z.filter(W=>W.id!==u));const D=P>0?e("backgroundDispatch.toast.completeWithFailures",{completed:j,failed:P}):e("backgroundDispatch.toast.completeSuccess",{completed:j}),$=Math.random().toString(36).substr(2,9);r(z=>[...z,{id:$,message:D,type:P>0?"warning":"success"}]);const G=setTimeout(()=>{r(z=>z.filter(W=>W.id!==$)),c.current.delete($)},4e3);c.current.set($,G)}if(k.recent_event?.status==="idle"&&!E&&r(B=>B.filter(D=>D.id!==u)),E||l(new Set),k.dispatched_jobs){const B=new Set(k.dispatched_jobs.map(D=>D.job_id));l(D=>{const $=new Set;return D.forEach(G=>{B.has(G)&&$.add(G)}),$})}};return window.addEventListener("background-dispatch",_),()=>window.removeEventListener("background-dispatch",_)},[e]),i.jsxs(PX.Provider,{value:{showToast:f,showPersistentToast:p,dismissToast:x},children:[t,i.jsx("div",{className:"fixed bottom-4 right-4 z-50 flex flex-col gap-2",children:n.map(g=>i.jsx("div",{className:`rounded-lg border shadow-lg backdrop-blur-sm animate-slide-in ${wge[g.type]} ${g.dispatchData?"w-[420px] p-3":"flex items-center gap-3 px-4 py-3"}`,children:g.dispatchData?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-start justify-between gap-3",children:[i.jsxs("div",{className:"flex items-start gap-2",children:[HB[g.type],i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:e("backgroundDispatch.startingPrints")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:e("backgroundDispatch.progressSummary",{complete:g.dispatchData.completed+g.dispatchData.failed,total:g.dispatchData.total,dispatched:g.dispatchData.dispatched,processing:g.dispatchData.processing})})]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s(y=>!y),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e(a?"backgroundDispatch.expandDetails":"backgroundDispatch.collapseDetails"),children:a?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Pn,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>x(g.id),className:"text-bambu-gray hover:text-white transition-colors","aria-label":e("backgroundDispatch.dismissToast"),children:i.jsx(Lt,{className:"w-4 h-4"})})]})]}),!a&&i.jsx("div",{className:"mt-3 space-y-2 max-h-64 overflow-y-auto pr-1",children:g.dispatchData.jobs.map(y=>{const _={dispatched:15,processing:60,completed:100,failed:100,cancelled:100},N={dispatched:"bg-bambu-gray/60",processing:"bg-bambu-green",completed:"bg-green-500",failed:"bg-red-500",cancelled:"bg-yellow-500"};return i.jsxs("div",{className:"rounded border border-white/10 bg-black/15 p-2",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-xs text-white truncate",title:y.sourceName,children:y.sourceName}),i.jsxs("div",{className:"flex items-center gap-2",children:[(y.status==="dispatched"||y.status==="processing")&&i.jsx("button",{onClick:()=>{v(y.jobId)},disabled:o.has(y.jobId),className:"text-[11px] text-red-300 hover:text-red-200 disabled:opacity-50 disabled:cursor-not-allowed",title:e("backgroundDispatch.cancelDispatchJob"),children:o.has(y.jobId)?e("backgroundDispatch.cancelling"):e("backgroundDispatch.cancel")}),i.jsx("span",{className:"text-[11px] uppercase tracking-wide text-bambu-gray",children:e(`backgroundDispatch.status.${y.status}`)})]})]}),i.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:y.printerName,children:y.printerName}),y.message&&i.jsx("div",{className:"text-[11px] text-bambu-gray truncate",title:y.message,children:y.message}),y.status==="processing"&&typeof y.uploadBytes=="number"&&typeof y.uploadTotalBytes=="number"&&y.uploadTotalBytes>0&&i.jsxs("div",{className:"text-[11px] text-bambu-gray truncate",children:[h(y.uploadBytes)," / ",h(y.uploadTotalBytes),typeof y.uploadProgressPct=="number"?` (${y.uploadProgressPct.toFixed(1)}%)`:""]}),i.jsx("div",{className:"mt-1 h-1.5 w-full rounded bg-white/10 overflow-hidden",children:i.jsx("div",{className:`h-full ${N[y.status]} transition-all duration-300`,style:{width:`${y.status==="processing"&&typeof y.uploadProgressPct=="number"?Math.max(0,Math.min(100,y.uploadProgressPct)):_[y.status]}%`}})})]},y.jobId)})})]}):i.jsxs(i.Fragment,{children:[HB[g.type],i.jsx("span",{className:"text-white text-sm",children:g.message}),i.jsx("button",{onClick:()=>x(g.id),className:"ml-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-4 h-4"})})]})},g.id))})]})}const xv=[{id:"printers",to:"/",icon:gr,labelKey:"nav.printers"},{id:"archives",to:"/archives",icon:js,labelKey:"nav.archives"},{id:"queue",to:"/queue",icon:ra,labelKey:"nav.queue"},{id:"stats",to:"/stats",icon:ohe,labelKey:"nav.stats"},{id:"profiles",to:"/profiles",icon:$b,labelKey:"nav.profiles"},{id:"maintenance",to:"/maintenance",icon:Df,labelKey:"nav.maintenance"},{id:"projects",to:"/projects",icon:gs,labelKey:"nav.projects"},{id:"inventory",to:"/inventory",icon:Yhe,labelKey:"nav.inventory"},{id:"files",to:"/files",icon:Zl,labelKey:"nav.files"},{id:"settings",to:"/settings",icon:f0,labelKey:"nav.settings"}];function _ge(){const t=localStorage.getItem("sidebarOrder");if(t)try{return JSON.parse(t)}catch{return xv.map(e=>e.id)}return xv.map(e=>e.id)}function Nge(t){localStorage.setItem("sidebarOrder",JSON.stringify(t))}function BM(t){return t.startsWith("ext-")}function EX(){return localStorage.getItem("defaultView")||"/"}function Cge(t){localStorage.setItem("defaultView",t)}function kge(){const t=rc(),e=Vc(),{mode:n,toggleMode:r}=tp(),{t:a}=Ot(),s=yge(),{user:o,authEnabled:l,logout:c,hasPermission:u}=Ir(),{showToast:d}=an(),[h,f]=w.useState(!1),[p,x]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[v,g]=w.useState(!1),[y,_]=w.useState(()=>localStorage.getItem("sidebarExpanded")!=="false"),[N,k]=w.useState(!1),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(_ge),[U,L]=w.useState(null),[B,D]=w.useState(null),$=w.useRef(!1),[G,z]=w.useState(()=>sessionStorage.getItem("dismissedUpdateVersion")),[W,X]=w.useState(null),{data:ae}=Je({queryKey:["version"],queryFn:ne.getVersion,staleTime:1/0}),{data:H}=Je({queryKey:["settings"],queryFn:ne.getSettings,staleTime:300*1e3}),{data:K}=Je({queryKey:["updateCheck"],queryFn:ne.checkForUpdates,enabled:H?.check_updates!==!1,staleTime:3600*1e3,refetchInterval:3600*1e3}),{data:te}=Je({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:300*1e3}),{data:Z}=Je({queryKey:["external-links"],queryFn:ne.getExternalLinks}),{data:ve}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs,staleTime:30*1e3}),ce=ve?.some(J=>J.show_in_switchbar)??!1,{data:ee}=Je({queryKey:["debugLogging"],queryFn:Kg.getDebugLoggingState,staleTime:60*1e3,refetchInterval:60*1e3}),{data:je}=Je({queryKey:["developer-mode-warnings"],queryFn:ne.getDeveloperModeWarnings,staleTime:10*1e3,refetchInterval:30*1e3,refetchOnWindowFocus:!0}),{data:he}=Je({queryKey:["queue","pending"],queryFn:()=>ne.getQueue(void 0,"pending"),staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),oe=he?.length??0,{data:_e}=Je({queryKey:["pending-uploads","count"],queryFn:Eg.getCount,staleTime:5*1e3,refetchInterval:5*1e3,refetchOnWindowFocus:!0}),ie=_e?.count??0,[ze,V]=w.useState(null);w.useEffect(()=>{if(!ee?.enabled||!ee.enabled_at){V(null);return}const J=new Date(ee.enabled_at).getTime(),fe=()=>{V(Math.floor((Date.now()-J)/1e3))};fe();const le=setInterval(fe,1e3);return()=>clearInterval(le)},[ee?.enabled,ee?.enabled_at]);const Y=w.useMemo(()=>new Map(xv.map(J=>[J.id,J])),[]),me=w.useMemo(()=>new Map((Z||[]).map(J=>[`ext-${J.id}`,J])),[Z]),Q=(()=>{const J=[],fe=new Set,le=l&&o?.role==="user",Be=te?.spoolman_enabled==="true";for(const Ie of P)le&&Ie==="settings"||Be&&Ie==="inventory"||(Y.has(Ie)||me.has(Ie))&&(J.push(Ie),fe.add(Ie));for(const Ie of xv)le&&Ie.id==="settings"||Be&&Ie.id==="inventory"||fe.has(Ie.id)||(J.push(Ie.id),fe.add(Ie.id));for(const Ie of Z||[]){const Ke=`ext-${Ie.id}`;fe.has(Ke)||(J.push(Ke),fe.add(Ke))}return J})(),se=(J,fe)=>{L(fe),J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/plain",fe)},de=(J,fe)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",D(fe)},Le=()=>{D(null)},Ne=(J,fe)=>{if(J.preventDefault(),U===null||U===fe){L(null),D(null);return}const le=[...Q],Be=le.indexOf(U),Ie=le.indexOf(fe);if(Be===-1||Ie===-1){L(null),D(null);return}le.splice(Be,1),le.splice(Ie,0,U),E(le),Nge(le),L(null),D(null)},be=()=>{L(null),D(null)},O=K?.update_available&&K.latest_version&&K.latest_version!==G,R=()=>{K?.latest_version&&(sessionStorage.setItem("dismissedUpdateVersion",K.latest_version),z(K.latest_version))};w.useEffect(()=>{if(!$.current&&e.pathname==="/"){const J=EX();J!=="/"&&($.current=!0,t(J,{replace:!0}))}},[e.pathname,t]),w.useEffect(()=>{localStorage.setItem("sidebarExpanded",String(y))},[y]),w.useEffect(()=>{s&&k(!1)},[e.pathname,s]),w.useEffect(()=>{const J=fe=>{if(!u("printers:control"))return;const le=fe.detail;X({printer_id:le.printer_id,printer_name:le.printer_name,message:le.message})};return window.addEventListener("plate-not-empty",J),()=>window.removeEventListener("plate-not-empty",J)},[u]);const q=w.useCallback(J=>{const fe=J.target;if(!(fe.tagName==="INPUT"||fe.tagName==="TEXTAREA"||fe.isContentEditable)&&!J.metaKey&&!J.ctrlKey&&!J.altKey){const le=parseInt(J.key);if(le>=1&&le<=Q.length&&le<=9){const Be=Q[le-1];if(J.preventDefault(),BM(Be)){const Ie=me.get(Be);if(Ie?.open_in_new_tab)window.open(Ie.url,"_blank","noopener,noreferrer");else{const Ke=Be.replace("ext-","");t(`/external/${Ke}`)}}else{const Ie=Y.get(Be);Ie&&t(Ie.to)}return}switch(J.key){case"?":J.preventDefault(),M(!0);break;case"Escape":M(!1);break}}},[t,Q,Y,me]);return w.useEffect(()=>(document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)),[q]),i.jsxs("div",{className:"flex min-h-screen",children:[s&&i.jsxs("header",{className:"fixed top-0 left-0 right-0 z-40 h-14 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary flex items-center px-4",children:[i.jsx("button",{onClick:()=>k(!0),className:"p-2 -ml-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors","aria-label":"Open menu",children:i.jsx(wfe,{className:"w-6 h-6 text-white"})}),i.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-8 ml-3"})]}),s&&N&&i.jsx("div",{className:"fixed inset-0 bg-black/60 z-40 transition-opacity",onClick:()=>k(!1)}),i.jsxs("aside",{className:`bg-bambu-dark-secondary border-r border-bambu-dark-tertiary flex flex-col transition-all duration-300 ${s?`fixed inset-y-0 left-0 z-50 w-72 transform ${N?"translate-x-0":"-translate-x-full"}`:`fixed inset-y-0 left-0 z-30 ${y?"w-64":"w-16"}`}`,children:[i.jsx("div",{className:`border-b border-bambu-dark-tertiary flex items-center justify-center ${s||y?"p-4":"p-2"}`,children:i.jsx("img",{src:n==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:s||y?"h-16 w-auto":"h-8 w-8 object-cover object-left"})}),i.jsx("nav",{className:"flex-1 p-2",children:i.jsx("ul",{className:"space-y-2",children:Q.map(J=>{if(BM(J)){const le=me.get(J);if(!le)return null;const Be=le.custom_icon?null:tk(le.icon);return i.jsx("li",{draggable:!0,onDragStart:Ie=>se(Ie,J),onDragOver:Ie=>de(Ie,J),onDragLeave:Le,onDrop:Ie=>Ne(Ie,J),onDragEnd:be,className:`relative ${U===J?"opacity-50":""} ${B===J&&U!==J?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:le.open_in_new_tab?i.jsxs("a",{href:le.url,target:"_blank",rel:"noopener noreferrer",className:`flex items-center ${s||y?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white`,title:!s&&!y?le.name:void 0,children:[y&&!s&&i.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),le.custom_icon?i.jsx("img",{src:`/api/v1/external-links/${le.id}/icon`,alt:"",className:"w-5 h-5 flex-shrink-0"}):Be&&i.jsx(Be,{className:"w-5 h-5 flex-shrink-0"}),(s||y)&&i.jsx("span",{children:le.name})]}):i.jsxs(Zm,{to:`/external/${le.id}`,className:({isActive:Ie})=>`flex items-center ${s||y?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${Ie?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!y?le.name:void 0,children:[y&&!s&&i.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),le.custom_icon?i.jsx("img",{src:`/api/v1/external-links/${le.id}/icon`,alt:"",className:"w-5 h-5 flex-shrink-0"}):Be&&i.jsx(Be,{className:"w-5 h-5 flex-shrink-0"}),(s||y)&&i.jsx("span",{children:le.name})]})},J)}else{const le=Y.get(J);if(!le)return null;const{to:Be,icon:Ie,labelKey:Ke}=le,Oe=J==="queue"&&oe>0,pe=J==="archives"&&ie>0,xe=Oe?oe:pe?ie:0,ke=Oe||pe;return i.jsx("li",{draggable:!0,onDragStart:ge=>se(ge,J),onDragOver:ge=>de(ge,J),onDragLeave:Le,onDrop:ge=>Ne(ge,J),onDragEnd:be,className:`relative ${U===J?"opacity-50":""} ${B===J&&U!==J?"before:absolute before:left-0 before:right-0 before:top-0 before:h-0.5 before:bg-bambu-green":""}`,children:i.jsxs(Zm,{to:Be,className:({isActive:ge})=>`flex items-center ${s||y?"gap-3 px-4":"justify-center px-2"} py-3 rounded-lg transition-colors group ${ge?"bg-bambu-green text-white":"text-bambu-gray-light hover:bg-bambu-dark-tertiary hover:text-white"}`,title:!s&&!y?a(Ke):void 0,children:[y&&!s&&i.jsx(Eh,{className:"w-4 h-4 flex-shrink-0 opacity-0 group-hover:opacity-50 cursor-grab active:cursor-grabbing -ml-1"}),i.jsxs("div",{className:"relative",children:[i.jsx(Ie,{className:"w-5 h-5 flex-shrink-0"}),ke&&i.jsx("span",{className:`absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 flex items-center justify-center text-[10px] font-bold rounded-full ${pe?"bg-blue-500 text-white":"bg-yellow-500 text-black"}`,children:xe>99?"99+":xe})]}),(s||y)&&i.jsx("span",{children:a(Ke)})]})},J)}})})}),!s&&i.jsx("button",{onClick:()=>_(!y),className:"p-2 mx-2 mb-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white flex items-center justify-center",title:a(y?"nav.collapseSidebar":"nav.expandSidebar"),children:y?i.jsx(Xl,{className:"w-5 h-5"}):i.jsx(pi,{className:"w-5 h-5"})}),i.jsx("div",{className:"p-2 border-t border-bambu-dark-tertiary",children:s||y?i.jsxs("div",{className:"flex flex-col gap-2 px-2",children:[i.jsxs("div",{className:"flex items-center justify-center gap-1",children:[ce&&i.jsxs("div",{className:"relative",children:[i.jsx("button",{onMouseEnter:()=>j(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${C?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:a("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:i.jsx(fl,{className:"w-5 h-5"})}),C&&i.jsx(UB,{onClose:()=>j(!1)})]}),u("system:read")?i.jsx(Zm,{to:"/system",className:({isActive:J})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${J?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:a("nav.system"),children:i.jsx(Zs,{className:"w-5 h-5"})}):i.jsx("span",{className:"p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed",title:"You do not have permission to view system information",children:i.jsx(Zs,{className:"w-5 h-5"})}),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.viewOnGithub"),children:i.jsx(r3,{className:"w-5 h-5"})}),i.jsx("button",{onClick:()=>M(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.keyboardShortcuts"),children:i.jsx(a3,{className:"w-5 h-5"})}),i.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?i.jsx(IB,{className:"w-5 h-5"}):i.jsx(N1,{className:"w-5 h-5"})}),l&&o&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>f(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("changePassword.title"),children:i.jsx(nl,{className:"w-5 h-5"})}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.logout",{defaultValue:"Logout"}),children:i.jsx(s3,{className:"w-5 h-5"})})]})]}),i.jsxs("div",{className:"flex items-center justify-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:["v",ae?.version||"..."]}),K?.update_available&&i.jsxs("button",{onClick:()=>t("/settings"),className:"flex items-center gap-1 text-xs text-bambu-green hover:text-bambu-green/80 transition-colors",title:a("nav.updateAvailable",{version:K.latest_version}),children:[i.jsx(zM,{className:"w-4 h-4"}),i.jsx("span",{children:a("nav.update")})]})]})]}):i.jsxs("div",{className:"flex flex-col items-center gap-1",children:[K?.update_available&&i.jsx("button",{onClick:()=>t("/settings"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-green hover:text-bambu-green/80",title:a("nav.updateAvailable",{version:K.latest_version}),children:i.jsx(zM,{className:"w-5 h-5"})}),ce&&i.jsxs("div",{className:"relative",children:[i.jsx("button",{onMouseEnter:()=>j(!0),className:`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${C?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:a("nav.smartSwitches",{defaultValue:"Smart Switches"}),children:i.jsx(fl,{className:"w-5 h-5"})}),C&&i.jsx(UB,{onClose:()=>j(!1)})]}),u("system:read")?i.jsx(Zm,{to:"/system",className:({isActive:J})=>`p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors ${J?"text-bambu-green":"text-bambu-gray-light hover:text-white"}`,title:a("nav.system"),children:i.jsx(Zs,{className:"w-5 h-5"})}):i.jsx("span",{className:"p-2 rounded-lg text-bambu-gray/50 cursor-not-allowed",title:"You do not have permission to view system information",children:i.jsx(Zs,{className:"w-5 h-5"})}),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.viewOnGithub"),children:i.jsx(r3,{className:"w-5 h-5"})}),i.jsx("button",{onClick:()=>M(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.keyboardShortcuts"),children:i.jsx(a3,{className:"w-5 h-5"})}),i.jsx("button",{onClick:r,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a(n==="dark"?"nav.switchToLight":"nav.switchToDark"),children:n==="dark"?i.jsx(IB,{className:"w-5 h-5"}):i.jsx(N1,{className:"w-5 h-5"})}),l&&o&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>f(!0),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("changePassword.title"),children:i.jsx(nl,{className:"w-5 h-5"})}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray-light hover:text-white",title:a("nav.logout",{defaultValue:"Logout"}),children:i.jsx(s3,{className:"w-5 h-5"})})]})]})})]}),i.jsxs("main",{className:`flex-1 bg-bambu-dark overflow-auto transition-all duration-300 ${s?"mt-14":y?"ml-64":"ml-16"}`,children:[ee?.enabled&&i.jsx("div",{className:"bg-amber-500/20 border-b border-amber-500/30 px-4 py-2 flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(HC,{className:"w-4 h-4 text-amber-500 animate-pulse"}),i.jsxs("span",{className:"text-amber-200",children:[a("support.debugLoggingActive",{defaultValue:"Debug logging is active"}),ze!==null&&i.jsxs("span",{className:"text-amber-300/70 ml-2",children:["(",Math.floor(ze/60),"m ",ze%60,"s)"]})]}),i.jsx("button",{onClick:()=>t("/system"),className:"text-amber-400 hover:text-amber-300 font-medium underline ml-2",children:a("support.manageLogs",{defaultValue:"Manage"})})]})}),je&&je.length>0&&i.jsx("div",{className:"bg-orange-500/20 border-b border-orange-500/30 px-4 py-2 flex items-center justify-between",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(cpe,{className:"w-4 h-4 text-orange-500"}),i.jsx("span",{className:"text-orange-200",children:a("printers.developerModeWarning",{names:je.map(J=>J.name).join(", "),defaultValue:`Developer LAN mode is not enabled on: ${je.map(J=>J.name).join(", ")}. Some features may not work.`})}),i.jsx("a",{href:"https://wiki.bambulab.com/en/knowledge-sharing/enable-developer-mode",target:"_blank",rel:"noopener noreferrer",className:"text-orange-400 hover:text-orange-300 font-medium underline ml-2",children:a("printers.howToEnable",{defaultValue:"How to enable"})})]})}),O&&i.jsxs("div",{className:"bg-bambu-green/20 border-b border-bambu-green/30 px-4 py-2 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(zM,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{children:a("nav.updateAvailableBanner",{version:K?.latest_version,defaultValue:`Version ${K?.latest_version} is available!`})}),i.jsx("button",{onClick:()=>t("/settings"),className:"text-bambu-green hover:text-bambu-green/80 font-medium underline",children:a("nav.viewUpdate",{defaultValue:"View update"})})]}),i.jsx("button",{onClick:R,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:a("common.dismiss",{defaultValue:"Dismiss"}),children:i.jsx(Lt,{className:"w-4 h-4"})})]}),i.jsx(HK,{})]}),A&&i.jsx(gge,{onClose:()=>M(!1),sidebarItems:Q.map(J=>{if(BM(J)){const fe=me.get(J);return fe?{type:"external",label:fe.name}:null}else{const fe=Y.get(J);return fe?{type:"nav",label:fe.labelKey,labelKey:fe.labelKey}:null}}).filter(Boolean)}),W&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[100] p-4",children:i.jsx("div",{className:"bg-bambu-dark-secondary border-2 border-yellow-500 rounded-xl shadow-2xl max-w-md w-full animate-in fade-in zoom-in duration-200",children:i.jsxs("div",{className:"p-6 text-center",children:[i.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-10 h-10 text-yellow-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),i.jsx("h2",{className:"text-xl font-bold text-yellow-400 mb-2",children:a("plateAlert.title")}),i.jsx("p",{className:"text-lg text-white mb-2",children:W.printer_name}),i.jsx("p",{className:"text-bambu-gray mb-6",children:a("plateAlert.message")}),i.jsx("button",{onClick:()=>X(null),className:"w-full py-3 px-6 bg-yellow-500 hover:bg-yellow-600 text-black font-semibold rounded-lg transition-colors",children:a("plateAlert.understand")})]})})}),h&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{f(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsxs(wt,{className:"w-full max-w-md",onClick:J=>J.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("changePassword.title")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{f(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("changePassword.currentPassword")}),i.jsx("input",{type:"password",value:p.currentPassword,onChange:J=>x({...p,currentPassword:J.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("changePassword.currentPasswordPlaceholder"),autoComplete:"current-password"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("changePassword.newPassword")}),i.jsx("input",{type:"password",value:p.newPassword,onChange:J=>x({...p,newPassword:J.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("changePassword.newPasswordPlaceholder"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("changePassword.confirmPassword")}),i.jsx("input",{type:"password",value:p.confirmPassword,onChange:J=>x({...p,confirmPassword:J.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${p.confirmPassword&&p.newPassword!==p.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("changePassword.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),p.confirmPassword&&p.newPassword!==p.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("changePassword.passwordsDoNotMatch")})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{f(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})},children:a("common.cancel")}),i.jsx(Ce,{onClick:async()=>{if(p.newPassword!==p.confirmPassword){d(a("changePassword.passwordsDoNotMatch"),"error");return}if(p.newPassword.length<6){d(a("changePassword.passwordTooShort"),"error");return}g(!0);try{await ne.changePassword(p.currentPassword,p.newPassword),d(a("changePassword.success"),"success"),f(!1),x({currentPassword:"",newPassword:"",confirmPassword:""})}catch(J){const fe=J instanceof Error?J.message:a("changePassword.failed");d(fe,"error")}finally{g(!1)}},disabled:v||!p.currentPassword||!p.newPassword||p.newPassword!==p.confirmPassword||p.newPassword.length<6,children:v?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("changePassword.changing")]}):i.jsxs(i.Fragment,{children:[i.jsx(nl,{className:"w-4 h-4"}),a("changePassword.title")]})})]})]})]})})]})}function Age(t="system"){switch(t){case"us":return"MM/DD/YYYY";case"eu":return"DD/MM/YYYY";case"iso":return"YYYY-MM-DD";default:{const n=new Date(2e3,11,31).toLocaleDateString();return n.startsWith("12")?"MM/DD/YYYY":n.startsWith("31")?"DD/MM/YYYY":"YYYY-MM-DD"}}}function Tge(t="system"){switch(t){case"12h":return"HH:MM AM/PM";case"24h":return"HH:MM";default:{const n=new Date(2e3,0,1,14,30).toLocaleTimeString();return n.includes("PM")||n.includes("AM")?"HH:MM AM/PM":"HH:MM"}}}function u3(t,e="system"){const n=String(t.getDate()).padStart(2,"0"),r=String(t.getMonth()+1).padStart(2,"0"),a=t.getFullYear();switch(e){case"us":return`${r}/${n}/${a}`;case"eu":return`${n}/${r}/${a}`;case"iso":return`${a}-${r}-${n}`;default:return t.toLocaleDateString()}}function $B(t,e="system"){const n=t.getHours(),r=String(t.getMinutes()).padStart(2,"0");switch(e){case"12h":{const a=n%12||12,s=n<12?"AM":"PM";return`${a}:${r} ${s}`}case"24h":return`${String(n).padStart(2,"0")}:${r}`;default:return t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}}function aS(t){for(const e of["/",".","-"]){const n=t.split(e);if(n.length===3)return n}return null}function Mge(t,e="system"){if(!t)return null;let n,r,a;try{switch(e){case"us":{const s=aS(t);if(!s)return null;r=parseInt(s[0],10),n=parseInt(s[1],10),a=parseInt(s[2],10);break}case"eu":{const s=aS(t);if(!s)return null;n=parseInt(s[0],10),r=parseInt(s[1],10),a=parseInt(s[2],10);break}case"iso":{const s=aS(t);if(!s)return null;a=parseInt(s[0],10),r=parseInt(s[1],10),n=parseInt(s[2],10);break}default:{const o=new Date(2e3,11,31).toLocaleDateString(),l=aS(t);if(l){o.startsWith("12")?(r=parseInt(l[0],10),n=parseInt(l[1],10),a=parseInt(l[2],10)):o.startsWith("31")?(n=parseInt(l[0],10),r=parseInt(l[1],10),a=parseInt(l[2],10)):(a=parseInt(l[0],10),r=parseInt(l[1],10),n=parseInt(l[2],10));break}return null}}return isNaN(n)||isNaN(r)||isNaN(a)||r<1||r>12||n<1||n>31||a<1900||a>2100?null:new Date(a,r-1,n)}catch{return null}}function Pge(t){if(!t)return null;try{const e=t.trim().toUpperCase(),n=e.match(/^(\d{1,2}):(\d{2})\s*(AM|PM)?$/i);if(n){let a=parseInt(n[1],10);const s=parseInt(n[2],10),o=n[3]?.toUpperCase();return o==="PM"&&a<12&&(a+=12),o==="AM"&&a===12&&(a=0),a<0||a>23||s<0||s>59?null:{hours:a,minutes:s}}const r=e.match(/^(\d{1,2}):(\d{2})$/);if(r){const a=parseInt(r[1],10),s=parseInt(r[2],10);return a<0||a>23||s<0||s>59?null:{hours:a,minutes:s}}return null}catch{return null}}function d3(t){const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),a=String(t.getHours()).padStart(2,"0"),s=String(t.getMinutes()).padStart(2,"0");return`${e}-${n}-${r}T${a}:${s}`}function Vy(t,e="system"){return e==="12h"?t.hour12=!0:e==="24h"&&(t.hour12=!1),t}function hi(t){return t?t.endsWith("Z")||/[+-]\d{2}:\d{2}$/.test(t)?new Date(t):new Date(t+"Z"):null}function mb(t,e){const n=hi(t);if(!n)return"";const r={year:"numeric",month:"short",day:"numeric"};return n.toLocaleDateString(void 0,e??r)}function Rf(t,e="system",n){const r=hi(t);if(!r)return"";const s=Vy(n??{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},e);return r.toLocaleString(void 0,s)}function Ege(t,e="system",n){const a=Vy({...{hour:"2-digit",minute:"2-digit"},...n},e);return t.toLocaleTimeString([],a)}function DF(t,e="system",n){const r=new Date,a=new Date(r.getTime()+t*60*1e3),s=new Date;s.setHours(0,0,0,0);const o=new Date(a);o.setHours(0,0,0,0);const l={hour:"2-digit",minute:"2-digit"};e==="12h"?l.hour12=!0:e==="24h"&&(l.hour12=!1);const c=a.toLocaleTimeString([],l),u=Math.floor((o.getTime()-s.getTime())/864e5);return u===0?c:u===1?`${n?.("common.tomorrow")??"Tomorrow"} ${c}`:`${a.toLocaleDateString([],{weekday:"short"})} ${c}`}function Qs(t){if(t==null||t<0)return"--";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function yv(t,e="system",n){if(!t)return n?.("time.unknown")??"-";const r=hi(t);if(!r)return n?.("time.unknown")??"-";const a=new Date,s=r.getTime()-a.getTime(),o=s<0,l=Math.abs(s),c=Math.floor(l/6e4),u=Math.floor(l/36e5),d=Math.floor(l/864e5);return c<1?o?n?.("time.justNow")??"Just now":n?.("time.now")??"Now":u<1?o?n?.("time.minsAgo",{count:c})??`${c}m ago`:n?.("time.inMins",{count:c})??`in ${c}m`:d<1?o?n?.("time.hoursAgo",{count:u})??`${u}h ago`:n?.("time.inHours",{count:u})??`in ${u}h`:d<7?o?n?.("time.daysAgo",{count:d})??`${d}d ago`:n?.("time.inDays",{count:d})??`in ${d}d`:Rf(t,e)}const RF="181",Xg={ROTATE:0,DOLLY:1,PAN:2},Ig={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},jge=0,VB=1,Dge=2,jX=1,Rge=2,Tu=3,qh=0,to=1,_c=2,Vu=0,Yg=1,qB=2,GB=3,WB=4,Fge=5,Gm=100,Lge=101,Oge=102,Ige=103,zge=104,Uge=200,Bge=201,Hge=202,$ge=203,h3=204,m3=205,Vge=206,qge=207,Gge=208,Wge=209,Kge=210,Xge=211,Yge=212,Qge=213,Zge=214,f3=0,p3=1,g3=2,fb=3,b3=4,x3=5,y3=6,v3=7,FF=0,Jge=1,ebe=2,Dh=0,tbe=1,nbe=2,rbe=3,abe=4,ibe=5,sbe=6,obe=7,DX=300,pb=301,gb=302,w3=303,S3=304,nk=306,_3=1e3,Ou=1001,N3=1002,Eo=1003,lbe=1004,iS=1005,hl=1006,HM=1007,tf=1008,Lc=1009,RX=1010,FX=1011,vv=1012,LF=1013,Ff=1014,Iu=1015,Gb=1016,OF=1017,IF=1018,wv=1020,LX=35902,OX=35899,IX=1021,zX=1022,ql=1023,Sv=1026,_v=1027,UX=1028,zF=1029,UF=1030,BF=1031,HF=1033,V_=33776,q_=33777,G_=33778,W_=33779,C3=35840,k3=35841,A3=35842,T3=35843,M3=36196,P3=37492,E3=37496,j3=37808,D3=37809,R3=37810,F3=37811,L3=37812,O3=37813,I3=37814,z3=37815,U3=37816,B3=37817,H3=37818,$3=37819,V3=37820,q3=37821,G3=36492,W3=36494,K3=36495,X3=36283,Y3=36284,Q3=36285,Z3=36286,cbe=3200,ube=3201,BX=0,dbe=1,fh="",ko="srgb",bb="srgb-linear",A1="linear",Dr="srgb",Hp=7680,KB=519,hbe=512,mbe=513,fbe=514,HX=515,pbe=516,gbe=517,bbe=518,xbe=519,XB=35044,YB="300 es",kc=2e3,T1=2001;function $X(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function M1(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function ybe(){const t=M1("canvas");return t.style.display="block",t}const QB={};function ZB(...t){const e="THREE."+t.shift();console.log(e,...t)}function vn(...t){const e="THREE."+t.shift();console.warn(e,...t)}function Ua(...t){const e="THREE."+t.shift();console.error(e,...t)}function Nv(...t){const e=t.join(" ");e in QB||(QB[e]=!0,vn(...t))}function vbe(t,e,n){return new Promise(function(r,a){function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:a();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}}setTimeout(s,n)})}let np=class{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(n)===-1&&r[e].push(n)}hasEventListener(e,n){const r=this._listeners;return r===void 0?!1:r[e]!==void 0&&r[e].indexOf(n)!==-1}removeEventListener(e,n){const r=this._listeners;if(r===void 0)return;const a=r[e];if(a!==void 0){const s=a.indexOf(n);s!==-1&&a.splice(s,1)}}dispatchEvent(e){const n=this._listeners;if(n===void 0)return;const r=n[e.type];if(r!==void 0){e.target=this;const a=r.slice(0);for(let s=0,o=a.length;s<o;s++)a[s].call(this,e);e.target=null}}};const is=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],K_=Math.PI/180,J3=180/Math.PI;function p0(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(is[t&255]+is[t>>8&255]+is[t>>16&255]+is[t>>24&255]+"-"+is[e&255]+is[e>>8&255]+"-"+is[e>>16&15|64]+is[e>>24&255]+"-"+is[n&63|128]+is[n>>8&255]+"-"+is[n>>16&255]+is[n>>24&255]+is[r&255]+is[r>>8&255]+is[r>>16&255]+is[r>>24&255]).toLowerCase()}function Yn(t,e,n){return Math.max(e,Math.min(n,t))}function wbe(t,e){return(t%e+e)%e}function $M(t,e,n){return(1-n)*t+n*e}function ey(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Gs(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}const Sbe={DEG2RAD:K_};let Un=class VX{constructor(e=0,n=0){VX.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,a=e.elements;return this.x=a[0]*n+a[3]*r+a[6],this.y=a[1]*n+a[4]*r+a[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Yn(this.x,e.x,n.x),this.y=Yn(this.y,e.y,n.y),this}clampScalar(e,n){return this.x=Yn(this.x,e,n),this.y=Yn(this.y,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Yn(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Yn(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),a=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*a+e.x,this.y=s*a+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Lf=class{constructor(e=0,n=0,r=0,a=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=a}static slerpFlat(e,n,r,a,s,o,l){let c=r[a+0],u=r[a+1],d=r[a+2],h=r[a+3],f=s[o+0],p=s[o+1],x=s[o+2],v=s[o+3];if(l<=0){e[n+0]=c,e[n+1]=u,e[n+2]=d,e[n+3]=h;return}if(l>=1){e[n+0]=f,e[n+1]=p,e[n+2]=x,e[n+3]=v;return}if(h!==v||c!==f||u!==p||d!==x){let g=c*f+u*p+d*x+h*v;g<0&&(f=-f,p=-p,x=-x,v=-v,g=-g);let y=1-l;if(g<.9995){const _=Math.acos(g),N=Math.sin(_);y=Math.sin(y*_)/N,l=Math.sin(l*_)/N,c=c*y+f*l,u=u*y+p*l,d=d*y+x*l,h=h*y+v*l}else{c=c*y+f*l,u=u*y+p*l,d=d*y+x*l,h=h*y+v*l;const _=1/Math.sqrt(c*c+u*u+d*d+h*h);c*=_,u*=_,d*=_,h*=_}}e[n]=c,e[n+1]=u,e[n+2]=d,e[n+3]=h}static multiplyQuaternionsFlat(e,n,r,a,s,o){const l=r[a],c=r[a+1],u=r[a+2],d=r[a+3],h=s[o],f=s[o+1],p=s[o+2],x=s[o+3];return e[n]=l*x+d*h+c*p-u*f,e[n+1]=c*x+d*f+u*h-l*p,e[n+2]=u*x+d*p+l*f-c*h,e[n+3]=d*x-l*h-c*f-u*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,a){return this._x=e,this._y=n,this._z=r,this._w=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n=!0){const r=e._x,a=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,u=l(r/2),d=l(a/2),h=l(s/2),f=c(r/2),p=c(a/2),x=c(s/2);switch(o){case"XYZ":this._x=f*d*h+u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h-f*p*x;break;case"YXZ":this._x=f*d*h+u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h+f*p*x;break;case"ZXY":this._x=f*d*h-u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h-f*p*x;break;case"ZYX":this._x=f*d*h-u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h+f*p*x;break;case"YZX":this._x=f*d*h+u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h-f*p*x;break;case"XZY":this._x=f*d*h-u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h+f*p*x;break;default:vn("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,a=Math.sin(r);return this._x=e.x*a,this._y=e.y*a,this._z=e.z*a,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],a=n[4],s=n[8],o=n[1],l=n[5],c=n[9],u=n[2],d=n[6],h=n[10],f=r+l+h;if(f>0){const p=.5/Math.sqrt(f+1);this._w=.25/p,this._x=(d-c)*p,this._y=(s-u)*p,this._z=(o-a)*p}else if(r>l&&r>h){const p=2*Math.sqrt(1+r-l-h);this._w=(d-c)/p,this._x=.25*p,this._y=(a+o)/p,this._z=(s+u)/p}else if(l>h){const p=2*Math.sqrt(1+l-r-h);this._w=(s-u)/p,this._x=(a+o)/p,this._y=.25*p,this._z=(c+d)/p}else{const p=2*Math.sqrt(1+h-r-l);this._w=(o-a)/p,this._x=(s+u)/p,this._y=(c+d)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return r<1e-8?(r=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Yn(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const a=Math.min(1,n/r);return this.slerp(e,a),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,a=e._y,s=e._z,o=e._w,l=n._x,c=n._y,u=n._z,d=n._w;return this._x=r*d+o*l+a*u-s*c,this._y=a*d+o*c+s*l-r*u,this._z=s*d+o*u+r*c-a*l,this._w=o*d-r*l-a*c-s*u,this._onChangeCallback(),this}slerp(e,n){if(n<=0)return this;if(n>=1)return this.copy(e);let r=e._x,a=e._y,s=e._z,o=e._w,l=this.dot(e);l<0&&(r=-r,a=-a,s=-s,o=-o,l=-l);let c=1-n;if(l<.9995){const u=Math.acos(l),d=Math.sin(u);c=Math.sin(c*u)/d,n=Math.sin(n*u)/d,this._x=this._x*c+r*n,this._y=this._y*c+a*n,this._z=this._z*c+s*n,this._w=this._w*c+o*n,this._onChangeCallback()}else this._x=this._x*c+r*n,this._y=this._y*c+a*n,this._z=this._z*c+s*n,this._w=this._w*c+o*n,this.normalize();return this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=2*Math.PI*Math.random(),n=2*Math.PI*Math.random(),r=Math.random(),a=Math.sqrt(1-r),s=Math.sqrt(r);return this.set(a*Math.sin(e),a*Math.cos(e),s*Math.sin(n),s*Math.cos(n))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},ft=class qX{constructor(e=0,n=0,r=0){qX.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(JB.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(JB.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,a=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*a,this.y=s[1]*n+s[4]*r+s[7]*a,this.z=s[2]*n+s[5]*r+s[8]*a,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,a=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*a+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*a+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*a+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*a+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,a=this.z,s=e.x,o=e.y,l=e.z,c=e.w,u=2*(o*a-l*r),d=2*(l*n-s*a),h=2*(s*r-o*n);return this.x=n+c*u+o*h-l*d,this.y=r+c*d+l*u-s*h,this.z=a+c*h+s*d-o*u,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,a=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*a,this.y=s[1]*n+s[5]*r+s[9]*a,this.z=s[2]*n+s[6]*r+s[10]*a,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Yn(this.x,e.x,n.x),this.y=Yn(this.y,e.y,n.y),this.z=Yn(this.z,e.z,n.z),this}clampScalar(e,n){return this.x=Yn(this.x,e,n),this.y=Yn(this.y,e,n),this.z=Yn(this.z,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Yn(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,a=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=a*c-s*l,this.y=s*o-r*c,this.z=r*l-a*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return VM.copy(this).projectOnVector(e),this.sub(VM)}reflect(e){return this.sub(VM.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Yn(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,a=this.z-e.z;return n*n+r*r+a*a}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const a=Math.sin(n)*e;return this.x=a*Math.sin(r),this.y=Math.cos(n)*e,this.z=a*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),a=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=a,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,n=Math.random()*2-1,r=Math.sqrt(1-n*n);return this.x=r*Math.cos(e),this.y=n,this.z=r*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};const VM=new ft,JB=new Lf;let Hn=class GX{constructor(e,n,r,a,s,o,l,c,u){GX.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,a,s,o,l,c,u)}set(e,n,r,a,s,o,l,c,u){const d=this.elements;return d[0]=e,d[1]=a,d[2]=l,d[3]=n,d[4]=s,d[5]=c,d[6]=r,d[7]=o,d[8]=u,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,a=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],u=r[1],d=r[4],h=r[7],f=r[2],p=r[5],x=r[8],v=a[0],g=a[3],y=a[6],_=a[1],N=a[4],k=a[7],A=a[2],M=a[5],C=a[8];return s[0]=o*v+l*_+c*A,s[3]=o*g+l*N+c*M,s[6]=o*y+l*k+c*C,s[1]=u*v+d*_+h*A,s[4]=u*g+d*N+h*M,s[7]=u*y+d*k+h*C,s[2]=f*v+p*_+x*A,s[5]=f*g+p*N+x*M,s[8]=f*y+p*k+x*C,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8];return n*o*d-n*l*u-r*s*d+r*l*c+a*s*u-a*o*c}invert(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=d*o-l*u,f=l*c-d*s,p=u*s-o*c,x=n*h+r*f+a*p;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/x;return e[0]=h*v,e[1]=(a*u-d*r)*v,e[2]=(l*r-a*o)*v,e[3]=f*v,e[4]=(d*n-a*c)*v,e[5]=(a*s-l*n)*v,e[6]=p*v,e[7]=(r*c-u*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,a,s,o,l){const c=Math.cos(s),u=Math.sin(s);return this.set(r*c,r*u,-r*(c*o+u*l)+o+e,-a*u,a*c,-a*(-u*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(qM.makeScale(e,n)),this}rotate(e){return this.premultiply(qM.makeRotation(-e)),this}translate(e,n){return this.premultiply(qM.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let a=0;a<9;a++)if(n[a]!==r[a])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}};const qM=new Hn,e8=new Hn().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),t8=new Hn().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function _be(){const t={enabled:!0,workingColorSpace:bb,spaces:{},convert:function(a,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Dr&&(a.r=qu(a.r),a.g=qu(a.g),a.b=qu(a.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(a.applyMatrix3(this.spaces[s].toXYZ),a.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Dr&&(a.r=Qg(a.r),a.g=Qg(a.g),a.b=Qg(a.b))),a},workingToColorSpace:function(a,s){return this.convert(a,this.workingColorSpace,s)},colorSpaceToWorking:function(a,s){return this.convert(a,s,this.workingColorSpace)},getPrimaries:function(a){return this.spaces[a].primaries},getTransfer:function(a){return a===fh?A1:this.spaces[a].transfer},getToneMappingMode:function(a){return this.spaces[a].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(a,s=this.workingColorSpace){return a.fromArray(this.spaces[s].luminanceCoefficients)},define:function(a){Object.assign(this.spaces,a)},_getMatrix:function(a,s,o){return a.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(a){return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(a=this.workingColorSpace){return this.spaces[a].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(a,s){return Nv("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),t.workingToColorSpace(a,s)},toWorkingColorSpace:function(a,s){return Nv("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),t.colorSpaceToWorking(a,s)}},e=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return t.define({[bb]:{primaries:e,whitePoint:r,transfer:A1,toXYZ:e8,fromXYZ:t8,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:ko},outputColorSpaceConfig:{drawingBufferColorSpace:ko}},[ko]:{primaries:e,whitePoint:r,transfer:Dr,toXYZ:e8,fromXYZ:t8,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:ko}}}),t}const cr=_be();function qu(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function Qg(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let $p,Nbe=class{static getDataURL(e,n="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let r;if(e instanceof HTMLCanvasElement)r=e;else{$p===void 0&&($p=M1("canvas")),$p.width=e.width,$p.height=e.height;const a=$p.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,e.width,e.height),r=$p}return r.toDataURL(n)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=M1("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const a=r.getImageData(0,0,e.width,e.height),s=a.data;for(let o=0;o<s.length;o++)s[o]=qu(s[o]/255)*255;return r.putImageData(a,0,0),n}else if(e.data){const n=e.data.slice(0);for(let r=0;r<n.length;r++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[r]=Math.floor(qu(n[r]/255)*255):n[r]=qu(n[r]);return{data:n,width:e.width,height:e.height}}else return vn("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},Cbe=0,$F=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Cbe++}),this.uuid=p0(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const n=this.data;return typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?e.set(n.videoWidth,n.videoHeight,0):n instanceof VideoFrame?e.set(n.displayHeight,n.displayWidth,0):n!==null?e.set(n.width,n.height,n.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const r={uuid:this.uuid,url:""},a=this.data;if(a!==null){let s;if(Array.isArray(a)){s=[];for(let o=0,l=a.length;o<l;o++)a[o].isDataTexture?s.push(GM(a[o].image)):s.push(GM(a[o]))}else s=GM(a);r.url=s}return n||(e.images[this.uuid]=r),r}};function GM(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?Nbe.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(vn("Texture: Unable to serialize Texture."),{})}let kbe=0;const WM=new ft;let ac=class X_ extends np{constructor(e=X_.DEFAULT_IMAGE,n=X_.DEFAULT_MAPPING,r=Ou,a=Ou,s=hl,o=tf,l=ql,c=Lc,u=X_.DEFAULT_ANISOTROPY,d=fh){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:kbe++}),this.uuid=p0(),this.name="",this.source=new $F(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=a,this.magFilter=s,this.minFilter=o,this.anisotropy=u,this.format=l,this.internalFormat=null,this.type=c,this.offset=new Un(0,0),this.repeat=new Un(1,1),this.center=new Un(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Hn,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(WM).x}get height(){return this.source.getSize(WM).y}get depth(){return this.source.getSize(WM).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const n in e){const r=e[n];if(r===void 0){vn(`Texture.setValues(): parameter '${n}' has value of undefined.`);continue}const a=this[n];if(a===void 0){vn(`Texture.setValues(): property '${n}' does not exist.`);continue}a&&r&&a.isVector2&&r.isVector2||a&&r&&a.isVector3&&r.isVector3||a&&r&&a.isMatrix3&&r.isMatrix3?a.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const r={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==DX)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case _3:e.x=e.x-Math.floor(e.x);break;case Ou:e.x=e.x<0?0:1;break;case N3:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case _3:e.y=e.y-Math.floor(e.y);break;case Ou:e.y=e.y<0?0:1;break;case N3:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};ac.DEFAULT_IMAGE=null;ac.DEFAULT_MAPPING=DX;ac.DEFAULT_ANISOTROPY=1;let Za=class WX{constructor(e=0,n=0,r=0,a=1){WX.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=a}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,a){return this.x=e,this.y=n,this.z=r,this.w=a,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,a=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*a+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*a+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*a+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*a+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,a,s;const c=e.elements,u=c[0],d=c[4],h=c[8],f=c[1],p=c[5],x=c[9],v=c[2],g=c[6],y=c[10];if(Math.abs(d-f)<.01&&Math.abs(h-v)<.01&&Math.abs(x-g)<.01){if(Math.abs(d+f)<.1&&Math.abs(h+v)<.1&&Math.abs(x+g)<.1&&Math.abs(u+p+y-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const N=(u+1)/2,k=(p+1)/2,A=(y+1)/2,M=(d+f)/4,C=(h+v)/4,j=(x+g)/4;return N>k&&N>A?N<.01?(r=0,a=.707106781,s=.707106781):(r=Math.sqrt(N),a=M/r,s=C/r):k>A?k<.01?(r=.707106781,a=0,s=.707106781):(a=Math.sqrt(k),r=M/a,s=j/a):A<.01?(r=.707106781,a=.707106781,s=0):(s=Math.sqrt(A),r=C/s,a=j/s),this.set(r,a,s,n),this}let _=Math.sqrt((g-x)*(g-x)+(h-v)*(h-v)+(f-d)*(f-d));return Math.abs(_)<.001&&(_=1),this.x=(g-x)/_,this.y=(h-v)/_,this.z=(f-d)/_,this.w=Math.acos((u+p+y-1)/2),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this.w=n[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Yn(this.x,e.x,n.x),this.y=Yn(this.y,e.y,n.y),this.z=Yn(this.z,e.z,n.z),this.w=Yn(this.w,e.w,n.w),this}clampScalar(e,n){return this.x=Yn(this.x,e,n),this.y=Yn(this.y,e,n),this.z=Yn(this.z,e,n),this.w=Yn(this.w,e,n),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Yn(r,e,n))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Abe=class extends np{constructor(e=1,n=1,r={}){super(),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:hl,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},r),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=r.depth,this.scissor=new Za(0,0,e,n),this.scissorTest=!1,this.viewport=new Za(0,0,e,n);const a={width:e,height:n,depth:r.depth},s=new ac(a);this.textures=[];const o=r.count;for(let l=0;l<o;l++)this.textures[l]=s.clone(),this.textures[l].isRenderTargetTexture=!0,this.textures[l].renderTarget=this;this._setTextureOptions(r),this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.resolveDepthBuffer=r.resolveDepthBuffer,this.resolveStencilBuffer=r.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=r.depthTexture,this.samples=r.samples,this.multiview=r.multiview}_setTextureOptions(e={}){const n={minFilter:hl,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(n.mapping=e.mapping),e.wrapS!==void 0&&(n.wrapS=e.wrapS),e.wrapT!==void 0&&(n.wrapT=e.wrapT),e.wrapR!==void 0&&(n.wrapR=e.wrapR),e.magFilter!==void 0&&(n.magFilter=e.magFilter),e.minFilter!==void 0&&(n.minFilter=e.minFilter),e.format!==void 0&&(n.format=e.format),e.type!==void 0&&(n.type=e.type),e.anisotropy!==void 0&&(n.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(n.colorSpace=e.colorSpace),e.flipY!==void 0&&(n.flipY=e.flipY),e.generateMipmaps!==void 0&&(n.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(n.internalFormat=e.internalFormat);for(let r=0;r<this.textures.length;r++)this.textures[r].setValues(n)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,n,r=1){if(this.width!==e||this.height!==n||this.depth!==r){this.width=e,this.height=n,this.depth=r;for(let a=0,s=this.textures.length;a<s;a++)this.textures[a].image.width=e,this.textures[a].image.height=n,this.textures[a].image.depth=r,this.textures[a].isData3DTexture!==!0&&(this.textures[a].isArrayTexture=this.textures[a].image.depth>1);this.dispose()}this.viewport.set(0,0,e,n),this.scissor.set(0,0,e,n)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let n=0,r=e.textures.length;n<r;n++){this.textures[n]=e.textures[n].clone(),this.textures[n].isRenderTargetTexture=!0,this.textures[n].renderTarget=this;const a=Object.assign({},e.textures[n].image);this.textures[n].source=new $F(a)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}},Of=class extends Abe{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}},KX=class extends ac{constructor(e=null,n=1,r=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:a},this.magFilter=Eo,this.minFilter=Eo,this.wrapR=Ou,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Tbe=class extends ac{constructor(e=null,n=1,r=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:a},this.magFilter=Eo,this.minFilter=Eo,this.wrapR=Ou,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Rh=class{constructor(e=new ft(1/0,1/0,1/0),n=new ft(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n+=3)this.expandByPoint(Dl.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(Dl.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const r=Dl.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}setFromObject(e,n=!1){return this.makeEmpty(),this.expandByObject(e,n)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,n=!1){e.updateWorldMatrix(!1,!1);const r=e.geometry;if(r!==void 0){const s=r.getAttribute("position");if(n===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,l=s.count;o<l;o++)e.isMesh===!0?e.getVertexPosition(o,Dl):Dl.fromBufferAttribute(s,o),Dl.applyMatrix4(e.matrixWorld),this.expandByPoint(Dl);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),sS.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),sS.copy(r.boundingBox)),sS.applyMatrix4(e.matrixWorld),this.union(sS)}const a=e.children;for(let s=0,o=a.length;s<o;s++)this.expandByObject(a[s],n);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Dl),Dl.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ty),oS.subVectors(this.max,ty),Vp.subVectors(e.a,ty),qp.subVectors(e.b,ty),Gp.subVectors(e.c,ty),Hd.subVectors(qp,Vp),$d.subVectors(Gp,qp),km.subVectors(Vp,Gp);let n=[0,-Hd.z,Hd.y,0,-$d.z,$d.y,0,-km.z,km.y,Hd.z,0,-Hd.x,$d.z,0,-$d.x,km.z,0,-km.x,-Hd.y,Hd.x,0,-$d.y,$d.x,0,-km.y,km.x,0];return!KM(n,Vp,qp,Gp,oS)||(n=[1,0,0,0,1,0,0,0,1],!KM(n,Vp,qp,Gp,oS))?!1:(lS.crossVectors(Hd,$d),n=[lS.x,lS.y,lS.z],KM(n,Vp,qp,Gp,oS))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Dl).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Dl).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(hu[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),hu[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),hu[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),hu[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),hu[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),hu[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),hu[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),hu[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(hu),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}};const hu=[new ft,new ft,new ft,new ft,new ft,new ft,new ft,new ft],Dl=new ft,sS=new Rh,Vp=new ft,qp=new ft,Gp=new ft,Hd=new ft,$d=new ft,km=new ft,ty=new ft,oS=new ft,lS=new ft,Am=new ft;function KM(t,e,n,r,a){for(let s=0,o=t.length-3;s<=o;s+=3){Am.fromArray(t,s);const l=a.x*Math.abs(Am.x)+a.y*Math.abs(Am.y)+a.z*Math.abs(Am.z),c=e.dot(Am),u=n.dot(Am),d=r.dot(Am);if(Math.max(-Math.max(c,u,d),Math.min(c,u,d))>l)return!1}return!0}const Mbe=new Rh,ny=new ft,XM=new ft;let rk=class{constructor(e=new ft,n=-1){this.isSphere=!0,this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):Mbe.setFromPoints(e).getCenter(r);let a=0;for(let s=0,o=e.length;s<o;s++)a=Math.max(a,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(a),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const n=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=n*n}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,n){const r=this.center.distanceToSquared(e);return n.copy(e),r>this.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ny.subVectors(e,this.center);const n=ny.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),a=(r-this.radius)*.5;this.center.addScaledVector(ny,a/r),this.radius+=a}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(XM.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ny.copy(e.center).add(XM)),this.expandByPoint(ny.copy(e.center).sub(XM))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}};const mu=new ft,YM=new ft,cS=new ft,Vd=new ft,QM=new ft,uS=new ft,ZM=new ft;let VF=class{constructor(e=new ft,n=new ft(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,mu)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=mu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(mu.copy(this.origin).addScaledVector(this.direction,n),mu.distanceToSquared(e))}distanceSqToSegment(e,n,r,a){YM.copy(e).add(n).multiplyScalar(.5),cS.copy(n).sub(e).normalize(),Vd.copy(this.origin).sub(YM);const s=e.distanceTo(n)*.5,o=-this.direction.dot(cS),l=Vd.dot(this.direction),c=-Vd.dot(cS),u=Vd.lengthSq(),d=Math.abs(1-o*o);let h,f,p,x;if(d>0)if(h=o*c-l,f=o*l-c,x=s*d,h>=0)if(f>=-x)if(f<=x){const v=1/d;h*=v,f*=v,p=h*(h+o*f+2*l)+f*(o*h+f+2*c)+u}else f=s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;else f=-s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;else f<=-x?(h=Math.max(0,-(-o*s+l)),f=h>0?-s:Math.min(Math.max(-s,-c),s),p=-h*h+f*(f+2*c)+u):f<=x?(h=0,f=Math.min(Math.max(-s,-c),s),p=f*(f+2*c)+u):(h=Math.max(0,-(o*s+l)),f=h>0?s:Math.min(Math.max(-s,-c),s),p=-h*h+f*(f+2*c)+u);else f=o>0?-s:s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;return r&&r.copy(this.origin).addScaledVector(this.direction,h),a&&a.copy(YM).addScaledVector(cS,f),p}intersectSphere(e,n){mu.subVectors(e.center,this.origin);const r=mu.dot(this.direction),a=mu.dot(mu)-r*r,s=e.radius*e.radius;if(a>s)return null;const o=Math.sqrt(s-a),l=r-o,c=r+o;return c<0?null:l<0?this.at(c,n):this.at(l,n)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,a,s,o,l,c;const u=1/this.direction.x,d=1/this.direction.y,h=1/this.direction.z,f=this.origin;return u>=0?(r=(e.min.x-f.x)*u,a=(e.max.x-f.x)*u):(r=(e.max.x-f.x)*u,a=(e.min.x-f.x)*u),d>=0?(s=(e.min.y-f.y)*d,o=(e.max.y-f.y)*d):(s=(e.max.y-f.y)*d,o=(e.min.y-f.y)*d),r>o||s>a||((s>r||isNaN(r))&&(r=s),(o<a||isNaN(a))&&(a=o),h>=0?(l=(e.min.z-f.z)*h,c=(e.max.z-f.z)*h):(l=(e.max.z-f.z)*h,c=(e.min.z-f.z)*h),r>c||l>a)||((l>r||r!==r)&&(r=l),(c<a||a!==a)&&(a=c),a<0)?null:this.at(r>=0?r:a,n)}intersectsBox(e){return this.intersectBox(e,mu)!==null}intersectTriangle(e,n,r,a,s){QM.subVectors(n,e),uS.subVectors(r,e),ZM.crossVectors(QM,uS);let o=this.direction.dot(ZM),l;if(o>0){if(a)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Vd.subVectors(this.origin,e);const c=l*this.direction.dot(uS.crossVectors(Vd,uS));if(c<0)return null;const u=l*this.direction.dot(QM.cross(Vd));if(u<0||c+u>o)return null;const d=-l*Vd.dot(ZM);return d<0?null:this.at(d/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},ri=class eD{constructor(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g){eD.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g)}set(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g){const y=this.elements;return y[0]=e,y[4]=n,y[8]=r,y[12]=a,y[1]=s,y[5]=o,y[9]=l,y[13]=c,y[2]=u,y[6]=d,y[10]=h,y[14]=f,y[3]=p,y[7]=x,y[11]=v,y[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new eD().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,a=1/Wp.setFromMatrixColumn(e,0).length(),s=1/Wp.setFromMatrixColumn(e,1).length(),o=1/Wp.setFromMatrixColumn(e,2).length();return n[0]=r[0]*a,n[1]=r[1]*a,n[2]=r[2]*a,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,a=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(a),u=Math.sin(a),d=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const f=o*d,p=o*h,x=l*d,v=l*h;n[0]=c*d,n[4]=-c*h,n[8]=u,n[1]=p+x*u,n[5]=f-v*u,n[9]=-l*c,n[2]=v-f*u,n[6]=x+p*u,n[10]=o*c}else if(e.order==="YXZ"){const f=c*d,p=c*h,x=u*d,v=u*h;n[0]=f+v*l,n[4]=x*l-p,n[8]=o*u,n[1]=o*h,n[5]=o*d,n[9]=-l,n[2]=p*l-x,n[6]=v+f*l,n[10]=o*c}else if(e.order==="ZXY"){const f=c*d,p=c*h,x=u*d,v=u*h;n[0]=f-v*l,n[4]=-o*h,n[8]=x+p*l,n[1]=p+x*l,n[5]=o*d,n[9]=v-f*l,n[2]=-o*u,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const f=o*d,p=o*h,x=l*d,v=l*h;n[0]=c*d,n[4]=x*u-p,n[8]=f*u+v,n[1]=c*h,n[5]=v*u+f,n[9]=p*u-x,n[2]=-u,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const f=o*c,p=o*u,x=l*c,v=l*u;n[0]=c*d,n[4]=v-f*h,n[8]=x*h+p,n[1]=h,n[5]=o*d,n[9]=-l*d,n[2]=-u*d,n[6]=p*h+x,n[10]=f-v*h}else if(e.order==="XZY"){const f=o*c,p=o*u,x=l*c,v=l*u;n[0]=c*d,n[4]=-h,n[8]=u*d,n[1]=f*h+v,n[5]=o*d,n[9]=p*h-x,n[2]=x*h-p,n[6]=l*d,n[10]=v*h+f}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Pbe,e,Ebe)}lookAt(e,n,r){const a=this.elements;return So.subVectors(e,n),So.lengthSq()===0&&(So.z=1),So.normalize(),qd.crossVectors(r,So),qd.lengthSq()===0&&(Math.abs(r.z)===1?So.x+=1e-4:So.z+=1e-4,So.normalize(),qd.crossVectors(r,So)),qd.normalize(),dS.crossVectors(So,qd),a[0]=qd.x,a[4]=dS.x,a[8]=So.x,a[1]=qd.y,a[5]=dS.y,a[9]=So.y,a[2]=qd.z,a[6]=dS.z,a[10]=So.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,a=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],u=r[12],d=r[1],h=r[5],f=r[9],p=r[13],x=r[2],v=r[6],g=r[10],y=r[14],_=r[3],N=r[7],k=r[11],A=r[15],M=a[0],C=a[4],j=a[8],P=a[12],E=a[1],U=a[5],L=a[9],B=a[13],D=a[2],$=a[6],G=a[10],z=a[14],W=a[3],X=a[7],ae=a[11],H=a[15];return s[0]=o*M+l*E+c*D+u*W,s[4]=o*C+l*U+c*$+u*X,s[8]=o*j+l*L+c*G+u*ae,s[12]=o*P+l*B+c*z+u*H,s[1]=d*M+h*E+f*D+p*W,s[5]=d*C+h*U+f*$+p*X,s[9]=d*j+h*L+f*G+p*ae,s[13]=d*P+h*B+f*z+p*H,s[2]=x*M+v*E+g*D+y*W,s[6]=x*C+v*U+g*$+y*X,s[10]=x*j+v*L+g*G+y*ae,s[14]=x*P+v*B+g*z+y*H,s[3]=_*M+N*E+k*D+A*W,s[7]=_*C+N*U+k*$+A*X,s[11]=_*j+N*L+k*G+A*ae,s[15]=_*P+N*B+k*z+A*H,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],a=e[8],s=e[12],o=e[1],l=e[5],c=e[9],u=e[13],d=e[2],h=e[6],f=e[10],p=e[14],x=e[3],v=e[7],g=e[11],y=e[15];return x*(+s*c*h-a*u*h-s*l*f+r*u*f+a*l*p-r*c*p)+v*(+n*c*p-n*u*f+s*o*f-a*o*p+a*u*d-s*c*d)+g*(+n*u*h-n*l*p-s*o*h+r*o*p+s*l*d-r*u*d)+y*(-a*l*d-n*c*h+n*l*f+a*o*h-r*o*f+r*c*d)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const a=this.elements;return e.isVector3?(a[12]=e.x,a[13]=e.y,a[14]=e.z):(a[12]=e,a[13]=n,a[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],x=e[12],v=e[13],g=e[14],y=e[15],_=h*g*u-v*f*u+v*c*p-l*g*p-h*c*y+l*f*y,N=x*f*u-d*g*u-x*c*p+o*g*p+d*c*y-o*f*y,k=d*v*u-x*h*u+x*l*p-o*v*p-d*l*y+o*h*y,A=x*h*c-d*v*c-x*l*f+o*v*f+d*l*g-o*h*g,M=n*_+r*N+a*k+s*A;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/M;return e[0]=_*C,e[1]=(v*f*s-h*g*s-v*a*p+r*g*p+h*a*y-r*f*y)*C,e[2]=(l*g*s-v*c*s+v*a*u-r*g*u-l*a*y+r*c*y)*C,e[3]=(h*c*s-l*f*s-h*a*u+r*f*u+l*a*p-r*c*p)*C,e[4]=N*C,e[5]=(d*g*s-x*f*s+x*a*p-n*g*p-d*a*y+n*f*y)*C,e[6]=(x*c*s-o*g*s-x*a*u+n*g*u+o*a*y-n*c*y)*C,e[7]=(o*f*s-d*c*s+d*a*u-n*f*u-o*a*p+n*c*p)*C,e[8]=k*C,e[9]=(x*h*s-d*v*s-x*r*p+n*v*p+d*r*y-n*h*y)*C,e[10]=(o*v*s-x*l*s+x*r*u-n*v*u-o*r*y+n*l*y)*C,e[11]=(d*l*s-o*h*s-d*r*u+n*h*u+o*r*p-n*l*p)*C,e[12]=A*C,e[13]=(d*v*a-x*h*a+x*r*f-n*v*f-d*r*g+n*h*g)*C,e[14]=(x*l*a-o*v*a-x*r*c+n*v*c+o*r*g-n*l*g)*C,e[15]=(o*h*a-d*l*a+d*r*c-n*h*c-o*r*f+n*l*f)*C,this}scale(e){const n=this.elements,r=e.x,a=e.y,s=e.z;return n[0]*=r,n[4]*=a,n[8]*=s,n[1]*=r,n[5]*=a,n[9]*=s,n[2]*=r,n[6]*=a,n[10]*=s,n[3]*=r,n[7]*=a,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],a=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,a))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),a=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,u=s*o,d=s*l;return this.set(u*o+r,u*l-a*c,u*c+a*l,0,u*l+a*c,d*l+r,d*c-a*o,0,u*c-a*l,d*c+a*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,a,s,o){return this.set(1,r,s,0,e,1,o,0,n,a,1,0,0,0,0,1),this}compose(e,n,r){const a=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,u=s+s,d=o+o,h=l+l,f=s*u,p=s*d,x=s*h,v=o*d,g=o*h,y=l*h,_=c*u,N=c*d,k=c*h,A=r.x,M=r.y,C=r.z;return a[0]=(1-(v+y))*A,a[1]=(p+k)*A,a[2]=(x-N)*A,a[3]=0,a[4]=(p-k)*M,a[5]=(1-(f+y))*M,a[6]=(g+_)*M,a[7]=0,a[8]=(x+N)*C,a[9]=(g-_)*C,a[10]=(1-(f+v))*C,a[11]=0,a[12]=e.x,a[13]=e.y,a[14]=e.z,a[15]=1,this}decompose(e,n,r){const a=this.elements;let s=Wp.set(a[0],a[1],a[2]).length();const o=Wp.set(a[4],a[5],a[6]).length(),l=Wp.set(a[8],a[9],a[10]).length();this.determinant()<0&&(s=-s),e.x=a[12],e.y=a[13],e.z=a[14],Rl.copy(this);const u=1/s,d=1/o,h=1/l;return Rl.elements[0]*=u,Rl.elements[1]*=u,Rl.elements[2]*=u,Rl.elements[4]*=d,Rl.elements[5]*=d,Rl.elements[6]*=d,Rl.elements[8]*=h,Rl.elements[9]*=h,Rl.elements[10]*=h,n.setFromRotationMatrix(Rl),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,a,s,o,l=kc,c=!1){const u=this.elements,d=2*s/(n-e),h=2*s/(r-a),f=(n+e)/(n-e),p=(r+a)/(r-a);let x,v;if(c)x=s/(o-s),v=o*s/(o-s);else if(l===kc)x=-(o+s)/(o-s),v=-2*o*s/(o-s);else if(l===T1)x=-o/(o-s),v=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+l);return u[0]=d,u[4]=0,u[8]=f,u[12]=0,u[1]=0,u[5]=h,u[9]=p,u[13]=0,u[2]=0,u[6]=0,u[10]=x,u[14]=v,u[3]=0,u[7]=0,u[11]=-1,u[15]=0,this}makeOrthographic(e,n,r,a,s,o,l=kc,c=!1){const u=this.elements,d=2/(n-e),h=2/(r-a),f=-(n+e)/(n-e),p=-(r+a)/(r-a);let x,v;if(c)x=1/(o-s),v=o/(o-s);else if(l===kc)x=-2/(o-s),v=-(o+s)/(o-s);else if(l===T1)x=-1/(o-s),v=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return u[0]=d,u[4]=0,u[8]=0,u[12]=f,u[1]=0,u[5]=h,u[9]=0,u[13]=p,u[2]=0,u[6]=0,u[10]=x,u[14]=v,u[3]=0,u[7]=0,u[11]=0,u[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let a=0;a<16;a++)if(n[a]!==r[a])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}};const Wp=new ft,Rl=new ri,Pbe=new ft(0,0,0),Ebe=new ft(1,1,1),qd=new ft,dS=new ft,So=new ft,n8=new ri,r8=new Lf;let Gh=class XX{constructor(e=0,n=0,r=0,a=XX.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=a}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,a=this._order){return this._x=e,this._y=n,this._z=r,this._order=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const a=e.elements,s=a[0],o=a[4],l=a[8],c=a[1],u=a[5],d=a[9],h=a[2],f=a[6],p=a[10];switch(n){case"XYZ":this._y=Math.asin(Yn(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,p),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(f,u),this._z=0);break;case"YXZ":this._x=Math.asin(-Yn(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(l,p),this._z=Math.atan2(c,u)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Yn(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-h,p),this._z=Math.atan2(-o,u)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Yn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(f,p),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,u));break;case"YZX":this._z=Math.asin(Yn(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,u),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(l,p));break;case"XZY":this._z=Math.asin(-Yn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(f,u),this._y=Math.atan2(l,s)):(this._x=Math.atan2(-d,p),this._y=0);break;default:vn("Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return n8.makeRotationFromQuaternion(e),this.setFromRotationMatrix(n8,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return r8.setFromEuler(this),this.setFromQuaternion(r8,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Gh.DEFAULT_ORDER="XYZ";let YX=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},jbe=0;const a8=new ft,Kp=new Lf,fu=new ri,hS=new ft,ry=new ft,Dbe=new ft,Rbe=new Lf,i8=new ft(1,0,0),s8=new ft(0,1,0),o8=new ft(0,0,1),l8={type:"added"},Fbe={type:"removed"},Xp={type:"childadded",child:null},JM={type:"childremoved",child:null};let Lo=class Y_ extends np{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:jbe++}),this.uuid=p0(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Y_.DEFAULT_UP.clone();const e=new ft,n=new Gh,r=new Lf,a=new ft(1,1,1);function s(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(s),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:a},modelViewMatrix:{value:new ri},normalMatrix:{value:new Hn}}),this.matrix=new ri,this.matrixWorld=new ri,this.matrixAutoUpdate=Y_.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Y_.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new YX,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,n){this.quaternion.setFromAxisAngle(e,n)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,n){return Kp.setFromAxisAngle(e,n),this.quaternion.multiply(Kp),this}rotateOnWorldAxis(e,n){return Kp.setFromAxisAngle(e,n),this.quaternion.premultiply(Kp),this}rotateX(e){return this.rotateOnAxis(i8,e)}rotateY(e){return this.rotateOnAxis(s8,e)}rotateZ(e){return this.rotateOnAxis(o8,e)}translateOnAxis(e,n){return a8.copy(e).applyQuaternion(this.quaternion),this.position.add(a8.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(i8,e)}translateY(e){return this.translateOnAxis(s8,e)}translateZ(e){return this.translateOnAxis(o8,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(fu.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?hS.copy(e):hS.set(e,n,r);const a=this.parent;this.updateWorldMatrix(!0,!1),ry.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?fu.lookAt(ry,hS,this.up):fu.lookAt(hS,ry,this.up),this.quaternion.setFromRotationMatrix(fu),a&&(fu.extractRotation(a.matrixWorld),Kp.setFromRotationMatrix(fu),this.quaternion.premultiply(Kp.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(Ua("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(l8),Xp.child=e,this.dispatchEvent(Xp),Xp.child=null):Ua("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.remove(arguments[r]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(Fbe),JM.child=e,this.dispatchEvent(JM),JM.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),fu.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),fu.multiply(e.parent.matrixWorld)),e.applyMatrix4(fu),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(l8),Xp.child=e,this.dispatchEvent(Xp),Xp.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,n){if(this[e]===n)return this;for(let r=0,a=this.children.length;r<a;r++){const o=this.children[r].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,r=[]){this[e]===n&&r.push(this);const a=this.children;for(let s=0,o=a.length;s<o;s++)a[s].getObjectsByProperty(e,n,r);return r}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ry,e,Dbe),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ry,Rbe,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const n=this.matrixWorld.elements;return e.set(n[8],n[9],n[10]).normalize()}raycast(){}traverse(e){e(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].traverseVisible(e)}traverseAncestors(e){const n=this.parent;n!==null&&(e(n),n.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].updateMatrixWorld(e)}updateWorldMatrix(e,n){const r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),n===!0){const a=this.children;for(let s=0,o=a.length;s<o;s++)a[s].updateWorldMatrix(!1,!0)}}toJSON(e){const n=e===void 0||typeof e=="string",r={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},r.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const a={};a.uuid=this.uuid,a.type=this.type,this.name!==""&&(a.name=this.name),this.castShadow===!0&&(a.castShadow=!0),this.receiveShadow===!0&&(a.receiveShadow=!0),this.visible===!1&&(a.visible=!1),this.frustumCulled===!1&&(a.frustumCulled=!1),this.renderOrder!==0&&(a.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(a.userData=this.userData),a.layers=this.layers.mask,a.matrix=this.matrix.toArray(),a.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(a.matrixAutoUpdate=!1),this.isInstancedMesh&&(a.type="InstancedMesh",a.count=this.count,a.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(a.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(a.type="BatchedMesh",a.perObjectFrustumCulled=this.perObjectFrustumCulled,a.sortObjects=this.sortObjects,a.drawRanges=this._drawRanges,a.reservedRanges=this._reservedRanges,a.geometryInfo=this._geometryInfo.map(l=>({...l,boundingBox:l.boundingBox?l.boundingBox.toJSON():void 0,boundingSphere:l.boundingSphere?l.boundingSphere.toJSON():void 0})),a.instanceInfo=this._instanceInfo.map(l=>({...l})),a.availableInstanceIds=this._availableInstanceIds.slice(),a.availableGeometryIds=this._availableGeometryIds.slice(),a.nextIndexStart=this._nextIndexStart,a.nextVertexStart=this._nextVertexStart,a.geometryCount=this._geometryCount,a.maxInstanceCount=this._maxInstanceCount,a.maxVertexCount=this._maxVertexCount,a.maxIndexCount=this._maxIndexCount,a.geometryInitialized=this._geometryInitialized,a.matricesTexture=this._matricesTexture.toJSON(e),a.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(a.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(a.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(a.boundingBox=this.boundingBox.toJSON()));function s(l,c){return l[c.uuid]===void 0&&(l[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?a.background=this.background.toJSON():this.background.isTexture&&(a.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(a.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){a.geometry=s(e.geometries,this.geometry);const l=this.geometry.parameters;if(l!==void 0&&l.shapes!==void 0){const c=l.shapes;if(Array.isArray(c))for(let u=0,d=c.length;u<d;u++){const h=c[u];s(e.shapes,h)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(a.bindMode=this.bindMode,a.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),a.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,u=this.material.length;c<u;c++)l.push(s(e.materials,this.material[c]));a.material=l}else a.material=s(e.materials,this.material);if(this.children.length>0){a.children=[];for(let l=0;l<this.children.length;l++)a.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){a.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];a.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),u=o(e.textures),d=o(e.images),h=o(e.shapes),f=o(e.skeletons),p=o(e.animations),x=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),u.length>0&&(r.textures=u),d.length>0&&(r.images=d),h.length>0&&(r.shapes=h),f.length>0&&(r.skeletons=f),p.length>0&&(r.animations=p),x.length>0&&(r.nodes=x)}return r.object=a,r;function o(l){const c=[];for(const u in l){const d=l[u];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r<e.children.length;r++){const a=e.children[r];this.add(a.clone())}return this}};Lo.DEFAULT_UP=new ft(0,1,0);Lo.DEFAULT_MATRIX_AUTO_UPDATE=!0;Lo.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Fl=new ft,pu=new ft,eP=new ft,gu=new ft,Yp=new ft,Qp=new ft,c8=new ft,tP=new ft,nP=new ft,rP=new ft,aP=new Za,iP=new Za,sP=new Za;let ay=class jg{constructor(e=new ft,n=new ft,r=new ft){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,a){a.subVectors(r,n),Fl.subVectors(e,n),a.cross(Fl);const s=a.lengthSq();return s>0?a.multiplyScalar(1/Math.sqrt(s)):a.set(0,0,0)}static getBarycoord(e,n,r,a,s){Fl.subVectors(a,n),pu.subVectors(r,n),eP.subVectors(e,n);const o=Fl.dot(Fl),l=Fl.dot(pu),c=Fl.dot(eP),u=pu.dot(pu),d=pu.dot(eP),h=o*u-l*l;if(h===0)return s.set(0,0,0),null;const f=1/h,p=(u*c-l*d)*f,x=(o*d-l*c)*f;return s.set(1-p-x,x,p)}static containsPoint(e,n,r,a){return this.getBarycoord(e,n,r,a,gu)===null?!1:gu.x>=0&&gu.y>=0&&gu.x+gu.y<=1}static getInterpolation(e,n,r,a,s,o,l,c){return this.getBarycoord(e,n,r,a,gu)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,gu.x),c.addScaledVector(o,gu.y),c.addScaledVector(l,gu.z),c)}static getInterpolatedAttribute(e,n,r,a,s,o){return aP.setScalar(0),iP.setScalar(0),sP.setScalar(0),aP.fromBufferAttribute(e,n),iP.fromBufferAttribute(e,r),sP.fromBufferAttribute(e,a),o.setScalar(0),o.addScaledVector(aP,s.x),o.addScaledVector(iP,s.y),o.addScaledVector(sP,s.z),o}static isFrontFacing(e,n,r,a){return Fl.subVectors(r,n),pu.subVectors(e,n),Fl.cross(pu).dot(a)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,a){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[a]),this}setFromAttributeAndIndices(e,n,r,a){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,a),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Fl.subVectors(this.c,this.b),pu.subVectors(this.a,this.b),Fl.cross(pu).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return jg.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return jg.getBarycoord(e,this.a,this.b,this.c,n)}getInterpolation(e,n,r,a,s){return jg.getInterpolation(e,this.a,this.b,this.c,n,r,a,s)}containsPoint(e){return jg.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return jg.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,a=this.b,s=this.c;let o,l;Yp.subVectors(a,r),Qp.subVectors(s,r),tP.subVectors(e,r);const c=Yp.dot(tP),u=Qp.dot(tP);if(c<=0&&u<=0)return n.copy(r);nP.subVectors(e,a);const d=Yp.dot(nP),h=Qp.dot(nP);if(d>=0&&h<=d)return n.copy(a);const f=c*h-d*u;if(f<=0&&c>=0&&d<=0)return o=c/(c-d),n.copy(r).addScaledVector(Yp,o);rP.subVectors(e,s);const p=Yp.dot(rP),x=Qp.dot(rP);if(x>=0&&p<=x)return n.copy(s);const v=p*u-c*x;if(v<=0&&u>=0&&x<=0)return l=u/(u-x),n.copy(r).addScaledVector(Qp,l);const g=d*x-p*h;if(g<=0&&h-d>=0&&p-x>=0)return c8.subVectors(s,a),l=(h-d)/(h-d+(p-x)),n.copy(a).addScaledVector(c8,l);const y=1/(g+v+f);return o=v*y,l=f*y,n.copy(r).addScaledVector(Yp,o).addScaledVector(Qp,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}};const QX={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Gd={h:0,s:0,l:0},mS={h:0,s:0,l:0};function oP(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}let $n=class{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const a=e;a&&a.isColor?this.copy(a):typeof a=="number"?this.setHex(a):typeof a=="string"&&this.setStyle(a)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=ko){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,cr.colorSpaceToWorking(this,n),this}setRGB(e,n,r,a=cr.workingColorSpace){return this.r=e,this.g=n,this.b=r,cr.colorSpaceToWorking(this,a),this}setHSL(e,n,r,a=cr.workingColorSpace){if(e=wbe(e,1),n=Yn(n,0,1),r=Yn(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=oP(o,s,e+1/3),this.g=oP(o,s,e),this.b=oP(o,s,e-1/3)}return cr.colorSpaceToWorking(this,a),this}setStyle(e,n=ko){function r(s){s!==void 0&&parseFloat(s)<1&&vn("Color: Alpha component of "+e+" will be ignored.")}let a;if(a=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=a[1],l=a[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:vn("Color: Unknown color model "+e)}}else if(a=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=a[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,n);if(o===6)return this.setHex(parseInt(s,16),n);vn("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=ko){const r=QX[e.toLowerCase()];return r!==void 0?this.setHex(r,n):vn("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=qu(e.r),this.g=qu(e.g),this.b=qu(e.b),this}copyLinearToSRGB(e){return this.r=Qg(e.r),this.g=Qg(e.g),this.b=Qg(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ko){return cr.workingToColorSpace(ss.copy(this),e),Math.round(Yn(ss.r*255,0,255))*65536+Math.round(Yn(ss.g*255,0,255))*256+Math.round(Yn(ss.b*255,0,255))}getHexString(e=ko){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=cr.workingColorSpace){cr.workingToColorSpace(ss.copy(this),n);const r=ss.r,a=ss.g,s=ss.b,o=Math.max(r,a,s),l=Math.min(r,a,s);let c,u;const d=(l+o)/2;if(l===o)c=0,u=0;else{const h=o-l;switch(u=d<=.5?h/(o+l):h/(2-o-l),o){case r:c=(a-s)/h+(a<s?6:0);break;case a:c=(s-r)/h+2;break;case s:c=(r-a)/h+4;break}c/=6}return e.h=c,e.s=u,e.l=d,e}getRGB(e,n=cr.workingColorSpace){return cr.workingToColorSpace(ss.copy(this),n),e.r=ss.r,e.g=ss.g,e.b=ss.b,e}getStyle(e=ko){cr.workingToColorSpace(ss.copy(this),e);const n=ss.r,r=ss.g,a=ss.b;return e!==ko?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${a.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(a*255)})`}offsetHSL(e,n,r){return this.getHSL(Gd),this.setHSL(Gd.h+e,Gd.s+n,Gd.l+r)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,n){return this.r=e.r+n.r,this.g=e.g+n.g,this.b=e.b+n.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,n){return this.r+=(e.r-this.r)*n,this.g+=(e.g-this.g)*n,this.b+=(e.b-this.b)*n,this}lerpColors(e,n,r){return this.r=e.r+(n.r-e.r)*r,this.g=e.g+(n.g-e.g)*r,this.b=e.b+(n.b-e.b)*r,this}lerpHSL(e,n){this.getHSL(Gd),e.getHSL(mS);const r=$M(Gd.h,mS.h,n),a=$M(Gd.s,mS.s,n),s=$M(Gd.l,mS.l,n);return this.setHSL(r,a,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const n=this.r,r=this.g,a=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*a,this.g=s[1]*n+s[4]*r+s[7]*a,this.b=s[2]*n+s[5]*r+s[8]*a,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,n=0){return this.r=e[n],this.g=e[n+1],this.b=e[n+2],this}toArray(e=[],n=0){return e[n]=this.r,e[n+1]=this.g,e[n+2]=this.b,e}fromBufferAttribute(e,n){return this.r=e.getX(n),this.g=e.getY(n),this.b=e.getZ(n),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const ss=new $n;$n.NAMES=QX;let Lbe=0,Wb=class extends np{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Lbe++}),this.uuid=p0(),this.name="",this.type="Material",this.blending=Yg,this.side=qh,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=h3,this.blendDst=m3,this.blendEquation=Gm,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new $n(0,0,0),this.blendAlpha=0,this.depthFunc=fb,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=KB,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Hp,this.stencilZFail=Hp,this.stencilZPass=Hp,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){vn(`Material: parameter '${n}' has value of undefined.`);continue}const a=this[n];if(a===void 0){vn(`Material: '${n}' is not a property of THREE.${this.type}.`);continue}a&&a.isColor?a.set(r):a&&a.isVector3&&r&&r.isVector3?a.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(r.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(r.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==Yg&&(r.blending=this.blending),this.side!==qh&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==h3&&(r.blendSrc=this.blendSrc),this.blendDst!==m3&&(r.blendDst=this.blendDst),this.blendEquation!==Gm&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==fb&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==KB&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Hp&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Hp&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Hp&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function a(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=a(e.textures),o=a(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const a=n.length;r=new Array(a);for(let s=0;s!==a;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},qF=class extends Wb{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new $n(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Gh,this.combine=FF,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}};const Ya=new ft,fS=new Un;let Obe=0,Ds=class{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Obe++}),this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=XB,this.updateRanges=[],this.gpuType=Iu,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let a=0,s=this.itemSize;a<s;a++)this.array[e+a]=n.array[r+a];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,r=this.count;n<r;n++)fS.fromBufferAttribute(this,n),fS.applyMatrix3(e),this.setXY(n,fS.x,fS.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)Ya.fromBufferAttribute(this,n),Ya.applyMatrix3(e),this.setXYZ(n,Ya.x,Ya.y,Ya.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)Ya.fromBufferAttribute(this,n),Ya.applyMatrix4(e),this.setXYZ(n,Ya.x,Ya.y,Ya.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)Ya.fromBufferAttribute(this,n),Ya.applyNormalMatrix(e),this.setXYZ(n,Ya.x,Ya.y,Ya.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)Ya.fromBufferAttribute(this,n),Ya.transformDirection(e),this.setXYZ(n,Ya.x,Ya.y,Ya.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let r=this.array[e*this.itemSize+n];return this.normalized&&(r=ey(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=Gs(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=ey(n,this.array)),n}setX(e,n){return this.normalized&&(n=Gs(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=ey(n,this.array)),n}setY(e,n){return this.normalized&&(n=Gs(n,this.array)),this.array[e*this.itemSize+1]=n,this}getZ(e){let n=this.array[e*this.itemSize+2];return this.normalized&&(n=ey(n,this.array)),n}setZ(e,n){return this.normalized&&(n=Gs(n,this.array)),this.array[e*this.itemSize+2]=n,this}getW(e){let n=this.array[e*this.itemSize+3];return this.normalized&&(n=ey(n,this.array)),n}setW(e,n){return this.normalized&&(n=Gs(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=Gs(n,this.array),r=Gs(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,a){return e*=this.itemSize,this.normalized&&(n=Gs(n,this.array),r=Gs(r,this.array),a=Gs(a,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=a,this}setXYZW(e,n,r,a,s){return e*=this.itemSize,this.normalized&&(n=Gs(n,this.array),r=Gs(r,this.array),a=Gs(a,this.array),s=Gs(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=a,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==XB&&(e.usage=this.usage),e}},ZX=class extends Ds{constructor(e,n,r){super(new Uint16Array(e),n,r)}},JX=class extends Ds{constructor(e,n,r){super(new Uint32Array(e),n,r)}},jo=class extends Ds{constructor(e,n,r){super(new Float32Array(e),n,r)}},Ibe=0;const Wo=new ri,lP=new Lo,Zp=new ft,_o=new Rh,iy=new Rh,Ai=new ft;let wl=class eY extends np{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Ibe++}),this.uuid=p0(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new($X(e)?JX:ZX)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,n){return this.attributes[e]=n,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,n,r=0){this.groups.push({start:e,count:n,materialIndex:r})}clearGroups(){this.groups=[]}setDrawRange(e,n){this.drawRange.start=e,this.drawRange.count=n}applyMatrix4(e){const n=this.attributes.position;n!==void 0&&(n.applyMatrix4(e),n.needsUpdate=!0);const r=this.attributes.normal;if(r!==void 0){const s=new Hn().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const a=this.attributes.tangent;return a!==void 0&&(a.transformDirection(e),a.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Wo.makeRotationFromQuaternion(e),this.applyMatrix4(Wo),this}rotateX(e){return Wo.makeRotationX(e),this.applyMatrix4(Wo),this}rotateY(e){return Wo.makeRotationY(e),this.applyMatrix4(Wo),this}rotateZ(e){return Wo.makeRotationZ(e),this.applyMatrix4(Wo),this}translate(e,n,r){return Wo.makeTranslation(e,n,r),this.applyMatrix4(Wo),this}scale(e,n,r){return Wo.makeScale(e,n,r),this.applyMatrix4(Wo),this}lookAt(e){return lP.lookAt(e),lP.updateMatrix(),this.applyMatrix4(lP.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Zp).negate(),this.translate(Zp.x,Zp.y,Zp.z),this}setFromPoints(e){const n=this.getAttribute("position");if(n===void 0){const r=[];for(let a=0,s=e.length;a<s;a++){const o=e[a];r.push(o.x,o.y,o.z||0)}this.setAttribute("position",new jo(r,3))}else{const r=Math.min(e.length,n.count);for(let a=0;a<r;a++){const s=e[a];n.setXYZ(a,s.x,s.y,s.z||0)}e.length>n.count&&vn("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),n.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Rh);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ua("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new ft(-1/0,-1/0,-1/0),new ft(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,a=n.length;r<a;r++){const s=n[r];_o.setFromBufferAttribute(s),this.morphTargetsRelative?(Ai.addVectors(this.boundingBox.min,_o.min),this.boundingBox.expandByPoint(Ai),Ai.addVectors(this.boundingBox.max,_o.max),this.boundingBox.expandByPoint(Ai)):(this.boundingBox.expandByPoint(_o.min),this.boundingBox.expandByPoint(_o.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Ua('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new rk);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ua("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new ft,1/0);return}if(e){const r=this.boundingSphere.center;if(_o.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];iy.setFromBufferAttribute(l),this.morphTargetsRelative?(Ai.addVectors(_o.min,iy.min),_o.expandByPoint(Ai),Ai.addVectors(_o.max,iy.max),_o.expandByPoint(Ai)):(_o.expandByPoint(iy.min),_o.expandByPoint(iy.max))}_o.getCenter(r);let a=0;for(let s=0,o=e.count;s<o;s++)Ai.fromBufferAttribute(e,s),a=Math.max(a,r.distanceToSquared(Ai));if(n)for(let s=0,o=n.length;s<o;s++){const l=n[s],c=this.morphTargetsRelative;for(let u=0,d=l.count;u<d;u++)Ai.fromBufferAttribute(l,u),c&&(Zp.fromBufferAttribute(e,u),Ai.add(Zp)),a=Math.max(a,r.distanceToSquared(Ai))}this.boundingSphere.radius=Math.sqrt(a),isNaN(this.boundingSphere.radius)&&Ua('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,n=this.attributes;if(e===null||n.position===void 0||n.normal===void 0||n.uv===void 0){Ua("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const r=n.position,a=n.normal,s=n.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Ds(new Float32Array(4*r.count),4));const o=this.getAttribute("tangent"),l=[],c=[];for(let j=0;j<r.count;j++)l[j]=new ft,c[j]=new ft;const u=new ft,d=new ft,h=new ft,f=new Un,p=new Un,x=new Un,v=new ft,g=new ft;function y(j,P,E){u.fromBufferAttribute(r,j),d.fromBufferAttribute(r,P),h.fromBufferAttribute(r,E),f.fromBufferAttribute(s,j),p.fromBufferAttribute(s,P),x.fromBufferAttribute(s,E),d.sub(u),h.sub(u),p.sub(f),x.sub(f);const U=1/(p.x*x.y-x.x*p.y);isFinite(U)&&(v.copy(d).multiplyScalar(x.y).addScaledVector(h,-p.y).multiplyScalar(U),g.copy(h).multiplyScalar(p.x).addScaledVector(d,-x.x).multiplyScalar(U),l[j].add(v),l[P].add(v),l[E].add(v),c[j].add(g),c[P].add(g),c[E].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let j=0,P=_.length;j<P;++j){const E=_[j],U=E.start,L=E.count;for(let B=U,D=U+L;B<D;B+=3)y(e.getX(B+0),e.getX(B+1),e.getX(B+2))}const N=new ft,k=new ft,A=new ft,M=new ft;function C(j){A.fromBufferAttribute(a,j),M.copy(A);const P=l[j];N.copy(P),N.sub(A.multiplyScalar(A.dot(P))).normalize(),k.crossVectors(M,P);const U=k.dot(c[j])<0?-1:1;o.setXYZW(j,N.x,N.y,N.z,U)}for(let j=0,P=_.length;j<P;++j){const E=_[j],U=E.start,L=E.count;for(let B=U,D=U+L;B<D;B+=3)C(e.getX(B+0)),C(e.getX(B+1)),C(e.getX(B+2))}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let r=this.getAttribute("normal");if(r===void 0)r=new Ds(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let f=0,p=r.count;f<p;f++)r.setXYZ(f,0,0,0);const a=new ft,s=new ft,o=new ft,l=new ft,c=new ft,u=new ft,d=new ft,h=new ft;if(e)for(let f=0,p=e.count;f<p;f+=3){const x=e.getX(f+0),v=e.getX(f+1),g=e.getX(f+2);a.fromBufferAttribute(n,x),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,g),d.subVectors(o,s),h.subVectors(a,s),d.cross(h),l.fromBufferAttribute(r,x),c.fromBufferAttribute(r,v),u.fromBufferAttribute(r,g),l.add(d),c.add(d),u.add(d),r.setXYZ(x,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.setXYZ(g,u.x,u.y,u.z)}else for(let f=0,p=n.count;f<p;f+=3)a.fromBufferAttribute(n,f+0),s.fromBufferAttribute(n,f+1),o.fromBufferAttribute(n,f+2),d.subVectors(o,s),h.subVectors(a,s),d.cross(h),r.setXYZ(f+0,d.x,d.y,d.z),r.setXYZ(f+1,d.x,d.y,d.z),r.setXYZ(f+2,d.x,d.y,d.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Ai.fromBufferAttribute(e,n),Ai.normalize(),e.setXYZ(n,Ai.x,Ai.y,Ai.z)}toNonIndexed(){function e(l,c){const u=l.array,d=l.itemSize,h=l.normalized,f=new u.constructor(c.length*d);let p=0,x=0;for(let v=0,g=c.length;v<g;v++){l.isInterleavedBufferAttribute?p=c[v]*l.data.stride+l.offset:p=c[v]*d;for(let y=0;y<d;y++)f[x++]=u[p++]}return new Ds(f,d,h)}if(this.index===null)return vn("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new eY,r=this.index.array,a=this.attributes;for(const l in a){const c=a[l],u=e(c,r);n.setAttribute(l,u)}const s=this.morphAttributes;for(const l in s){const c=[],u=s[l];for(let d=0,h=u.length;d<h;d++){const f=u[d],p=e(f,r);c.push(p)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const u=o[l];n.addGroup(u.start,u.count,u.materialIndex)}return n}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const u in c)c[u]!==void 0&&(e[u]=c[u]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const c in r){const u=r[c];e.data.attributes[c]=u.toJSON(e.data)}const a={};let s=!1;for(const c in this.morphAttributes){const u=this.morphAttributes[c],d=[];for(let h=0,f=u.length;h<f;h++){const p=u[h];d.push(p.toJSON(e.data))}d.length>0&&(a[c]=d,s=!0)}s&&(e.data.morphAttributes=a,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const l=this.boundingSphere;return l!==null&&(e.data.boundingSphere=l.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone());const a=e.attributes;for(const u in a){const d=a[u];this.setAttribute(u,d.clone(n))}const s=e.morphAttributes;for(const u in s){const d=[],h=s[u];for(let f=0,p=h.length;f<p;f++)d.push(h[f].clone(n));this.morphAttributes[u]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let u=0,d=o.length;u<d;u++){const h=o[u];this.addGroup(h.start,h.count,h.materialIndex)}const l=e.boundingBox;l!==null&&(this.boundingBox=l.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}};const u8=new ri,Tm=new VF,pS=new rk,d8=new ft,gS=new ft,bS=new ft,xS=new ft,cP=new ft,yS=new ft,h8=new ft,vS=new ft;let Sl=class extends Lo{constructor(e=new wl,n=new qF){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=n,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const l=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,a=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(a,e);const l=this.morphTargetInfluences;if(s&&l){yS.set(0,0,0);for(let c=0,u=s.length;c<u;c++){const d=l[c],h=s[c];d!==0&&(cP.fromBufferAttribute(h,e),o?yS.addScaledVector(cP,d):yS.addScaledVector(cP.sub(n),d))}n.add(yS)}return n}raycast(e,n){const r=this.geometry,a=this.material,s=this.matrixWorld;a!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),pS.copy(r.boundingSphere),pS.applyMatrix4(s),Tm.copy(e.ray).recast(e.near),!(pS.containsPoint(Tm.origin)===!1&&(Tm.intersectSphere(pS,d8)===null||Tm.origin.distanceToSquared(d8)>(e.far-e.near)**2))&&(u8.copy(s).invert(),Tm.copy(e.ray).applyMatrix4(u8),!(r.boundingBox!==null&&Tm.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Tm)))}_computeIntersections(e,n,r){let a;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,u=s.attributes.uv,d=s.attributes.uv1,h=s.attributes.normal,f=s.groups,p=s.drawRange;if(l!==null)if(Array.isArray(o))for(let x=0,v=f.length;x<v;x++){const g=f[x],y=o[g.materialIndex],_=Math.max(g.start,p.start),N=Math.min(l.count,Math.min(g.start+g.count,p.start+p.count));for(let k=_,A=N;k<A;k+=3){const M=l.getX(k),C=l.getX(k+1),j=l.getX(k+2);a=wS(this,y,e,r,u,d,h,M,C,j),a&&(a.faceIndex=Math.floor(k/3),a.face.materialIndex=g.materialIndex,n.push(a))}}else{const x=Math.max(0,p.start),v=Math.min(l.count,p.start+p.count);for(let g=x,y=v;g<y;g+=3){const _=l.getX(g),N=l.getX(g+1),k=l.getX(g+2);a=wS(this,o,e,r,u,d,h,_,N,k),a&&(a.faceIndex=Math.floor(g/3),n.push(a))}}else if(c!==void 0)if(Array.isArray(o))for(let x=0,v=f.length;x<v;x++){const g=f[x],y=o[g.materialIndex],_=Math.max(g.start,p.start),N=Math.min(c.count,Math.min(g.start+g.count,p.start+p.count));for(let k=_,A=N;k<A;k+=3){const M=k,C=k+1,j=k+2;a=wS(this,y,e,r,u,d,h,M,C,j),a&&(a.faceIndex=Math.floor(k/3),a.face.materialIndex=g.materialIndex,n.push(a))}}else{const x=Math.max(0,p.start),v=Math.min(c.count,p.start+p.count);for(let g=x,y=v;g<y;g+=3){const _=g,N=g+1,k=g+2;a=wS(this,o,e,r,u,d,h,_,N,k),a&&(a.faceIndex=Math.floor(g/3),n.push(a))}}}};function zbe(t,e,n,r,a,s,o,l){let c;if(e.side===to?c=r.intersectTriangle(o,s,a,!0,l):c=r.intersectTriangle(a,s,o,e.side===qh,l),c===null)return null;vS.copy(l),vS.applyMatrix4(t.matrixWorld);const u=n.ray.origin.distanceTo(vS);return u<n.near||u>n.far?null:{distance:u,point:vS.clone(),object:t}}function wS(t,e,n,r,a,s,o,l,c,u){t.getVertexPosition(l,gS),t.getVertexPosition(c,bS),t.getVertexPosition(u,xS);const d=zbe(t,e,n,r,gS,bS,xS,h8);if(d){const h=new ft;ay.getBarycoord(h8,gS,bS,xS,h),a&&(d.uv=ay.getInterpolatedAttribute(a,l,c,u,h,new Un)),s&&(d.uv1=ay.getInterpolatedAttribute(s,l,c,u,h,new Un)),o&&(d.normal=ay.getInterpolatedAttribute(o,l,c,u,h,new ft),d.normal.dot(r.direction)>0&&d.normal.multiplyScalar(-1));const f={a:l,b:c,c:u,normal:new ft,materialIndex:0};ay.getNormal(gS,bS,xS,f.normal),d.face=f,d.barycoord=h}return d}let GF=class tY extends wl{constructor(e=1,n=1,r=1,a=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:a,heightSegments:s,depthSegments:o};const l=this;a=Math.floor(a),s=Math.floor(s),o=Math.floor(o);const c=[],u=[],d=[],h=[];let f=0,p=0;x("z","y","x",-1,-1,r,n,e,o,s,0),x("z","y","x",1,-1,r,n,-e,o,s,1),x("x","z","y",1,1,e,r,n,a,o,2),x("x","z","y",1,-1,e,r,-n,a,o,3),x("x","y","z",1,-1,e,n,r,a,s,4),x("x","y","z",-1,-1,e,n,-r,a,s,5),this.setIndex(c),this.setAttribute("position",new jo(u,3)),this.setAttribute("normal",new jo(d,3)),this.setAttribute("uv",new jo(h,2));function x(v,g,y,_,N,k,A,M,C,j,P){const E=k/C,U=A/j,L=k/2,B=A/2,D=M/2,$=C+1,G=j+1;let z=0,W=0;const X=new ft;for(let ae=0;ae<G;ae++){const H=ae*U-B;for(let K=0;K<$;K++){const te=K*E-L;X[v]=te*_,X[g]=H*N,X[y]=D,u.push(X.x,X.y,X.z),X[v]=0,X[g]=0,X[y]=M>0?1:-1,d.push(X.x,X.y,X.z),h.push(K/C),h.push(1-ae/j),z+=1}}for(let ae=0;ae<j;ae++)for(let H=0;H<C;H++){const K=f+H+$*ae,te=f+H+$*(ae+1),Z=f+(H+1)+$*(ae+1),ve=f+(H+1)+$*ae;c.push(K,te,ve),c.push(te,Z,ve),W+=6}l.addGroup(p,W,P),p+=W,f+=z}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new tY(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function xb(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const a=t[n][r];a&&(a.isColor||a.isMatrix3||a.isMatrix4||a.isVector2||a.isVector3||a.isVector4||a.isTexture||a.isQuaternion)?a.isRenderTargetTexture?(vn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=a.clone():Array.isArray(a)?e[n][r]=a.slice():e[n][r]=a}}return e}function ks(t){const e={};for(let n=0;n<t.length;n++){const r=xb(t[n]);for(const a in r)e[a]=r[a]}return e}function Ube(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function nY(t){const e=t.getRenderTarget();return e===null?t.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:cr.workingColorSpace}const Bbe={clone:xb,merge:ks};var Hbe=`void main() {
  11. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  12. }`,$be=`void main() {
  13. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  14. }`;let ad=class extends Wb{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Hbe,this.fragmentShader=$be,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=xb(e.uniforms),this.uniformsGroups=Ube(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const n=super.toJSON(e);n.glslVersion=this.glslVersion,n.uniforms={};for(const a in this.uniforms){const o=this.uniforms[a].value;o&&o.isTexture?n.uniforms[a]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[a]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[a]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[a]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[a]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[a]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[a]={type:"m4",value:o.toArray()}:n.uniforms[a]={value:o}}Object.keys(this.defines).length>0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const a in this.extensions)this.extensions[a]===!0&&(r[a]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}},rY=class extends Lo{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ri,this.projectionMatrix=new ri,this.projectionMatrixInverse=new ri,this.coordinateSystem=kc,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}};const Wd=new ft,m8=new Un,f8=new Un;let sl=class extends rY{constructor(e=50,n=1,r=.1,a=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=a,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=J3*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(K_*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return J3*2*Math.atan(Math.tan(K_*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,n,r){Wd.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Wd.x,Wd.y).multiplyScalar(-e/Wd.z),Wd.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(Wd.x,Wd.y).multiplyScalar(-e/Wd.z)}getViewSize(e,n){return this.getViewBounds(e,m8,f8),n.subVectors(f8,m8)}setViewOffset(e,n,r,a,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(K_*.5*this.fov)/this.zoom,r=2*n,a=this.aspect*r,s=-.5*a;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,u=o.fullHeight;s+=o.offsetX*a/c,n-=o.offsetY*r/u,a*=o.width/c,r*=o.height/u}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+a,n,n-r,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}};const Jp=-90,eg=1;let Vbe=class extends Lo{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const a=new sl(Jp,eg,e,n);a.layers=this.layers,this.add(a);const s=new sl(Jp,eg,e,n);s.layers=this.layers,this.add(s);const o=new sl(Jp,eg,e,n);o.layers=this.layers,this.add(o);const l=new sl(Jp,eg,e,n);l.layers=this.layers,this.add(l);const c=new sl(Jp,eg,e,n);c.layers=this.layers,this.add(c);const u=new sl(Jp,eg,e,n);u.layers=this.layers,this.add(u)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,a,s,o,l,c]=n;for(const u of n)this.remove(u);if(e===kc)r.up.set(0,1,0),r.lookAt(1,0,0),a.up.set(0,1,0),a.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),l.up.set(0,1,0),l.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===T1)r.up.set(0,-1,0),r.lookAt(-1,0,0),a.up.set(0,-1,0),a.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),l.up.set(0,-1,0),l.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const u of n)this.add(u),u.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:a}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,u,d]=this.children,h=e.getRenderTarget(),f=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,a),e.render(n,s),e.setRenderTarget(r,1,a),e.render(n,o),e.setRenderTarget(r,2,a),e.render(n,l),e.setRenderTarget(r,3,a),e.render(n,c),e.setRenderTarget(r,4,a),e.render(n,u),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,a),e.render(n,d),e.setRenderTarget(h,f,p),e.xr.enabled=x,r.texture.needsPMREMUpdate=!0}},aY=class extends ac{constructor(e=[],n=pb,r,a,s,o,l,c,u,d){super(e,n,r,a,s,o,l,c,u,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},qbe=class extends Of{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},a=[r,r,r,r,r,r];this.texture=new aY(a),this._setTextureOptions(n),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:`
  15. varying vec3 vWorldDirection;
  16. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  17. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  18. }
  19. void main() {
  20. vWorldDirection = transformDirection( position, modelMatrix );
  21. #include <begin_vertex>
  22. #include <project_vertex>
  23. }
  24. `,fragmentShader:`
  25. uniform sampler2D tEquirect;
  26. varying vec3 vWorldDirection;
  27. #include <common>
  28. void main() {
  29. vec3 direction = normalize( vWorldDirection );
  30. vec2 sampleUV = equirectUv( direction );
  31. gl_FragColor = texture2D( tEquirect, sampleUV );
  32. }
  33. `},a=new GF(5,5,5),s=new ad({name:"CubemapFromEquirect",uniforms:xb(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:to,blending:Vu});s.uniforms.tEquirect.value=n;const o=new Sl(a,s),l=n.minFilter;return n.minFilter===tf&&(n.minFilter=hl),new Vbe(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n=!0,r=!0,a=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,a);e.setRenderTarget(s)}},zg=class extends Lo{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Gbe={type:"move"};let uP=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new zg,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new zg,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ft,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ft),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new zg,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ft,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ft),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let a=null,s=null,o=null;const l=this._targetRay,c=this._grip,u=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(u&&e.hand){o=!0;for(const v of e.hand.values()){const g=n.getJointPose(v,r),y=this._getHandJoint(u,v);g!==null&&(y.matrix.fromArray(g.transform.matrix),y.matrix.decompose(y.position,y.rotation,y.scale),y.matrixWorldNeedsUpdate=!0,y.jointRadius=g.radius),y.visible=g!==null}const d=u.joints["index-finger-tip"],h=u.joints["thumb-tip"],f=d.position.distanceTo(h.position),p=.02,x=.005;u.inputState.pinching&&f>p+x?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&f<=p-x&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(a=n.getPose(e.targetRaySpace,r),a===null&&s!==null&&(a=s),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(Gbe)))}return l!==null&&(l.visible=a!==null),c!==null&&(c.visible=s!==null),u!==null&&(u.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new zg;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}},Wbe=class extends Lo{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Gh,this.environmentIntensity=1,this.environmentRotation=new Gh,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(n.object.environmentIntensity=this.environmentIntensity),n.object.environmentRotation=this.environmentRotation.toArray(),n}},Kbe=class extends ac{constructor(e=null,n=1,r=1,a,s,o,l,c,u=Eo,d=Eo,h,f){super(null,o,l,c,u,d,a,s,h,f),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};const dP=new ft,Xbe=new ft,Ybe=new Hn;let ih=class{constructor(e=new ft(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,a){return this.normal.set(e,n,r),this.constant=a,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const a=dP.subVectors(r,n).cross(Xbe.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(a,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta(dP),a=this.normal.dot(r);if(a===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/a;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||Ybe.getNormalMatrix(e),a=this.coplanarPoint(dP).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-a.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}};const Mm=new rk,Qbe=new Un(.5,.5),SS=new ft;let WF=class{constructor(e=new ih,n=new ih,r=new ih,a=new ih,s=new ih,o=new ih){this.planes=[e,n,r,a,s,o]}set(e,n,r,a,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(a),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=kc,r=!1){const a=this.planes,s=e.elements,o=s[0],l=s[1],c=s[2],u=s[3],d=s[4],h=s[5],f=s[6],p=s[7],x=s[8],v=s[9],g=s[10],y=s[11],_=s[12],N=s[13],k=s[14],A=s[15];if(a[0].setComponents(u-o,p-d,y-x,A-_).normalize(),a[1].setComponents(u+o,p+d,y+x,A+_).normalize(),a[2].setComponents(u+l,p+h,y+v,A+N).normalize(),a[3].setComponents(u-l,p-h,y-v,A-N).normalize(),r)a[4].setComponents(c,f,g,k).normalize(),a[5].setComponents(u-c,p-f,y-g,A-k).normalize();else if(a[4].setComponents(u-c,p-f,y-g,A-k).normalize(),n===kc)a[5].setComponents(u+c,p+f,y+g,A+k).normalize();else if(n===T1)a[5].setComponents(c,f,g,k).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Mm.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Mm.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Mm)}intersectsSprite(e){Mm.center.set(0,0,0);const n=Qbe.distanceTo(e.center);return Mm.radius=.7071067811865476+n,Mm.applyMatrix4(e.matrixWorld),this.intersectsSphere(Mm)}intersectsSphere(e){const n=this.planes,r=e.center,a=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<a)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const a=n[r];if(SS.x=a.normal.x>0?e.max.x:e.min.x,SS.y=a.normal.y>0?e.max.y:e.min.y,SS.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(SS)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},iY=class extends Wb{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new $n(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}};const P1=new ft,E1=new ft,p8=new ri,sy=new VF,_S=new rk,hP=new ft,g8=new ft;let Zbe=class extends Lo{constructor(e=new wl,n=new iY){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=n,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[0];for(let a=1,s=n.count;a<s;a++)P1.fromBufferAttribute(n,a-1),E1.fromBufferAttribute(n,a),r[a]=r[a-1],r[a]+=P1.distanceTo(E1);e.setAttribute("lineDistance",new jo(r,1))}else vn("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,a=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),_S.copy(r.boundingSphere),_S.applyMatrix4(a),_S.radius+=s,e.ray.intersectsSphere(_S)===!1)return;p8.copy(a).invert(),sy.copy(e.ray).applyMatrix4(p8);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,u=this.isLineSegments?2:1,d=r.index,f=r.attributes.position;if(d!==null){const p=Math.max(0,o.start),x=Math.min(d.count,o.start+o.count);for(let v=p,g=x-1;v<g;v+=u){const y=d.getX(v),_=d.getX(v+1),N=NS(this,e,sy,c,y,_,v);N&&n.push(N)}if(this.isLineLoop){const v=d.getX(x-1),g=d.getX(p),y=NS(this,e,sy,c,v,g,x-1);y&&n.push(y)}}else{const p=Math.max(0,o.start),x=Math.min(f.count,o.start+o.count);for(let v=p,g=x-1;v<g;v+=u){const y=NS(this,e,sy,c,v,v+1,v);y&&n.push(y)}if(this.isLineLoop){const v=NS(this,e,sy,c,x-1,p,x-1);v&&n.push(v)}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const l=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};function NS(t,e,n,r,a,s,o){const l=t.geometry.attributes.position;if(P1.fromBufferAttribute(l,a),E1.fromBufferAttribute(l,s),n.distanceSqToSegment(P1,E1,hP,g8)>r)return;hP.applyMatrix4(t.matrixWorld);const u=e.ray.origin.distanceTo(hP);if(!(u<e.near||u>e.far))return{distance:u,point:g8.clone().applyMatrix4(t.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:t}}const b8=new ft,x8=new ft;let Jbe=class extends Zbe{constructor(e,n){super(e,n),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[];for(let a=0,s=n.count;a<s;a+=2)b8.fromBufferAttribute(n,a),x8.fromBufferAttribute(n,a+1),r[a]=a===0?0:r[a-1],r[a+1]=r[a]+b8.distanceTo(x8);e.setAttribute("lineDistance",new jo(r,1))}else vn("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},sY=class extends ac{constructor(e,n,r=Ff,a,s,o,l=Eo,c=Eo,u,d=Sv,h=1){if(d!==Sv&&d!==_v)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const f={width:e,height:n,depth:h};super(f,a,s,o,l,c,d,r,u),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new $F(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const n=super.toJSON(e);return this.compareFunction!==null&&(n.compareFunction=this.compareFunction),n}};class oY extends ac{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}let KF=class lY extends wl{constructor(e=1,n=1,r=1,a=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:a};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(a),u=l+1,d=c+1,h=e/l,f=n/c,p=[],x=[],v=[],g=[];for(let y=0;y<d;y++){const _=y*f-o;for(let N=0;N<u;N++){const k=N*h-s;x.push(k,-_,0),v.push(0,0,1),g.push(N/l),g.push(1-y/c)}}for(let y=0;y<c;y++)for(let _=0;_<l;_++){const N=_+u*y,k=_+u*(y+1),A=_+1+u*(y+1),M=_+1+u*y;p.push(N,k,M),p.push(k,A,M)}this.setIndex(p),this.setAttribute("position",new jo(x,3)),this.setAttribute("normal",new jo(v,3)),this.setAttribute("uv",new jo(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new lY(e.width,e.height,e.widthSegments,e.heightSegments)}};class cY extends Wb{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new $n(16777215),this.specular=new $n(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new $n(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=BX,this.normalScale=new Un(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Gh,this.combine=FF,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}let exe=class extends Wb{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=cbe,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},txe=class extends Wb{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};const y8={enabled:!1,files:{},add:function(t,e){this.enabled!==!1&&(this.files[t]=e)},get:function(t){if(this.enabled!==!1)return this.files[t]},remove:function(t){delete this.files[t]},clear:function(){this.files={}}};class nxe{constructor(e,n,r){const a=this;let s=!1,o=0,l=0,c;const u=[];this.onStart=void 0,this.onLoad=e,this.onProgress=n,this.onError=r,this._abortController=null,this.itemStart=function(d){l++,s===!1&&a.onStart!==void 0&&a.onStart(d,o,l),s=!0},this.itemEnd=function(d){o++,a.onProgress!==void 0&&a.onProgress(d,o,l),o===l&&(s=!1,a.onLoad!==void 0&&a.onLoad())},this.itemError=function(d){a.onError!==void 0&&a.onError(d)},this.resolveURL=function(d){return c?c(d):d},this.setURLModifier=function(d){return c=d,this},this.addHandler=function(d,h){return u.push(d,h),this},this.removeHandler=function(d){const h=u.indexOf(d);return h!==-1&&u.splice(h,2),this},this.getHandler=function(d){for(let h=0,f=u.length;h<f;h+=2){const p=u[h],x=u[h+1];if(p.global&&(p.lastIndex=0),p.test(d))return x}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const rxe=new nxe;class XF{constructor(e){this.manager=e!==void 0?e:rxe,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,n){const r=this;return new Promise(function(a,s){r.load(e,a,n,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}}XF.DEFAULT_MATERIAL_NAME="__DEFAULT";const bu={};class axe extends Error{constructor(e,n){super(e),this.response=n}}class ixe extends XF{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,n,r,a){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=y8.get(`file:${e}`);if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{n&&n(s),this.manager.itemEnd(e)},0),s;if(bu[e]!==void 0){bu[e].push({onLoad:n,onProgress:r,onError:a});return}bu[e]=[],bu[e].push({onLoad:n,onProgress:r,onError:a});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),l=this.mimeType,c=this.responseType;fetch(o).then(u=>{if(u.status===200||u.status===0){if(u.status===0&&vn("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||u.body===void 0||u.body.getReader===void 0)return u;const d=bu[e],h=u.body.getReader(),f=u.headers.get("X-File-Size")||u.headers.get("Content-Length"),p=f?parseInt(f):0,x=p!==0;let v=0;const g=new ReadableStream({start(y){_();function _(){h.read().then(({done:N,value:k})=>{if(N)y.close();else{v+=k.byteLength;const A=new ProgressEvent("progress",{lengthComputable:x,loaded:v,total:p});for(let M=0,C=d.length;M<C;M++){const j=d[M];j.onProgress&&j.onProgress(A)}y.enqueue(k),_()}},N=>{y.error(N)})}}});return new Response(g)}else throw new axe(`fetch for "${u.url}" responded with ${u.status}: ${u.statusText}`,u)}).then(u=>{switch(c){case"arraybuffer":return u.arrayBuffer();case"blob":return u.blob();case"document":return u.text().then(d=>new DOMParser().parseFromString(d,l));case"json":return u.json();default:if(l==="")return u.text();{const h=/charset="?([^;"\s]*)"?/i.exec(l),f=h&&h[1]?h[1].toLowerCase():void 0,p=new TextDecoder(f);return u.arrayBuffer().then(x=>p.decode(x))}}}).then(u=>{y8.add(`file:${e}`,u);const d=bu[e];delete bu[e];for(let h=0,f=d.length;h<f;h++){const p=d[h];p.onLoad&&p.onLoad(u)}}).catch(u=>{const d=bu[e];if(d===void 0)throw this.manager.itemError(e),u;delete bu[e];for(let h=0,f=d.length;h<f;h++){const p=d[h];p.onError&&p.onError(u)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}let uY=class extends Lo{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new $n(e),this.intensity=n}dispose(){}copy(e,n){return super.copy(e,n),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const n=super.toJSON(e);return n.object.color=this.color.getHex(),n.object.intensity=this.intensity,this.groundColor!==void 0&&(n.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(n.object.distance=this.distance),this.angle!==void 0&&(n.object.angle=this.angle),this.decay!==void 0&&(n.object.decay=this.decay),this.penumbra!==void 0&&(n.object.penumbra=this.penumbra),this.shadow!==void 0&&(n.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(n.object.target=this.target.uuid),n}};const mP=new ri,v8=new ft,w8=new ft;let sxe=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Un(512,512),this.mapType=Lc,this.map=null,this.mapPass=null,this.matrix=new ri,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new WF,this._frameExtents=new Un(1,1),this._viewportCount=1,this._viewports=[new Za(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;v8.setFromMatrixPosition(e.matrixWorld),n.position.copy(v8),w8.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(w8),n.updateMatrixWorld(),mP.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(mP,n.coordinateSystem,n.reversedDepth),n.reversedDepth?r.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(mP)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},dY=class extends rY{constructor(e=-1,n=1,r=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=a,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,a,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=a+n,c=a-n;if(this.view!==null&&this.view.enabled){const u=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=u*this.view.offsetX,o=s+u*this.view.width,l-=d*this.view.offsetY,c=l-d*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}};class oxe extends sxe{constructor(){super(new dY(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class S8 extends uY{constructor(e,n){super(e,n),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Lo.DEFAULT_UP),this.updateMatrix(),this.target=new Lo,this.shadow=new oxe}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}let lxe=class extends uY{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}},cxe=class extends sl{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},_8=class{constructor(e=1,n=0,r=0){this.radius=e,this.phi=n,this.theta=r}set(e,n,r){return this.radius=e,this.phi=n,this.theta=r,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Yn(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,n,r){return this.radius=Math.sqrt(e*e+n*n+r*r),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,r),this.phi=Math.acos(Yn(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};class uxe extends Jbe{constructor(e=10,n=10,r=4473924,a=8947848){r=new $n(r),a=new $n(a);const s=n/2,o=e/n,l=e/2,c=[],u=[];for(let f=0,p=0,x=-l;f<=n;f++,x+=o){c.push(-l,0,x,l,0,x),c.push(x,0,-l,x,0,l);const v=f===s?r:a;v.toArray(u,p),p+=3,v.toArray(u,p),p+=3,v.toArray(u,p),p+=3,v.toArray(u,p),p+=3}const d=new wl;d.setAttribute("position",new jo(c,3)),d.setAttribute("color",new jo(u,3));const h=new iY({vertexColors:!0,toneMapped:!1});super(d,h),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class dxe extends np{constructor(e,n=null){super(),this.object=e,this.domElement=n,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){vn("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function N8(t,e,n,r){const a=hxe(r);switch(n){case IX:return t*e;case UX:return t*e/a.components*a.byteLength;case zF:return t*e/a.components*a.byteLength;case UF:return t*e*2/a.components*a.byteLength;case BF:return t*e*2/a.components*a.byteLength;case zX:return t*e*3/a.components*a.byteLength;case ql:return t*e*4/a.components*a.byteLength;case HF:return t*e*4/a.components*a.byteLength;case V_:case q_:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case G_:case W_:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case k3:case T3:return Math.max(t,16)*Math.max(e,8)/4;case C3:case A3:return Math.max(t,8)*Math.max(e,8)/2;case M3:case P3:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*8;case E3:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case j3:return Math.floor((t+3)/4)*Math.floor((e+3)/4)*16;case D3:return Math.floor((t+4)/5)*Math.floor((e+3)/4)*16;case R3:return Math.floor((t+4)/5)*Math.floor((e+4)/5)*16;case F3:return Math.floor((t+5)/6)*Math.floor((e+4)/5)*16;case L3:return Math.floor((t+5)/6)*Math.floor((e+5)/6)*16;case O3:return Math.floor((t+7)/8)*Math.floor((e+4)/5)*16;case I3:return Math.floor((t+7)/8)*Math.floor((e+5)/6)*16;case z3:return Math.floor((t+7)/8)*Math.floor((e+7)/8)*16;case U3:return Math.floor((t+9)/10)*Math.floor((e+4)/5)*16;case B3:return Math.floor((t+9)/10)*Math.floor((e+5)/6)*16;case H3:return Math.floor((t+9)/10)*Math.floor((e+7)/8)*16;case $3:return Math.floor((t+9)/10)*Math.floor((e+9)/10)*16;case V3:return Math.floor((t+11)/12)*Math.floor((e+9)/10)*16;case q3:return Math.floor((t+11)/12)*Math.floor((e+11)/12)*16;case G3:case W3:case K3:return Math.ceil(t/4)*Math.ceil(e/4)*16;case X3:case Y3:return Math.ceil(t/4)*Math.ceil(e/4)*8;case Q3:case Z3:return Math.ceil(t/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function hxe(t){switch(t){case Lc:case RX:return{byteLength:1,components:1};case vv:case FX:case Gb:return{byteLength:2,components:1};case OF:case IF:return{byteLength:2,components:4};case Ff:case LF:case Iu:return{byteLength:4,components:1};case LX:case OX:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${t}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:RF}}));typeof window<"u"&&(window.__THREE__?vn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=RF);function hY(){let t=null,e=!1,n=null,r=null;function a(s,o){n(s,o),r=t.requestAnimationFrame(a)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(a),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function mxe(t){const e=new WeakMap;function n(l,c){const u=l.array,d=l.usage,h=u.byteLength,f=t.createBuffer();t.bindBuffer(c,f),t.bufferData(c,u,d),l.onUploadCallback();let p;if(u instanceof Float32Array)p=t.FLOAT;else if(typeof Float16Array<"u"&&u instanceof Float16Array)p=t.HALF_FLOAT;else if(u instanceof Uint16Array)l.isFloat16BufferAttribute?p=t.HALF_FLOAT:p=t.UNSIGNED_SHORT;else if(u instanceof Int16Array)p=t.SHORT;else if(u instanceof Uint32Array)p=t.UNSIGNED_INT;else if(u instanceof Int32Array)p=t.INT;else if(u instanceof Int8Array)p=t.BYTE;else if(u instanceof Uint8Array)p=t.UNSIGNED_BYTE;else if(u instanceof Uint8ClampedArray)p=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+u);return{buffer:f,type:p,bytesPerElement:u.BYTES_PER_ELEMENT,version:l.version,size:h}}function r(l,c,u){const d=c.array,h=c.updateRanges;if(t.bindBuffer(u,l),h.length===0)t.bufferSubData(u,0,d);else{h.sort((p,x)=>p.start-x.start);let f=0;for(let p=1;p<h.length;p++){const x=h[f],v=h[p];v.start<=x.start+x.count+1?x.count=Math.max(x.count,v.start+v.count-x.start):(++f,h[f]=v)}h.length=f+1;for(let p=0,x=h.length;p<x;p++){const v=h[p];t.bufferSubData(u,v.start*d.BYTES_PER_ELEMENT,d,v.start,v.count)}c.clearUpdateRanges()}c.onUploadCallback()}function a(l){return l.isInterleavedBufferAttribute&&(l=l.data),e.get(l)}function s(l){l.isInterleavedBufferAttribute&&(l=l.data);const c=e.get(l);c&&(t.deleteBuffer(c.buffer),e.delete(l))}function o(l,c){if(l.isInterleavedBufferAttribute&&(l=l.data),l.isGLBufferAttribute){const d=e.get(l);(!d||d.version<l.version)&&e.set(l,{buffer:l.buffer,type:l.type,bytesPerElement:l.elementSize,version:l.version});return}const u=e.get(l);if(u===void 0)e.set(l,n(l,c));else if(u.version<l.version){if(u.size!==l.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");r(u.buffer,l,c),u.version=l.version}}return{get:a,remove:s,update:o}}var fxe=`#ifdef USE_ALPHAHASH
  34. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  35. #endif`,pxe=`#ifdef USE_ALPHAHASH
  36. const float ALPHA_HASH_SCALE = 0.05;
  37. float hash2D( vec2 value ) {
  38. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  39. }
  40. float hash3D( vec3 value ) {
  41. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  42. }
  43. float getAlphaHashThreshold( vec3 position ) {
  44. float maxDeriv = max(
  45. length( dFdx( position.xyz ) ),
  46. length( dFdy( position.xyz ) )
  47. );
  48. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  49. vec2 pixScales = vec2(
  50. exp2( floor( log2( pixScale ) ) ),
  51. exp2( ceil( log2( pixScale ) ) )
  52. );
  53. vec2 alpha = vec2(
  54. hash3D( floor( pixScales.x * position.xyz ) ),
  55. hash3D( floor( pixScales.y * position.xyz ) )
  56. );
  57. float lerpFactor = fract( log2( pixScale ) );
  58. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  59. float a = min( lerpFactor, 1.0 - lerpFactor );
  60. vec3 cases = vec3(
  61. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  62. ( x - 0.5 * a ) / ( 1.0 - a ),
  63. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  64. );
  65. float threshold = ( x < ( 1.0 - a ) )
  66. ? ( ( x < a ) ? cases.x : cases.y )
  67. : cases.z;
  68. return clamp( threshold , 1.0e-6, 1.0 );
  69. }
  70. #endif`,gxe=`#ifdef USE_ALPHAMAP
  71. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  72. #endif`,bxe=`#ifdef USE_ALPHAMAP
  73. uniform sampler2D alphaMap;
  74. #endif`,xxe=`#ifdef USE_ALPHATEST
  75. #ifdef ALPHA_TO_COVERAGE
  76. diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
  77. if ( diffuseColor.a == 0.0 ) discard;
  78. #else
  79. if ( diffuseColor.a < alphaTest ) discard;
  80. #endif
  81. #endif`,yxe=`#ifdef USE_ALPHATEST
  82. uniform float alphaTest;
  83. #endif`,vxe=`#ifdef USE_AOMAP
  84. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  85. reflectedLight.indirectDiffuse *= ambientOcclusion;
  86. #if defined( USE_CLEARCOAT )
  87. clearcoatSpecularIndirect *= ambientOcclusion;
  88. #endif
  89. #if defined( USE_SHEEN )
  90. sheenSpecularIndirect *= ambientOcclusion;
  91. #endif
  92. #if defined( USE_ENVMAP ) && defined( STANDARD )
  93. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  94. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  95. #endif
  96. #endif`,wxe=`#ifdef USE_AOMAP
  97. uniform sampler2D aoMap;
  98. uniform float aoMapIntensity;
  99. #endif`,Sxe=`#ifdef USE_BATCHING
  100. #if ! defined( GL_ANGLE_multi_draw )
  101. #define gl_DrawID _gl_DrawID
  102. uniform int _gl_DrawID;
  103. #endif
  104. uniform highp sampler2D batchingTexture;
  105. uniform highp usampler2D batchingIdTexture;
  106. mat4 getBatchingMatrix( const in float i ) {
  107. int size = textureSize( batchingTexture, 0 ).x;
  108. int j = int( i ) * 4;
  109. int x = j % size;
  110. int y = j / size;
  111. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  112. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  113. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  114. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  115. return mat4( v1, v2, v3, v4 );
  116. }
  117. float getIndirectIndex( const in int i ) {
  118. int size = textureSize( batchingIdTexture, 0 ).x;
  119. int x = i % size;
  120. int y = i / size;
  121. return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
  122. }
  123. #endif
  124. #ifdef USE_BATCHING_COLOR
  125. uniform sampler2D batchingColorTexture;
  126. vec3 getBatchingColor( const in float i ) {
  127. int size = textureSize( batchingColorTexture, 0 ).x;
  128. int j = int( i );
  129. int x = j % size;
  130. int y = j / size;
  131. return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
  132. }
  133. #endif`,_xe=`#ifdef USE_BATCHING
  134. mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
  135. #endif`,Nxe=`vec3 transformed = vec3( position );
  136. #ifdef USE_ALPHAHASH
  137. vPosition = vec3( position );
  138. #endif`,Cxe=`vec3 objectNormal = vec3( normal );
  139. #ifdef USE_TANGENT
  140. vec3 objectTangent = vec3( tangent.xyz );
  141. #endif`,kxe=`float G_BlinnPhong_Implicit( ) {
  142. return 0.25;
  143. }
  144. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  145. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  146. }
  147. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  148. vec3 halfDir = normalize( lightDir + viewDir );
  149. float dotNH = saturate( dot( normal, halfDir ) );
  150. float dotVH = saturate( dot( viewDir, halfDir ) );
  151. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  152. float G = G_BlinnPhong_Implicit( );
  153. float D = D_BlinnPhong( shininess, dotNH );
  154. return F * ( G * D );
  155. } // validated`,Axe=`#ifdef USE_IRIDESCENCE
  156. const mat3 XYZ_TO_REC709 = mat3(
  157. 3.2404542, -0.9692660, 0.0556434,
  158. -1.5371385, 1.8760108, -0.2040259,
  159. -0.4985314, 0.0415560, 1.0572252
  160. );
  161. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  162. vec3 sqrtF0 = sqrt( fresnel0 );
  163. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  164. }
  165. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  166. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  167. }
  168. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  169. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  170. }
  171. vec3 evalSensitivity( float OPD, vec3 shift ) {
  172. float phase = 2.0 * PI * OPD * 1.0e-9;
  173. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  174. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  175. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  176. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  177. xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
  178. xyz /= 1.0685e-7;
  179. vec3 rgb = XYZ_TO_REC709 * xyz;
  180. return rgb;
  181. }
  182. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  183. vec3 I;
  184. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  185. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  186. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  187. if ( cosTheta2Sq < 0.0 ) {
  188. return vec3( 1.0 );
  189. }
  190. float cosTheta2 = sqrt( cosTheta2Sq );
  191. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  192. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  193. float T121 = 1.0 - R12;
  194. float phi12 = 0.0;
  195. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  196. float phi21 = PI - phi12;
  197. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  198. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  199. vec3 phi23 = vec3( 0.0 );
  200. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  201. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  202. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  203. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  204. vec3 phi = vec3( phi21 ) + phi23;
  205. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  206. vec3 r123 = sqrt( R123 );
  207. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  208. vec3 C0 = R12 + Rs;
  209. I = C0;
  210. vec3 Cm = Rs - T121;
  211. for ( int m = 1; m <= 2; ++ m ) {
  212. Cm *= r123;
  213. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  214. I += Cm * Sm;
  215. }
  216. return max( I, vec3( 0.0 ) );
  217. }
  218. #endif`,Txe=`#ifdef USE_BUMPMAP
  219. uniform sampler2D bumpMap;
  220. uniform float bumpScale;
  221. vec2 dHdxy_fwd() {
  222. vec2 dSTdx = dFdx( vBumpMapUv );
  223. vec2 dSTdy = dFdy( vBumpMapUv );
  224. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  225. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  226. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  227. return vec2( dBx, dBy );
  228. }
  229. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  230. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  231. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  232. vec3 vN = surf_norm;
  233. vec3 R1 = cross( vSigmaY, vN );
  234. vec3 R2 = cross( vN, vSigmaX );
  235. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  236. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  237. return normalize( abs( fDet ) * surf_norm - vGrad );
  238. }
  239. #endif`,Mxe=`#if NUM_CLIPPING_PLANES > 0
  240. vec4 plane;
  241. #ifdef ALPHA_TO_COVERAGE
  242. float distanceToPlane, distanceGradient;
  243. float clipOpacity = 1.0;
  244. #pragma unroll_loop_start
  245. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  246. plane = clippingPlanes[ i ];
  247. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  248. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  249. clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  250. if ( clipOpacity == 0.0 ) discard;
  251. }
  252. #pragma unroll_loop_end
  253. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  254. float unionClipOpacity = 1.0;
  255. #pragma unroll_loop_start
  256. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  257. plane = clippingPlanes[ i ];
  258. distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
  259. distanceGradient = fwidth( distanceToPlane ) / 2.0;
  260. unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
  261. }
  262. #pragma unroll_loop_end
  263. clipOpacity *= 1.0 - unionClipOpacity;
  264. #endif
  265. diffuseColor.a *= clipOpacity;
  266. if ( diffuseColor.a == 0.0 ) discard;
  267. #else
  268. #pragma unroll_loop_start
  269. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  270. plane = clippingPlanes[ i ];
  271. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  272. }
  273. #pragma unroll_loop_end
  274. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  275. bool clipped = true;
  276. #pragma unroll_loop_start
  277. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  278. plane = clippingPlanes[ i ];
  279. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  280. }
  281. #pragma unroll_loop_end
  282. if ( clipped ) discard;
  283. #endif
  284. #endif
  285. #endif`,Pxe=`#if NUM_CLIPPING_PLANES > 0
  286. varying vec3 vClipPosition;
  287. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  288. #endif`,Exe=`#if NUM_CLIPPING_PLANES > 0
  289. varying vec3 vClipPosition;
  290. #endif`,jxe=`#if NUM_CLIPPING_PLANES > 0
  291. vClipPosition = - mvPosition.xyz;
  292. #endif`,Dxe=`#if defined( USE_COLOR_ALPHA )
  293. diffuseColor *= vColor;
  294. #elif defined( USE_COLOR )
  295. diffuseColor.rgb *= vColor;
  296. #endif`,Rxe=`#if defined( USE_COLOR_ALPHA )
  297. varying vec4 vColor;
  298. #elif defined( USE_COLOR )
  299. varying vec3 vColor;
  300. #endif`,Fxe=`#if defined( USE_COLOR_ALPHA )
  301. varying vec4 vColor;
  302. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  303. varying vec3 vColor;
  304. #endif`,Lxe=`#if defined( USE_COLOR_ALPHA )
  305. vColor = vec4( 1.0 );
  306. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
  307. vColor = vec3( 1.0 );
  308. #endif
  309. #ifdef USE_COLOR
  310. vColor *= color;
  311. #endif
  312. #ifdef USE_INSTANCING_COLOR
  313. vColor.xyz *= instanceColor.xyz;
  314. #endif
  315. #ifdef USE_BATCHING_COLOR
  316. vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
  317. vColor.xyz *= batchingColor.xyz;
  318. #endif`,Oxe=`#define PI 3.141592653589793
  319. #define PI2 6.283185307179586
  320. #define PI_HALF 1.5707963267948966
  321. #define RECIPROCAL_PI 0.3183098861837907
  322. #define RECIPROCAL_PI2 0.15915494309189535
  323. #define EPSILON 1e-6
  324. #ifndef saturate
  325. #define saturate( a ) clamp( a, 0.0, 1.0 )
  326. #endif
  327. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  328. float pow2( const in float x ) { return x*x; }
  329. vec3 pow2( const in vec3 x ) { return x*x; }
  330. float pow3( const in float x ) { return x*x*x; }
  331. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  332. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  333. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  334. highp float rand( const in vec2 uv ) {
  335. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  336. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  337. return fract( sin( sn ) * c );
  338. }
  339. #ifdef HIGH_PRECISION
  340. float precisionSafeLength( vec3 v ) { return length( v ); }
  341. #else
  342. float precisionSafeLength( vec3 v ) {
  343. float maxComponent = max3( abs( v ) );
  344. return length( v / maxComponent ) * maxComponent;
  345. }
  346. #endif
  347. struct IncidentLight {
  348. vec3 color;
  349. vec3 direction;
  350. bool visible;
  351. };
  352. struct ReflectedLight {
  353. vec3 directDiffuse;
  354. vec3 directSpecular;
  355. vec3 indirectDiffuse;
  356. vec3 indirectSpecular;
  357. };
  358. #ifdef USE_ALPHAHASH
  359. varying vec3 vPosition;
  360. #endif
  361. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  362. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  363. }
  364. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  365. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  366. }
  367. bool isPerspectiveMatrix( mat4 m ) {
  368. return m[ 2 ][ 3 ] == - 1.0;
  369. }
  370. vec2 equirectUv( in vec3 dir ) {
  371. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  372. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  373. return vec2( u, v );
  374. }
  375. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  376. return RECIPROCAL_PI * diffuseColor;
  377. }
  378. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  379. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  380. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  381. }
  382. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  383. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  384. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  385. } // validated`,Ixe=`#ifdef ENVMAP_TYPE_CUBE_UV
  386. #define cubeUV_minMipLevel 4.0
  387. #define cubeUV_minTileSize 16.0
  388. float getFace( vec3 direction ) {
  389. vec3 absDirection = abs( direction );
  390. float face = - 1.0;
  391. if ( absDirection.x > absDirection.z ) {
  392. if ( absDirection.x > absDirection.y )
  393. face = direction.x > 0.0 ? 0.0 : 3.0;
  394. else
  395. face = direction.y > 0.0 ? 1.0 : 4.0;
  396. } else {
  397. if ( absDirection.z > absDirection.y )
  398. face = direction.z > 0.0 ? 2.0 : 5.0;
  399. else
  400. face = direction.y > 0.0 ? 1.0 : 4.0;
  401. }
  402. return face;
  403. }
  404. vec2 getUV( vec3 direction, float face ) {
  405. vec2 uv;
  406. if ( face == 0.0 ) {
  407. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  408. } else if ( face == 1.0 ) {
  409. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  410. } else if ( face == 2.0 ) {
  411. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  412. } else if ( face == 3.0 ) {
  413. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  414. } else if ( face == 4.0 ) {
  415. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  416. } else {
  417. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  418. }
  419. return 0.5 * ( uv + 1.0 );
  420. }
  421. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  422. float face = getFace( direction );
  423. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  424. mipInt = max( mipInt, cubeUV_minMipLevel );
  425. float faceSize = exp2( mipInt );
  426. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  427. if ( face > 2.0 ) {
  428. uv.y += faceSize;
  429. face -= 3.0;
  430. }
  431. uv.x += face * faceSize;
  432. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  433. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  434. uv.x *= CUBEUV_TEXEL_WIDTH;
  435. uv.y *= CUBEUV_TEXEL_HEIGHT;
  436. #ifdef texture2DGradEXT
  437. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  438. #else
  439. return texture2D( envMap, uv ).rgb;
  440. #endif
  441. }
  442. #define cubeUV_r0 1.0
  443. #define cubeUV_m0 - 2.0
  444. #define cubeUV_r1 0.8
  445. #define cubeUV_m1 - 1.0
  446. #define cubeUV_r4 0.4
  447. #define cubeUV_m4 2.0
  448. #define cubeUV_r5 0.305
  449. #define cubeUV_m5 3.0
  450. #define cubeUV_r6 0.21
  451. #define cubeUV_m6 4.0
  452. float roughnessToMip( float roughness ) {
  453. float mip = 0.0;
  454. if ( roughness >= cubeUV_r1 ) {
  455. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  456. } else if ( roughness >= cubeUV_r4 ) {
  457. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  458. } else if ( roughness >= cubeUV_r5 ) {
  459. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  460. } else if ( roughness >= cubeUV_r6 ) {
  461. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  462. } else {
  463. mip = - 2.0 * log2( 1.16 * roughness ); }
  464. return mip;
  465. }
  466. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  467. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  468. float mipF = fract( mip );
  469. float mipInt = floor( mip );
  470. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  471. if ( mipF == 0.0 ) {
  472. return vec4( color0, 1.0 );
  473. } else {
  474. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  475. return vec4( mix( color0, color1, mipF ), 1.0 );
  476. }
  477. }
  478. #endif`,zxe=`vec3 transformedNormal = objectNormal;
  479. #ifdef USE_TANGENT
  480. vec3 transformedTangent = objectTangent;
  481. #endif
  482. #ifdef USE_BATCHING
  483. mat3 bm = mat3( batchingMatrix );
  484. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  485. transformedNormal = bm * transformedNormal;
  486. #ifdef USE_TANGENT
  487. transformedTangent = bm * transformedTangent;
  488. #endif
  489. #endif
  490. #ifdef USE_INSTANCING
  491. mat3 im = mat3( instanceMatrix );
  492. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  493. transformedNormal = im * transformedNormal;
  494. #ifdef USE_TANGENT
  495. transformedTangent = im * transformedTangent;
  496. #endif
  497. #endif
  498. transformedNormal = normalMatrix * transformedNormal;
  499. #ifdef FLIP_SIDED
  500. transformedNormal = - transformedNormal;
  501. #endif
  502. #ifdef USE_TANGENT
  503. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  504. #ifdef FLIP_SIDED
  505. transformedTangent = - transformedTangent;
  506. #endif
  507. #endif`,Uxe=`#ifdef USE_DISPLACEMENTMAP
  508. uniform sampler2D displacementMap;
  509. uniform float displacementScale;
  510. uniform float displacementBias;
  511. #endif`,Bxe=`#ifdef USE_DISPLACEMENTMAP
  512. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  513. #endif`,Hxe=`#ifdef USE_EMISSIVEMAP
  514. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  515. #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
  516. emissiveColor = sRGBTransferEOTF( emissiveColor );
  517. #endif
  518. totalEmissiveRadiance *= emissiveColor.rgb;
  519. #endif`,$xe=`#ifdef USE_EMISSIVEMAP
  520. uniform sampler2D emissiveMap;
  521. #endif`,Vxe="gl_FragColor = linearToOutputTexel( gl_FragColor );",qxe=`vec4 LinearTransferOETF( in vec4 value ) {
  522. return value;
  523. }
  524. vec4 sRGBTransferEOTF( in vec4 value ) {
  525. return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
  526. }
  527. vec4 sRGBTransferOETF( in vec4 value ) {
  528. return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
  529. }`,Gxe=`#ifdef USE_ENVMAP
  530. #ifdef ENV_WORLDPOS
  531. vec3 cameraToFrag;
  532. if ( isOrthographic ) {
  533. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  534. } else {
  535. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  536. }
  537. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  538. #ifdef ENVMAP_MODE_REFLECTION
  539. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  540. #else
  541. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  542. #endif
  543. #else
  544. vec3 reflectVec = vReflect;
  545. #endif
  546. #ifdef ENVMAP_TYPE_CUBE
  547. vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  548. #else
  549. vec4 envColor = vec4( 0.0 );
  550. #endif
  551. #ifdef ENVMAP_BLENDING_MULTIPLY
  552. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  553. #elif defined( ENVMAP_BLENDING_MIX )
  554. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  555. #elif defined( ENVMAP_BLENDING_ADD )
  556. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  557. #endif
  558. #endif`,Wxe=`#ifdef USE_ENVMAP
  559. uniform float envMapIntensity;
  560. uniform float flipEnvMap;
  561. uniform mat3 envMapRotation;
  562. #ifdef ENVMAP_TYPE_CUBE
  563. uniform samplerCube envMap;
  564. #else
  565. uniform sampler2D envMap;
  566. #endif
  567. #endif`,Kxe=`#ifdef USE_ENVMAP
  568. uniform float reflectivity;
  569. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  570. #define ENV_WORLDPOS
  571. #endif
  572. #ifdef ENV_WORLDPOS
  573. varying vec3 vWorldPosition;
  574. uniform float refractionRatio;
  575. #else
  576. varying vec3 vReflect;
  577. #endif
  578. #endif`,Xxe=`#ifdef USE_ENVMAP
  579. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  580. #define ENV_WORLDPOS
  581. #endif
  582. #ifdef ENV_WORLDPOS
  583. varying vec3 vWorldPosition;
  584. #else
  585. varying vec3 vReflect;
  586. uniform float refractionRatio;
  587. #endif
  588. #endif`,Yxe=`#ifdef USE_ENVMAP
  589. #ifdef ENV_WORLDPOS
  590. vWorldPosition = worldPosition.xyz;
  591. #else
  592. vec3 cameraToVertex;
  593. if ( isOrthographic ) {
  594. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  595. } else {
  596. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  597. }
  598. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  599. #ifdef ENVMAP_MODE_REFLECTION
  600. vReflect = reflect( cameraToVertex, worldNormal );
  601. #else
  602. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  603. #endif
  604. #endif
  605. #endif`,Qxe=`#ifdef USE_FOG
  606. vFogDepth = - mvPosition.z;
  607. #endif`,Zxe=`#ifdef USE_FOG
  608. varying float vFogDepth;
  609. #endif`,Jxe=`#ifdef USE_FOG
  610. #ifdef FOG_EXP2
  611. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  612. #else
  613. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  614. #endif
  615. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  616. #endif`,eye=`#ifdef USE_FOG
  617. uniform vec3 fogColor;
  618. varying float vFogDepth;
  619. #ifdef FOG_EXP2
  620. uniform float fogDensity;
  621. #else
  622. uniform float fogNear;
  623. uniform float fogFar;
  624. #endif
  625. #endif`,tye=`#ifdef USE_GRADIENTMAP
  626. uniform sampler2D gradientMap;
  627. #endif
  628. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  629. float dotNL = dot( normal, lightDirection );
  630. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  631. #ifdef USE_GRADIENTMAP
  632. return vec3( texture2D( gradientMap, coord ).r );
  633. #else
  634. vec2 fw = fwidth( coord ) * 0.5;
  635. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  636. #endif
  637. }`,nye=`#ifdef USE_LIGHTMAP
  638. uniform sampler2D lightMap;
  639. uniform float lightMapIntensity;
  640. #endif`,rye=`LambertMaterial material;
  641. material.diffuseColor = diffuseColor.rgb;
  642. material.specularStrength = specularStrength;`,aye=`varying vec3 vViewPosition;
  643. struct LambertMaterial {
  644. vec3 diffuseColor;
  645. float specularStrength;
  646. };
  647. void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
  648. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  649. vec3 irradiance = dotNL * directLight.color;
  650. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  651. }
  652. void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
  653. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  654. }
  655. #define RE_Direct RE_Direct_Lambert
  656. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,iye=`uniform bool receiveShadow;
  657. uniform vec3 ambientLightColor;
  658. #if defined( USE_LIGHT_PROBES )
  659. uniform vec3 lightProbe[ 9 ];
  660. #endif
  661. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  662. float x = normal.x, y = normal.y, z = normal.z;
  663. vec3 result = shCoefficients[ 0 ] * 0.886227;
  664. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  665. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  666. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  667. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  668. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  669. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  670. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  671. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  672. return result;
  673. }
  674. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  675. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  676. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  677. return irradiance;
  678. }
  679. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  680. vec3 irradiance = ambientLightColor;
  681. return irradiance;
  682. }
  683. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  684. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  685. if ( cutoffDistance > 0.0 ) {
  686. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  687. }
  688. return distanceFalloff;
  689. }
  690. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  691. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  692. }
  693. #if NUM_DIR_LIGHTS > 0
  694. struct DirectionalLight {
  695. vec3 direction;
  696. vec3 color;
  697. };
  698. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  699. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  700. light.color = directionalLight.color;
  701. light.direction = directionalLight.direction;
  702. light.visible = true;
  703. }
  704. #endif
  705. #if NUM_POINT_LIGHTS > 0
  706. struct PointLight {
  707. vec3 position;
  708. vec3 color;
  709. float distance;
  710. float decay;
  711. };
  712. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  713. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  714. vec3 lVector = pointLight.position - geometryPosition;
  715. light.direction = normalize( lVector );
  716. float lightDistance = length( lVector );
  717. light.color = pointLight.color;
  718. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  719. light.visible = ( light.color != vec3( 0.0 ) );
  720. }
  721. #endif
  722. #if NUM_SPOT_LIGHTS > 0
  723. struct SpotLight {
  724. vec3 position;
  725. vec3 direction;
  726. vec3 color;
  727. float distance;
  728. float decay;
  729. float coneCos;
  730. float penumbraCos;
  731. };
  732. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  733. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  734. vec3 lVector = spotLight.position - geometryPosition;
  735. light.direction = normalize( lVector );
  736. float angleCos = dot( light.direction, spotLight.direction );
  737. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  738. if ( spotAttenuation > 0.0 ) {
  739. float lightDistance = length( lVector );
  740. light.color = spotLight.color * spotAttenuation;
  741. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  742. light.visible = ( light.color != vec3( 0.0 ) );
  743. } else {
  744. light.color = vec3( 0.0 );
  745. light.visible = false;
  746. }
  747. }
  748. #endif
  749. #if NUM_RECT_AREA_LIGHTS > 0
  750. struct RectAreaLight {
  751. vec3 color;
  752. vec3 position;
  753. vec3 halfWidth;
  754. vec3 halfHeight;
  755. };
  756. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  757. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  758. #endif
  759. #if NUM_HEMI_LIGHTS > 0
  760. struct HemisphereLight {
  761. vec3 direction;
  762. vec3 skyColor;
  763. vec3 groundColor;
  764. };
  765. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  766. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  767. float dotNL = dot( normal, hemiLight.direction );
  768. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  769. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  770. return irradiance;
  771. }
  772. #endif`,sye=`#ifdef USE_ENVMAP
  773. vec3 getIBLIrradiance( const in vec3 normal ) {
  774. #ifdef ENVMAP_TYPE_CUBE_UV
  775. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  776. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
  777. return PI * envMapColor.rgb * envMapIntensity;
  778. #else
  779. return vec3( 0.0 );
  780. #endif
  781. }
  782. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  783. #ifdef ENVMAP_TYPE_CUBE_UV
  784. vec3 reflectVec = reflect( - viewDir, normal );
  785. reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );
  786. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  787. vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
  788. return envMapColor.rgb * envMapIntensity;
  789. #else
  790. return vec3( 0.0 );
  791. #endif
  792. }
  793. #ifdef USE_ANISOTROPY
  794. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  795. #ifdef ENVMAP_TYPE_CUBE_UV
  796. vec3 bentNormal = cross( bitangent, viewDir );
  797. bentNormal = normalize( cross( bentNormal, bitangent ) );
  798. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  799. return getIBLRadiance( viewDir, bentNormal, roughness );
  800. #else
  801. return vec3( 0.0 );
  802. #endif
  803. }
  804. #endif
  805. #endif`,oye=`ToonMaterial material;
  806. material.diffuseColor = diffuseColor.rgb;`,lye=`varying vec3 vViewPosition;
  807. struct ToonMaterial {
  808. vec3 diffuseColor;
  809. };
  810. void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
  811. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  812. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  813. }
  814. void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
  815. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  816. }
  817. #define RE_Direct RE_Direct_Toon
  818. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,cye=`BlinnPhongMaterial material;
  819. material.diffuseColor = diffuseColor.rgb;
  820. material.specularColor = specular;
  821. material.specularShininess = shininess;
  822. material.specularStrength = specularStrength;`,uye=`varying vec3 vViewPosition;
  823. struct BlinnPhongMaterial {
  824. vec3 diffuseColor;
  825. vec3 specularColor;
  826. float specularShininess;
  827. float specularStrength;
  828. };
  829. void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
  830. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  831. vec3 irradiance = dotNL * directLight.color;
  832. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  833. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  834. }
  835. void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
  836. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  837. }
  838. #define RE_Direct RE_Direct_BlinnPhong
  839. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,dye=`PhysicalMaterial material;
  840. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  841. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  842. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  843. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  844. material.roughness = min( material.roughness, 1.0 );
  845. #ifdef IOR
  846. material.ior = ior;
  847. #ifdef USE_SPECULAR
  848. float specularIntensityFactor = specularIntensity;
  849. vec3 specularColorFactor = specularColor;
  850. #ifdef USE_SPECULAR_COLORMAP
  851. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  852. #endif
  853. #ifdef USE_SPECULAR_INTENSITYMAP
  854. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  855. #endif
  856. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  857. #else
  858. float specularIntensityFactor = 1.0;
  859. vec3 specularColorFactor = vec3( 1.0 );
  860. material.specularF90 = 1.0;
  861. #endif
  862. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  863. #else
  864. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  865. material.specularF90 = 1.0;
  866. #endif
  867. #ifdef USE_CLEARCOAT
  868. material.clearcoat = clearcoat;
  869. material.clearcoatRoughness = clearcoatRoughness;
  870. material.clearcoatF0 = vec3( 0.04 );
  871. material.clearcoatF90 = 1.0;
  872. #ifdef USE_CLEARCOATMAP
  873. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  874. #endif
  875. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  876. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  877. #endif
  878. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  879. material.clearcoatRoughness += geometryRoughness;
  880. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  881. #endif
  882. #ifdef USE_DISPERSION
  883. material.dispersion = dispersion;
  884. #endif
  885. #ifdef USE_IRIDESCENCE
  886. material.iridescence = iridescence;
  887. material.iridescenceIOR = iridescenceIOR;
  888. #ifdef USE_IRIDESCENCEMAP
  889. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  890. #endif
  891. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  892. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  893. #else
  894. material.iridescenceThickness = iridescenceThicknessMaximum;
  895. #endif
  896. #endif
  897. #ifdef USE_SHEEN
  898. material.sheenColor = sheenColor;
  899. #ifdef USE_SHEEN_COLORMAP
  900. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  901. #endif
  902. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  903. #ifdef USE_SHEEN_ROUGHNESSMAP
  904. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  905. #endif
  906. #endif
  907. #ifdef USE_ANISOTROPY
  908. #ifdef USE_ANISOTROPYMAP
  909. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  910. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  911. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  912. #else
  913. vec2 anisotropyV = anisotropyVector;
  914. #endif
  915. material.anisotropy = length( anisotropyV );
  916. if( material.anisotropy == 0.0 ) {
  917. anisotropyV = vec2( 1.0, 0.0 );
  918. } else {
  919. anisotropyV /= material.anisotropy;
  920. material.anisotropy = saturate( material.anisotropy );
  921. }
  922. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  923. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  924. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  925. #endif`,hye=`uniform sampler2D dfgLUT;
  926. struct PhysicalMaterial {
  927. vec3 diffuseColor;
  928. float roughness;
  929. vec3 specularColor;
  930. float specularF90;
  931. float dispersion;
  932. #ifdef USE_CLEARCOAT
  933. float clearcoat;
  934. float clearcoatRoughness;
  935. vec3 clearcoatF0;
  936. float clearcoatF90;
  937. #endif
  938. #ifdef USE_IRIDESCENCE
  939. float iridescence;
  940. float iridescenceIOR;
  941. float iridescenceThickness;
  942. vec3 iridescenceFresnel;
  943. vec3 iridescenceF0;
  944. #endif
  945. #ifdef USE_SHEEN
  946. vec3 sheenColor;
  947. float sheenRoughness;
  948. #endif
  949. #ifdef IOR
  950. float ior;
  951. #endif
  952. #ifdef USE_TRANSMISSION
  953. float transmission;
  954. float transmissionAlpha;
  955. float thickness;
  956. float attenuationDistance;
  957. vec3 attenuationColor;
  958. #endif
  959. #ifdef USE_ANISOTROPY
  960. float anisotropy;
  961. float alphaT;
  962. vec3 anisotropyT;
  963. vec3 anisotropyB;
  964. #endif
  965. };
  966. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  967. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  968. vec3 sheenSpecularDirect = vec3( 0.0 );
  969. vec3 sheenSpecularIndirect = vec3(0.0 );
  970. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  971. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  972. float x2 = x * x;
  973. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  974. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  975. }
  976. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  977. float a2 = pow2( alpha );
  978. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  979. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  980. return 0.5 / max( gv + gl, EPSILON );
  981. }
  982. float D_GGX( const in float alpha, const in float dotNH ) {
  983. float a2 = pow2( alpha );
  984. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  985. return RECIPROCAL_PI * a2 / pow2( denom );
  986. }
  987. #ifdef USE_ANISOTROPY
  988. float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
  989. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  990. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  991. float v = 0.5 / ( gv + gl );
  992. return saturate(v);
  993. }
  994. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  995. float a2 = alphaT * alphaB;
  996. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  997. highp float v2 = dot( v, v );
  998. float w2 = a2 / v2;
  999. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  1000. }
  1001. #endif
  1002. #ifdef USE_CLEARCOAT
  1003. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  1004. vec3 f0 = material.clearcoatF0;
  1005. float f90 = material.clearcoatF90;
  1006. float roughness = material.clearcoatRoughness;
  1007. float alpha = pow2( roughness );
  1008. vec3 halfDir = normalize( lightDir + viewDir );
  1009. float dotNL = saturate( dot( normal, lightDir ) );
  1010. float dotNV = saturate( dot( normal, viewDir ) );
  1011. float dotNH = saturate( dot( normal, halfDir ) );
  1012. float dotVH = saturate( dot( viewDir, halfDir ) );
  1013. vec3 F = F_Schlick( f0, f90, dotVH );
  1014. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1015. float D = D_GGX( alpha, dotNH );
  1016. return F * ( V * D );
  1017. }
  1018. #endif
  1019. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1020. vec3 f0 = material.specularColor;
  1021. float f90 = material.specularF90;
  1022. float roughness = material.roughness;
  1023. float alpha = pow2( roughness );
  1024. vec3 halfDir = normalize( lightDir + viewDir );
  1025. float dotNL = saturate( dot( normal, lightDir ) );
  1026. float dotNV = saturate( dot( normal, viewDir ) );
  1027. float dotNH = saturate( dot( normal, halfDir ) );
  1028. float dotVH = saturate( dot( viewDir, halfDir ) );
  1029. vec3 F = F_Schlick( f0, f90, dotVH );
  1030. #ifdef USE_IRIDESCENCE
  1031. F = mix( F, material.iridescenceFresnel, material.iridescence );
  1032. #endif
  1033. #ifdef USE_ANISOTROPY
  1034. float dotTL = dot( material.anisotropyT, lightDir );
  1035. float dotTV = dot( material.anisotropyT, viewDir );
  1036. float dotTH = dot( material.anisotropyT, halfDir );
  1037. float dotBL = dot( material.anisotropyB, lightDir );
  1038. float dotBV = dot( material.anisotropyB, viewDir );
  1039. float dotBH = dot( material.anisotropyB, halfDir );
  1040. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  1041. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  1042. #else
  1043. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  1044. float D = D_GGX( alpha, dotNH );
  1045. #endif
  1046. return F * ( V * D );
  1047. }
  1048. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  1049. const float LUT_SIZE = 64.0;
  1050. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  1051. const float LUT_BIAS = 0.5 / LUT_SIZE;
  1052. float dotNV = saturate( dot( N, V ) );
  1053. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  1054. uv = uv * LUT_SCALE + LUT_BIAS;
  1055. return uv;
  1056. }
  1057. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  1058. float l = length( f );
  1059. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  1060. }
  1061. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  1062. float x = dot( v1, v2 );
  1063. float y = abs( x );
  1064. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  1065. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  1066. float v = a / b;
  1067. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  1068. return cross( v1, v2 ) * theta_sintheta;
  1069. }
  1070. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  1071. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  1072. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  1073. vec3 lightNormal = cross( v1, v2 );
  1074. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  1075. vec3 T1, T2;
  1076. T1 = normalize( V - N * dot( V, N ) );
  1077. T2 = - cross( N, T1 );
  1078. mat3 mat = mInv * transpose( mat3( T1, T2, N ) );
  1079. vec3 coords[ 4 ];
  1080. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  1081. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  1082. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  1083. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  1084. coords[ 0 ] = normalize( coords[ 0 ] );
  1085. coords[ 1 ] = normalize( coords[ 1 ] );
  1086. coords[ 2 ] = normalize( coords[ 2 ] );
  1087. coords[ 3 ] = normalize( coords[ 3 ] );
  1088. vec3 vectorFormFactor = vec3( 0.0 );
  1089. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  1090. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  1091. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  1092. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  1093. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  1094. return vec3( result );
  1095. }
  1096. #if defined( USE_SHEEN )
  1097. float D_Charlie( float roughness, float dotNH ) {
  1098. float alpha = pow2( roughness );
  1099. float invAlpha = 1.0 / alpha;
  1100. float cos2h = dotNH * dotNH;
  1101. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  1102. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  1103. }
  1104. float V_Neubelt( float dotNV, float dotNL ) {
  1105. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  1106. }
  1107. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  1108. vec3 halfDir = normalize( lightDir + viewDir );
  1109. float dotNL = saturate( dot( normal, lightDir ) );
  1110. float dotNV = saturate( dot( normal, viewDir ) );
  1111. float dotNH = saturate( dot( normal, halfDir ) );
  1112. float D = D_Charlie( sheenRoughness, dotNH );
  1113. float V = V_Neubelt( dotNV, dotNL );
  1114. return sheenColor * ( D * V );
  1115. }
  1116. #endif
  1117. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1118. float dotNV = saturate( dot( normal, viewDir ) );
  1119. float r2 = roughness * roughness;
  1120. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  1121. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  1122. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  1123. return saturate( DG * RECIPROCAL_PI );
  1124. }
  1125. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  1126. float dotNV = saturate( dot( normal, viewDir ) );
  1127. vec2 uv = vec2( roughness, dotNV );
  1128. return texture2D( dfgLUT, uv ).rg;
  1129. }
  1130. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  1131. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1132. return specularColor * fab.x + specularF90 * fab.y;
  1133. }
  1134. #ifdef USE_IRIDESCENCE
  1135. void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
  1136. #else
  1137. void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
  1138. #endif
  1139. vec2 fab = DFGApprox( normal, viewDir, roughness );
  1140. #ifdef USE_IRIDESCENCE
  1141. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  1142. #else
  1143. vec3 Fr = specularColor;
  1144. #endif
  1145. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  1146. float Ess = fab.x + fab.y;
  1147. float Ems = 1.0 - Ess;
  1148. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  1149. singleScatter += FssEss;
  1150. multiScatter += Fms * Ems;
  1151. }
  1152. vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  1153. vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
  1154. float dotNL = saturate( dot( normal, lightDir ) );
  1155. float dotNV = saturate( dot( normal, viewDir ) );
  1156. vec2 dfgV = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness );
  1157. vec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness );
  1158. vec3 FssEss_V = material.specularColor * dfgV.x + material.specularF90 * dfgV.y;
  1159. vec3 FssEss_L = material.specularColor * dfgL.x + material.specularF90 * dfgL.y;
  1160. float Ess_V = dfgV.x + dfgV.y;
  1161. float Ess_L = dfgL.x + dfgL.y;
  1162. float Ems_V = 1.0 - Ess_V;
  1163. float Ems_L = 1.0 - Ess_L;
  1164. vec3 Favg = material.specularColor + ( 1.0 - material.specularColor ) * 0.047619;
  1165. vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg * Favg + EPSILON );
  1166. float compensationFactor = Ems_V * Ems_L;
  1167. vec3 multiScatter = Fms * compensationFactor;
  1168. return singleScatter + multiScatter;
  1169. }
  1170. #if NUM_RECT_AREA_LIGHTS > 0
  1171. void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  1172. vec3 normal = geometryNormal;
  1173. vec3 viewDir = geometryViewDir;
  1174. vec3 position = geometryPosition;
  1175. vec3 lightPos = rectAreaLight.position;
  1176. vec3 halfWidth = rectAreaLight.halfWidth;
  1177. vec3 halfHeight = rectAreaLight.halfHeight;
  1178. vec3 lightColor = rectAreaLight.color;
  1179. float roughness = material.roughness;
  1180. vec3 rectCoords[ 4 ];
  1181. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  1182. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  1183. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  1184. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  1185. vec4 t1 = texture2D( ltc_1, uv );
  1186. vec4 t2 = texture2D( ltc_2, uv );
  1187. mat3 mInv = mat3(
  1188. vec3( t1.x, 0, t1.y ),
  1189. vec3( 0, 1, 0 ),
  1190. vec3( t1.z, 0, t1.w )
  1191. );
  1192. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  1193. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  1194. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  1195. }
  1196. #endif
  1197. void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  1198. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  1199. vec3 irradiance = dotNL * directLight.color;
  1200. #ifdef USE_CLEARCOAT
  1201. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  1202. vec3 ccIrradiance = dotNLcc * directLight.color;
  1203. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  1204. #endif
  1205. #ifdef USE_SHEEN
  1206. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  1207. #endif
  1208. reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
  1209. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1210. }
  1211. void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  1212. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  1213. }
  1214. void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
  1215. #ifdef USE_CLEARCOAT
  1216. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  1217. #endif
  1218. #ifdef USE_SHEEN
  1219. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  1220. #endif
  1221. vec3 singleScattering = vec3( 0.0 );
  1222. vec3 multiScattering = vec3( 0.0 );
  1223. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  1224. #ifdef USE_IRIDESCENCE
  1225. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  1226. #else
  1227. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  1228. #endif
  1229. vec3 totalScattering = singleScattering + multiScattering;
  1230. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  1231. reflectedLight.indirectSpecular += radiance * singleScattering;
  1232. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  1233. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  1234. }
  1235. #define RE_Direct RE_Direct_Physical
  1236. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  1237. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  1238. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  1239. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  1240. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  1241. }`,mye=`
  1242. vec3 geometryPosition = - vViewPosition;
  1243. vec3 geometryNormal = normal;
  1244. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  1245. vec3 geometryClearcoatNormal = vec3( 0.0 );
  1246. #ifdef USE_CLEARCOAT
  1247. geometryClearcoatNormal = clearcoatNormal;
  1248. #endif
  1249. #ifdef USE_IRIDESCENCE
  1250. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  1251. if ( material.iridescenceThickness == 0.0 ) {
  1252. material.iridescence = 0.0;
  1253. } else {
  1254. material.iridescence = saturate( material.iridescence );
  1255. }
  1256. if ( material.iridescence > 0.0 ) {
  1257. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  1258. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  1259. }
  1260. #endif
  1261. IncidentLight directLight;
  1262. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  1263. PointLight pointLight;
  1264. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  1265. PointLightShadow pointLightShadow;
  1266. #endif
  1267. #pragma unroll_loop_start
  1268. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  1269. pointLight = pointLights[ i ];
  1270. getPointLightInfo( pointLight, geometryPosition, directLight );
  1271. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  1272. pointLightShadow = pointLightShadows[ i ];
  1273. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  1274. #endif
  1275. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1276. }
  1277. #pragma unroll_loop_end
  1278. #endif
  1279. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  1280. SpotLight spotLight;
  1281. vec4 spotColor;
  1282. vec3 spotLightCoord;
  1283. bool inSpotLightMap;
  1284. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  1285. SpotLightShadow spotLightShadow;
  1286. #endif
  1287. #pragma unroll_loop_start
  1288. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  1289. spotLight = spotLights[ i ];
  1290. getSpotLightInfo( spotLight, geometryPosition, directLight );
  1291. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1292. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  1293. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1294. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  1295. #else
  1296. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  1297. #endif
  1298. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  1299. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  1300. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  1301. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  1302. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  1303. #endif
  1304. #undef SPOT_LIGHT_MAP_INDEX
  1305. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1306. spotLightShadow = spotLightShadows[ i ];
  1307. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1308. #endif
  1309. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1310. }
  1311. #pragma unroll_loop_end
  1312. #endif
  1313. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  1314. DirectionalLight directionalLight;
  1315. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  1316. DirectionalLightShadow directionalLightShadow;
  1317. #endif
  1318. #pragma unroll_loop_start
  1319. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  1320. directionalLight = directionalLights[ i ];
  1321. getDirectionalLightInfo( directionalLight, directLight );
  1322. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  1323. directionalLightShadow = directionalLightShadows[ i ];
  1324. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1325. #endif
  1326. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1327. }
  1328. #pragma unroll_loop_end
  1329. #endif
  1330. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  1331. RectAreaLight rectAreaLight;
  1332. #pragma unroll_loop_start
  1333. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  1334. rectAreaLight = rectAreaLights[ i ];
  1335. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1336. }
  1337. #pragma unroll_loop_end
  1338. #endif
  1339. #if defined( RE_IndirectDiffuse )
  1340. vec3 iblIrradiance = vec3( 0.0 );
  1341. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  1342. #if defined( USE_LIGHT_PROBES )
  1343. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  1344. #endif
  1345. #if ( NUM_HEMI_LIGHTS > 0 )
  1346. #pragma unroll_loop_start
  1347. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  1348. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  1349. }
  1350. #pragma unroll_loop_end
  1351. #endif
  1352. #endif
  1353. #if defined( RE_IndirectSpecular )
  1354. vec3 radiance = vec3( 0.0 );
  1355. vec3 clearcoatRadiance = vec3( 0.0 );
  1356. #endif`,fye=`#if defined( RE_IndirectDiffuse )
  1357. #ifdef USE_LIGHTMAP
  1358. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  1359. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  1360. irradiance += lightMapIrradiance;
  1361. #endif
  1362. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  1363. iblIrradiance += getIBLIrradiance( geometryNormal );
  1364. #endif
  1365. #endif
  1366. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  1367. #ifdef USE_ANISOTROPY
  1368. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  1369. #else
  1370. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  1371. #endif
  1372. #ifdef USE_CLEARCOAT
  1373. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  1374. #endif
  1375. #endif`,pye=`#if defined( RE_IndirectDiffuse )
  1376. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1377. #endif
  1378. #if defined( RE_IndirectSpecular )
  1379. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  1380. #endif`,gye=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1381. gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  1382. #endif`,bye=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
  1383. uniform float logDepthBufFC;
  1384. varying float vFragDepth;
  1385. varying float vIsPerspective;
  1386. #endif`,xye=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1387. varying float vFragDepth;
  1388. varying float vIsPerspective;
  1389. #endif`,yye=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
  1390. vFragDepth = 1.0 + gl_Position.w;
  1391. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  1392. #endif`,vye=`#ifdef USE_MAP
  1393. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  1394. #ifdef DECODE_VIDEO_TEXTURE
  1395. sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
  1396. #endif
  1397. diffuseColor *= sampledDiffuseColor;
  1398. #endif`,wye=`#ifdef USE_MAP
  1399. uniform sampler2D map;
  1400. #endif`,Sye=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1401. #if defined( USE_POINTS_UV )
  1402. vec2 uv = vUv;
  1403. #else
  1404. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  1405. #endif
  1406. #endif
  1407. #ifdef USE_MAP
  1408. diffuseColor *= texture2D( map, uv );
  1409. #endif
  1410. #ifdef USE_ALPHAMAP
  1411. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  1412. #endif`,_ye=`#if defined( USE_POINTS_UV )
  1413. varying vec2 vUv;
  1414. #else
  1415. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  1416. uniform mat3 uvTransform;
  1417. #endif
  1418. #endif
  1419. #ifdef USE_MAP
  1420. uniform sampler2D map;
  1421. #endif
  1422. #ifdef USE_ALPHAMAP
  1423. uniform sampler2D alphaMap;
  1424. #endif`,Nye=`float metalnessFactor = metalness;
  1425. #ifdef USE_METALNESSMAP
  1426. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  1427. metalnessFactor *= texelMetalness.b;
  1428. #endif`,Cye=`#ifdef USE_METALNESSMAP
  1429. uniform sampler2D metalnessMap;
  1430. #endif`,kye=`#ifdef USE_INSTANCING_MORPH
  1431. float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1432. float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
  1433. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1434. morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
  1435. }
  1436. #endif`,Aye=`#if defined( USE_MORPHCOLORS )
  1437. vColor *= morphTargetBaseInfluence;
  1438. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1439. #if defined( USE_COLOR_ALPHA )
  1440. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  1441. #elif defined( USE_COLOR )
  1442. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  1443. #endif
  1444. }
  1445. #endif`,Tye=`#ifdef USE_MORPHNORMALS
  1446. objectNormal *= morphTargetBaseInfluence;
  1447. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1448. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  1449. }
  1450. #endif`,Mye=`#ifdef USE_MORPHTARGETS
  1451. #ifndef USE_INSTANCING_MORPH
  1452. uniform float morphTargetBaseInfluence;
  1453. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  1454. #endif
  1455. uniform sampler2DArray morphTargetsTexture;
  1456. uniform ivec2 morphTargetsTextureSize;
  1457. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  1458. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  1459. int y = texelIndex / morphTargetsTextureSize.x;
  1460. int x = texelIndex - y * morphTargetsTextureSize.x;
  1461. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  1462. return texelFetch( morphTargetsTexture, morphUV, 0 );
  1463. }
  1464. #endif`,Pye=`#ifdef USE_MORPHTARGETS
  1465. transformed *= morphTargetBaseInfluence;
  1466. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  1467. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  1468. }
  1469. #endif`,Eye=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  1470. #ifdef FLAT_SHADED
  1471. vec3 fdx = dFdx( vViewPosition );
  1472. vec3 fdy = dFdy( vViewPosition );
  1473. vec3 normal = normalize( cross( fdx, fdy ) );
  1474. #else
  1475. vec3 normal = normalize( vNormal );
  1476. #ifdef DOUBLE_SIDED
  1477. normal *= faceDirection;
  1478. #endif
  1479. #endif
  1480. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  1481. #ifdef USE_TANGENT
  1482. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1483. #else
  1484. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  1485. #if defined( USE_NORMALMAP )
  1486. vNormalMapUv
  1487. #elif defined( USE_CLEARCOAT_NORMALMAP )
  1488. vClearcoatNormalMapUv
  1489. #else
  1490. vUv
  1491. #endif
  1492. );
  1493. #endif
  1494. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1495. tbn[0] *= faceDirection;
  1496. tbn[1] *= faceDirection;
  1497. #endif
  1498. #endif
  1499. #ifdef USE_CLEARCOAT_NORMALMAP
  1500. #ifdef USE_TANGENT
  1501. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  1502. #else
  1503. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  1504. #endif
  1505. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  1506. tbn2[0] *= faceDirection;
  1507. tbn2[1] *= faceDirection;
  1508. #endif
  1509. #endif
  1510. vec3 nonPerturbedNormal = normal;`,jye=`#ifdef USE_NORMALMAP_OBJECTSPACE
  1511. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1512. #ifdef FLIP_SIDED
  1513. normal = - normal;
  1514. #endif
  1515. #ifdef DOUBLE_SIDED
  1516. normal = normal * faceDirection;
  1517. #endif
  1518. normal = normalize( normalMatrix * normal );
  1519. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  1520. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  1521. mapN.xy *= normalScale;
  1522. normal = normalize( tbn * mapN );
  1523. #elif defined( USE_BUMPMAP )
  1524. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  1525. #endif`,Dye=`#ifndef FLAT_SHADED
  1526. varying vec3 vNormal;
  1527. #ifdef USE_TANGENT
  1528. varying vec3 vTangent;
  1529. varying vec3 vBitangent;
  1530. #endif
  1531. #endif`,Rye=`#ifndef FLAT_SHADED
  1532. varying vec3 vNormal;
  1533. #ifdef USE_TANGENT
  1534. varying vec3 vTangent;
  1535. varying vec3 vBitangent;
  1536. #endif
  1537. #endif`,Fye=`#ifndef FLAT_SHADED
  1538. vNormal = normalize( transformedNormal );
  1539. #ifdef USE_TANGENT
  1540. vTangent = normalize( transformedTangent );
  1541. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  1542. #endif
  1543. #endif`,Lye=`#ifdef USE_NORMALMAP
  1544. uniform sampler2D normalMap;
  1545. uniform vec2 normalScale;
  1546. #endif
  1547. #ifdef USE_NORMALMAP_OBJECTSPACE
  1548. uniform mat3 normalMatrix;
  1549. #endif
  1550. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  1551. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  1552. vec3 q0 = dFdx( eye_pos.xyz );
  1553. vec3 q1 = dFdy( eye_pos.xyz );
  1554. vec2 st0 = dFdx( uv.st );
  1555. vec2 st1 = dFdy( uv.st );
  1556. vec3 N = surf_norm;
  1557. vec3 q1perp = cross( q1, N );
  1558. vec3 q0perp = cross( N, q0 );
  1559. vec3 T = q1perp * st0.x + q0perp * st1.x;
  1560. vec3 B = q1perp * st0.y + q0perp * st1.y;
  1561. float det = max( dot( T, T ), dot( B, B ) );
  1562. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  1563. return mat3( T * scale, B * scale, N );
  1564. }
  1565. #endif`,Oye=`#ifdef USE_CLEARCOAT
  1566. vec3 clearcoatNormal = nonPerturbedNormal;
  1567. #endif`,Iye=`#ifdef USE_CLEARCOAT_NORMALMAP
  1568. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  1569. clearcoatMapN.xy *= clearcoatNormalScale;
  1570. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  1571. #endif`,zye=`#ifdef USE_CLEARCOATMAP
  1572. uniform sampler2D clearcoatMap;
  1573. #endif
  1574. #ifdef USE_CLEARCOAT_NORMALMAP
  1575. uniform sampler2D clearcoatNormalMap;
  1576. uniform vec2 clearcoatNormalScale;
  1577. #endif
  1578. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  1579. uniform sampler2D clearcoatRoughnessMap;
  1580. #endif`,Uye=`#ifdef USE_IRIDESCENCEMAP
  1581. uniform sampler2D iridescenceMap;
  1582. #endif
  1583. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  1584. uniform sampler2D iridescenceThicknessMap;
  1585. #endif`,Bye=`#ifdef OPAQUE
  1586. diffuseColor.a = 1.0;
  1587. #endif
  1588. #ifdef USE_TRANSMISSION
  1589. diffuseColor.a *= material.transmissionAlpha;
  1590. #endif
  1591. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Hye=`vec3 packNormalToRGB( const in vec3 normal ) {
  1592. return normalize( normal ) * 0.5 + 0.5;
  1593. }
  1594. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  1595. return 2.0 * rgb.xyz - 1.0;
  1596. }
  1597. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
  1598. const float Inv255 = 1. / 255.;
  1599. const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
  1600. const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
  1601. const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
  1602. const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
  1603. vec4 packDepthToRGBA( const in float v ) {
  1604. if( v <= 0.0 )
  1605. return vec4( 0., 0., 0., 0. );
  1606. if( v >= 1.0 )
  1607. return vec4( 1., 1., 1., 1. );
  1608. float vuf;
  1609. float af = modf( v * PackFactors.a, vuf );
  1610. float bf = modf( vuf * ShiftRight8, vuf );
  1611. float gf = modf( vuf * ShiftRight8, vuf );
  1612. return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
  1613. }
  1614. vec3 packDepthToRGB( const in float v ) {
  1615. if( v <= 0.0 )
  1616. return vec3( 0., 0., 0. );
  1617. if( v >= 1.0 )
  1618. return vec3( 1., 1., 1. );
  1619. float vuf;
  1620. float bf = modf( v * PackFactors.b, vuf );
  1621. float gf = modf( vuf * ShiftRight8, vuf );
  1622. return vec3( vuf * Inv255, gf * PackUpscale, bf );
  1623. }
  1624. vec2 packDepthToRG( const in float v ) {
  1625. if( v <= 0.0 )
  1626. return vec2( 0., 0. );
  1627. if( v >= 1.0 )
  1628. return vec2( 1., 1. );
  1629. float vuf;
  1630. float gf = modf( v * 256., vuf );
  1631. return vec2( vuf * Inv255, gf );
  1632. }
  1633. float unpackRGBAToDepth( const in vec4 v ) {
  1634. return dot( v, UnpackFactors4 );
  1635. }
  1636. float unpackRGBToDepth( const in vec3 v ) {
  1637. return dot( v, UnpackFactors3 );
  1638. }
  1639. float unpackRGToDepth( const in vec2 v ) {
  1640. return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
  1641. }
  1642. vec4 pack2HalfToRGBA( const in vec2 v ) {
  1643. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  1644. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  1645. }
  1646. vec2 unpackRGBATo2Half( const in vec4 v ) {
  1647. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  1648. }
  1649. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  1650. return ( viewZ + near ) / ( near - far );
  1651. }
  1652. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1653. return depth * ( near - far ) - near;
  1654. }
  1655. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  1656. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  1657. }
  1658. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  1659. return ( near * far ) / ( ( far - near ) * depth - far );
  1660. }`,$ye=`#ifdef PREMULTIPLIED_ALPHA
  1661. gl_FragColor.rgb *= gl_FragColor.a;
  1662. #endif`,Vye=`vec4 mvPosition = vec4( transformed, 1.0 );
  1663. #ifdef USE_BATCHING
  1664. mvPosition = batchingMatrix * mvPosition;
  1665. #endif
  1666. #ifdef USE_INSTANCING
  1667. mvPosition = instanceMatrix * mvPosition;
  1668. #endif
  1669. mvPosition = modelViewMatrix * mvPosition;
  1670. gl_Position = projectionMatrix * mvPosition;`,qye=`#ifdef DITHERING
  1671. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  1672. #endif`,Gye=`#ifdef DITHERING
  1673. vec3 dithering( vec3 color ) {
  1674. float grid_position = rand( gl_FragCoord.xy );
  1675. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  1676. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  1677. return color + dither_shift_RGB;
  1678. }
  1679. #endif`,Wye=`float roughnessFactor = roughness;
  1680. #ifdef USE_ROUGHNESSMAP
  1681. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  1682. roughnessFactor *= texelRoughness.g;
  1683. #endif`,Kye=`#ifdef USE_ROUGHNESSMAP
  1684. uniform sampler2D roughnessMap;
  1685. #endif`,Xye=`#if NUM_SPOT_LIGHT_COORDS > 0
  1686. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1687. #endif
  1688. #if NUM_SPOT_LIGHT_MAPS > 0
  1689. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  1690. #endif
  1691. #ifdef USE_SHADOWMAP
  1692. #if NUM_DIR_LIGHT_SHADOWS > 0
  1693. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  1694. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1695. struct DirectionalLightShadow {
  1696. float shadowIntensity;
  1697. float shadowBias;
  1698. float shadowNormalBias;
  1699. float shadowRadius;
  1700. vec2 shadowMapSize;
  1701. };
  1702. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1703. #endif
  1704. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1705. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  1706. struct SpotLightShadow {
  1707. float shadowIntensity;
  1708. float shadowBias;
  1709. float shadowNormalBias;
  1710. float shadowRadius;
  1711. vec2 shadowMapSize;
  1712. };
  1713. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1714. #endif
  1715. #if NUM_POINT_LIGHT_SHADOWS > 0
  1716. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  1717. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1718. struct PointLightShadow {
  1719. float shadowIntensity;
  1720. float shadowBias;
  1721. float shadowNormalBias;
  1722. float shadowRadius;
  1723. vec2 shadowMapSize;
  1724. float shadowCameraNear;
  1725. float shadowCameraFar;
  1726. };
  1727. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1728. #endif
  1729. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  1730. float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
  1731. #ifdef USE_REVERSED_DEPTH_BUFFER
  1732. return step( depth, compare );
  1733. #else
  1734. return step( compare, depth );
  1735. #endif
  1736. }
  1737. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  1738. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  1739. }
  1740. float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
  1741. float occlusion = 1.0;
  1742. vec2 distribution = texture2DDistribution( shadow, uv );
  1743. #ifdef USE_REVERSED_DEPTH_BUFFER
  1744. float hard_shadow = step( distribution.x, compare );
  1745. #else
  1746. float hard_shadow = step( compare, distribution.x );
  1747. #endif
  1748. if ( hard_shadow != 1.0 ) {
  1749. float distance = compare - distribution.x;
  1750. float variance = max( 0.00000, distribution.y * distribution.y );
  1751. float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
  1752. }
  1753. return occlusion;
  1754. }
  1755. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  1756. float shadow = 1.0;
  1757. shadowCoord.xyz /= shadowCoord.w;
  1758. shadowCoord.z += shadowBias;
  1759. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  1760. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  1761. if ( frustumTest ) {
  1762. #if defined( SHADOWMAP_TYPE_PCF )
  1763. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1764. float dx0 = - texelSize.x * shadowRadius;
  1765. float dy0 = - texelSize.y * shadowRadius;
  1766. float dx1 = + texelSize.x * shadowRadius;
  1767. float dy1 = + texelSize.y * shadowRadius;
  1768. float dx2 = dx0 / 2.0;
  1769. float dy2 = dy0 / 2.0;
  1770. float dx3 = dx1 / 2.0;
  1771. float dy3 = dy1 / 2.0;
  1772. shadow = (
  1773. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  1774. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  1775. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  1776. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  1777. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  1778. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  1779. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  1780. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  1781. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  1782. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  1783. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  1784. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  1785. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  1786. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  1787. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  1788. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  1789. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  1790. ) * ( 1.0 / 17.0 );
  1791. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  1792. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  1793. float dx = texelSize.x;
  1794. float dy = texelSize.y;
  1795. vec2 uv = shadowCoord.xy;
  1796. vec2 f = fract( uv * shadowMapSize + 0.5 );
  1797. uv -= f * texelSize;
  1798. shadow = (
  1799. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  1800. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  1801. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  1802. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  1803. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  1804. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  1805. f.x ) +
  1806. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  1807. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  1808. f.x ) +
  1809. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  1810. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  1811. f.y ) +
  1812. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  1813. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  1814. f.y ) +
  1815. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  1816. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  1817. f.x ),
  1818. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  1819. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  1820. f.x ),
  1821. f.y )
  1822. ) * ( 1.0 / 9.0 );
  1823. #elif defined( SHADOWMAP_TYPE_VSM )
  1824. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  1825. #else
  1826. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  1827. #endif
  1828. }
  1829. return mix( 1.0, shadow, shadowIntensity );
  1830. }
  1831. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  1832. vec3 absV = abs( v );
  1833. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  1834. absV *= scaleToCube;
  1835. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  1836. vec2 planar = v.xy;
  1837. float almostATexel = 1.5 * texelSizeY;
  1838. float almostOne = 1.0 - almostATexel;
  1839. if ( absV.z >= almostOne ) {
  1840. if ( v.z > 0.0 )
  1841. planar.x = 4.0 - v.x;
  1842. } else if ( absV.x >= almostOne ) {
  1843. float signX = sign( v.x );
  1844. planar.x = v.z * signX + 2.0 * signX;
  1845. } else if ( absV.y >= almostOne ) {
  1846. float signY = sign( v.y );
  1847. planar.x = v.x + 2.0 * signY + 2.0;
  1848. planar.y = v.z * signY - 2.0;
  1849. }
  1850. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  1851. }
  1852. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  1853. float shadow = 1.0;
  1854. vec3 lightToPosition = shadowCoord.xyz;
  1855. float lightToPositionLength = length( lightToPosition );
  1856. if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
  1857. float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  1858. vec3 bd3D = normalize( lightToPosition );
  1859. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  1860. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  1861. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  1862. shadow = (
  1863. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  1864. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  1865. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  1866. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  1867. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  1868. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  1869. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  1870. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  1871. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  1872. ) * ( 1.0 / 9.0 );
  1873. #else
  1874. shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  1875. #endif
  1876. }
  1877. return mix( 1.0, shadow, shadowIntensity );
  1878. }
  1879. #endif`,Yye=`#if NUM_SPOT_LIGHT_COORDS > 0
  1880. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  1881. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  1882. #endif
  1883. #ifdef USE_SHADOWMAP
  1884. #if NUM_DIR_LIGHT_SHADOWS > 0
  1885. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  1886. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  1887. struct DirectionalLightShadow {
  1888. float shadowIntensity;
  1889. float shadowBias;
  1890. float shadowNormalBias;
  1891. float shadowRadius;
  1892. vec2 shadowMapSize;
  1893. };
  1894. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  1895. #endif
  1896. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1897. struct SpotLightShadow {
  1898. float shadowIntensity;
  1899. float shadowBias;
  1900. float shadowNormalBias;
  1901. float shadowRadius;
  1902. vec2 shadowMapSize;
  1903. };
  1904. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  1905. #endif
  1906. #if NUM_POINT_LIGHT_SHADOWS > 0
  1907. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  1908. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  1909. struct PointLightShadow {
  1910. float shadowIntensity;
  1911. float shadowBias;
  1912. float shadowNormalBias;
  1913. float shadowRadius;
  1914. vec2 shadowMapSize;
  1915. float shadowCameraNear;
  1916. float shadowCameraFar;
  1917. };
  1918. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  1919. #endif
  1920. #endif`,Qye=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  1921. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  1922. vec4 shadowWorldPosition;
  1923. #endif
  1924. #if defined( USE_SHADOWMAP )
  1925. #if NUM_DIR_LIGHT_SHADOWS > 0
  1926. #pragma unroll_loop_start
  1927. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1928. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  1929. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  1930. }
  1931. #pragma unroll_loop_end
  1932. #endif
  1933. #if NUM_POINT_LIGHT_SHADOWS > 0
  1934. #pragma unroll_loop_start
  1935. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  1936. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  1937. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  1938. }
  1939. #pragma unroll_loop_end
  1940. #endif
  1941. #endif
  1942. #if NUM_SPOT_LIGHT_COORDS > 0
  1943. #pragma unroll_loop_start
  1944. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  1945. shadowWorldPosition = worldPosition;
  1946. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  1947. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  1948. #endif
  1949. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  1950. }
  1951. #pragma unroll_loop_end
  1952. #endif`,Zye=`float getShadowMask() {
  1953. float shadow = 1.0;
  1954. #ifdef USE_SHADOWMAP
  1955. #if NUM_DIR_LIGHT_SHADOWS > 0
  1956. DirectionalLightShadow directionalLight;
  1957. #pragma unroll_loop_start
  1958. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  1959. directionalLight = directionalLightShadows[ i ];
  1960. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  1961. }
  1962. #pragma unroll_loop_end
  1963. #endif
  1964. #if NUM_SPOT_LIGHT_SHADOWS > 0
  1965. SpotLightShadow spotLight;
  1966. #pragma unroll_loop_start
  1967. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  1968. spotLight = spotLightShadows[ i ];
  1969. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  1970. }
  1971. #pragma unroll_loop_end
  1972. #endif
  1973. #if NUM_POINT_LIGHT_SHADOWS > 0
  1974. PointLightShadow pointLight;
  1975. #pragma unroll_loop_start
  1976. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  1977. pointLight = pointLightShadows[ i ];
  1978. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  1979. }
  1980. #pragma unroll_loop_end
  1981. #endif
  1982. #endif
  1983. return shadow;
  1984. }`,Jye=`#ifdef USE_SKINNING
  1985. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  1986. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  1987. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  1988. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  1989. #endif`,eve=`#ifdef USE_SKINNING
  1990. uniform mat4 bindMatrix;
  1991. uniform mat4 bindMatrixInverse;
  1992. uniform highp sampler2D boneTexture;
  1993. mat4 getBoneMatrix( const in float i ) {
  1994. int size = textureSize( boneTexture, 0 ).x;
  1995. int j = int( i ) * 4;
  1996. int x = j % size;
  1997. int y = j / size;
  1998. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  1999. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  2000. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  2001. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  2002. return mat4( v1, v2, v3, v4 );
  2003. }
  2004. #endif`,tve=`#ifdef USE_SKINNING
  2005. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  2006. vec4 skinned = vec4( 0.0 );
  2007. skinned += boneMatX * skinVertex * skinWeight.x;
  2008. skinned += boneMatY * skinVertex * skinWeight.y;
  2009. skinned += boneMatZ * skinVertex * skinWeight.z;
  2010. skinned += boneMatW * skinVertex * skinWeight.w;
  2011. transformed = ( bindMatrixInverse * skinned ).xyz;
  2012. #endif`,nve=`#ifdef USE_SKINNING
  2013. mat4 skinMatrix = mat4( 0.0 );
  2014. skinMatrix += skinWeight.x * boneMatX;
  2015. skinMatrix += skinWeight.y * boneMatY;
  2016. skinMatrix += skinWeight.z * boneMatZ;
  2017. skinMatrix += skinWeight.w * boneMatW;
  2018. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  2019. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  2020. #ifdef USE_TANGENT
  2021. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  2022. #endif
  2023. #endif`,rve=`float specularStrength;
  2024. #ifdef USE_SPECULARMAP
  2025. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  2026. specularStrength = texelSpecular.r;
  2027. #else
  2028. specularStrength = 1.0;
  2029. #endif`,ave=`#ifdef USE_SPECULARMAP
  2030. uniform sampler2D specularMap;
  2031. #endif`,ive=`#if defined( TONE_MAPPING )
  2032. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  2033. #endif`,sve=`#ifndef saturate
  2034. #define saturate( a ) clamp( a, 0.0, 1.0 )
  2035. #endif
  2036. uniform float toneMappingExposure;
  2037. vec3 LinearToneMapping( vec3 color ) {
  2038. return saturate( toneMappingExposure * color );
  2039. }
  2040. vec3 ReinhardToneMapping( vec3 color ) {
  2041. color *= toneMappingExposure;
  2042. return saturate( color / ( vec3( 1.0 ) + color ) );
  2043. }
  2044. vec3 CineonToneMapping( vec3 color ) {
  2045. color *= toneMappingExposure;
  2046. color = max( vec3( 0.0 ), color - 0.004 );
  2047. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  2048. }
  2049. vec3 RRTAndODTFit( vec3 v ) {
  2050. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  2051. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  2052. return a / b;
  2053. }
  2054. vec3 ACESFilmicToneMapping( vec3 color ) {
  2055. const mat3 ACESInputMat = mat3(
  2056. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  2057. vec3( 0.04823, 0.01566, 0.83777 )
  2058. );
  2059. const mat3 ACESOutputMat = mat3(
  2060. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  2061. vec3( -0.07367, -0.00605, 1.07602 )
  2062. );
  2063. color *= toneMappingExposure / 0.6;
  2064. color = ACESInputMat * color;
  2065. color = RRTAndODTFit( color );
  2066. color = ACESOutputMat * color;
  2067. return saturate( color );
  2068. }
  2069. const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
  2070. vec3( 1.6605, - 0.1246, - 0.0182 ),
  2071. vec3( - 0.5876, 1.1329, - 0.1006 ),
  2072. vec3( - 0.0728, - 0.0083, 1.1187 )
  2073. );
  2074. const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
  2075. vec3( 0.6274, 0.0691, 0.0164 ),
  2076. vec3( 0.3293, 0.9195, 0.0880 ),
  2077. vec3( 0.0433, 0.0113, 0.8956 )
  2078. );
  2079. vec3 agxDefaultContrastApprox( vec3 x ) {
  2080. vec3 x2 = x * x;
  2081. vec3 x4 = x2 * x2;
  2082. return + 15.5 * x4 * x2
  2083. - 40.14 * x4 * x
  2084. + 31.96 * x4
  2085. - 6.868 * x2 * x
  2086. + 0.4298 * x2
  2087. + 0.1191 * x
  2088. - 0.00232;
  2089. }
  2090. vec3 AgXToneMapping( vec3 color ) {
  2091. const mat3 AgXInsetMatrix = mat3(
  2092. vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
  2093. vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
  2094. vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
  2095. );
  2096. const mat3 AgXOutsetMatrix = mat3(
  2097. vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
  2098. vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
  2099. vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
  2100. );
  2101. const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
  2102. color *= toneMappingExposure;
  2103. color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
  2104. color = AgXInsetMatrix * color;
  2105. color = max( color, 1e-10 ); color = log2( color );
  2106. color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
  2107. color = clamp( color, 0.0, 1.0 );
  2108. color = agxDefaultContrastApprox( color );
  2109. color = AgXOutsetMatrix * color;
  2110. color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
  2111. color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
  2112. color = clamp( color, 0.0, 1.0 );
  2113. return color;
  2114. }
  2115. vec3 NeutralToneMapping( vec3 color ) {
  2116. const float StartCompression = 0.8 - 0.04;
  2117. const float Desaturation = 0.15;
  2118. color *= toneMappingExposure;
  2119. float x = min( color.r, min( color.g, color.b ) );
  2120. float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
  2121. color -= offset;
  2122. float peak = max( color.r, max( color.g, color.b ) );
  2123. if ( peak < StartCompression ) return color;
  2124. float d = 1. - StartCompression;
  2125. float newPeak = 1. - d * d / ( peak + d - StartCompression );
  2126. color *= newPeak / peak;
  2127. float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
  2128. return mix( color, vec3( newPeak ), g );
  2129. }
  2130. vec3 CustomToneMapping( vec3 color ) { return color; }`,ove=`#ifdef USE_TRANSMISSION
  2131. material.transmission = transmission;
  2132. material.transmissionAlpha = 1.0;
  2133. material.thickness = thickness;
  2134. material.attenuationDistance = attenuationDistance;
  2135. material.attenuationColor = attenuationColor;
  2136. #ifdef USE_TRANSMISSIONMAP
  2137. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  2138. #endif
  2139. #ifdef USE_THICKNESSMAP
  2140. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  2141. #endif
  2142. vec3 pos = vWorldPosition;
  2143. vec3 v = normalize( cameraPosition - pos );
  2144. vec3 n = inverseTransformDirection( normal, viewMatrix );
  2145. vec4 transmitted = getIBLVolumeRefraction(
  2146. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  2147. pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
  2148. material.attenuationColor, material.attenuationDistance );
  2149. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  2150. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  2151. #endif`,lve=`#ifdef USE_TRANSMISSION
  2152. uniform float transmission;
  2153. uniform float thickness;
  2154. uniform float attenuationDistance;
  2155. uniform vec3 attenuationColor;
  2156. #ifdef USE_TRANSMISSIONMAP
  2157. uniform sampler2D transmissionMap;
  2158. #endif
  2159. #ifdef USE_THICKNESSMAP
  2160. uniform sampler2D thicknessMap;
  2161. #endif
  2162. uniform vec2 transmissionSamplerSize;
  2163. uniform sampler2D transmissionSamplerMap;
  2164. uniform mat4 modelMatrix;
  2165. uniform mat4 projectionMatrix;
  2166. varying vec3 vWorldPosition;
  2167. float w0( float a ) {
  2168. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  2169. }
  2170. float w1( float a ) {
  2171. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  2172. }
  2173. float w2( float a ){
  2174. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  2175. }
  2176. float w3( float a ) {
  2177. return ( 1.0 / 6.0 ) * ( a * a * a );
  2178. }
  2179. float g0( float a ) {
  2180. return w0( a ) + w1( a );
  2181. }
  2182. float g1( float a ) {
  2183. return w2( a ) + w3( a );
  2184. }
  2185. float h0( float a ) {
  2186. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  2187. }
  2188. float h1( float a ) {
  2189. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  2190. }
  2191. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  2192. uv = uv * texelSize.zw + 0.5;
  2193. vec2 iuv = floor( uv );
  2194. vec2 fuv = fract( uv );
  2195. float g0x = g0( fuv.x );
  2196. float g1x = g1( fuv.x );
  2197. float h0x = h0( fuv.x );
  2198. float h1x = h1( fuv.x );
  2199. float h0y = h0( fuv.y );
  2200. float h1y = h1( fuv.y );
  2201. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2202. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  2203. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2204. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  2205. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  2206. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  2207. }
  2208. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  2209. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  2210. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  2211. vec2 fLodSizeInv = 1.0 / fLodSize;
  2212. vec2 cLodSizeInv = 1.0 / cLodSize;
  2213. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  2214. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  2215. return mix( fSample, cSample, fract( lod ) );
  2216. }
  2217. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  2218. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  2219. vec3 modelScale;
  2220. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  2221. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  2222. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  2223. return normalize( refractionVector ) * thickness * modelScale;
  2224. }
  2225. float applyIorToRoughness( const in float roughness, const in float ior ) {
  2226. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  2227. }
  2228. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  2229. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  2230. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  2231. }
  2232. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  2233. if ( isinf( attenuationDistance ) ) {
  2234. return vec3( 1.0 );
  2235. } else {
  2236. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  2237. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  2238. }
  2239. }
  2240. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  2241. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  2242. const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
  2243. const in vec3 attenuationColor, const in float attenuationDistance ) {
  2244. vec4 transmittedLight;
  2245. vec3 transmittance;
  2246. #ifdef USE_DISPERSION
  2247. float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
  2248. vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
  2249. for ( int i = 0; i < 3; i ++ ) {
  2250. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
  2251. vec3 refractedRayExit = position + transmissionRay;
  2252. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2253. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2254. refractionCoords += 1.0;
  2255. refractionCoords /= 2.0;
  2256. vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
  2257. transmittedLight[ i ] = transmissionSample[ i ];
  2258. transmittedLight.a += transmissionSample.a;
  2259. transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
  2260. }
  2261. transmittedLight.a /= 3.0;
  2262. #else
  2263. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  2264. vec3 refractedRayExit = position + transmissionRay;
  2265. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  2266. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  2267. refractionCoords += 1.0;
  2268. refractionCoords /= 2.0;
  2269. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  2270. transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  2271. #endif
  2272. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  2273. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  2274. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  2275. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  2276. }
  2277. #endif`,cve=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2278. varying vec2 vUv;
  2279. #endif
  2280. #ifdef USE_MAP
  2281. varying vec2 vMapUv;
  2282. #endif
  2283. #ifdef USE_ALPHAMAP
  2284. varying vec2 vAlphaMapUv;
  2285. #endif
  2286. #ifdef USE_LIGHTMAP
  2287. varying vec2 vLightMapUv;
  2288. #endif
  2289. #ifdef USE_AOMAP
  2290. varying vec2 vAoMapUv;
  2291. #endif
  2292. #ifdef USE_BUMPMAP
  2293. varying vec2 vBumpMapUv;
  2294. #endif
  2295. #ifdef USE_NORMALMAP
  2296. varying vec2 vNormalMapUv;
  2297. #endif
  2298. #ifdef USE_EMISSIVEMAP
  2299. varying vec2 vEmissiveMapUv;
  2300. #endif
  2301. #ifdef USE_METALNESSMAP
  2302. varying vec2 vMetalnessMapUv;
  2303. #endif
  2304. #ifdef USE_ROUGHNESSMAP
  2305. varying vec2 vRoughnessMapUv;
  2306. #endif
  2307. #ifdef USE_ANISOTROPYMAP
  2308. varying vec2 vAnisotropyMapUv;
  2309. #endif
  2310. #ifdef USE_CLEARCOATMAP
  2311. varying vec2 vClearcoatMapUv;
  2312. #endif
  2313. #ifdef USE_CLEARCOAT_NORMALMAP
  2314. varying vec2 vClearcoatNormalMapUv;
  2315. #endif
  2316. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2317. varying vec2 vClearcoatRoughnessMapUv;
  2318. #endif
  2319. #ifdef USE_IRIDESCENCEMAP
  2320. varying vec2 vIridescenceMapUv;
  2321. #endif
  2322. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2323. varying vec2 vIridescenceThicknessMapUv;
  2324. #endif
  2325. #ifdef USE_SHEEN_COLORMAP
  2326. varying vec2 vSheenColorMapUv;
  2327. #endif
  2328. #ifdef USE_SHEEN_ROUGHNESSMAP
  2329. varying vec2 vSheenRoughnessMapUv;
  2330. #endif
  2331. #ifdef USE_SPECULARMAP
  2332. varying vec2 vSpecularMapUv;
  2333. #endif
  2334. #ifdef USE_SPECULAR_COLORMAP
  2335. varying vec2 vSpecularColorMapUv;
  2336. #endif
  2337. #ifdef USE_SPECULAR_INTENSITYMAP
  2338. varying vec2 vSpecularIntensityMapUv;
  2339. #endif
  2340. #ifdef USE_TRANSMISSIONMAP
  2341. uniform mat3 transmissionMapTransform;
  2342. varying vec2 vTransmissionMapUv;
  2343. #endif
  2344. #ifdef USE_THICKNESSMAP
  2345. uniform mat3 thicknessMapTransform;
  2346. varying vec2 vThicknessMapUv;
  2347. #endif`,uve=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2348. varying vec2 vUv;
  2349. #endif
  2350. #ifdef USE_MAP
  2351. uniform mat3 mapTransform;
  2352. varying vec2 vMapUv;
  2353. #endif
  2354. #ifdef USE_ALPHAMAP
  2355. uniform mat3 alphaMapTransform;
  2356. varying vec2 vAlphaMapUv;
  2357. #endif
  2358. #ifdef USE_LIGHTMAP
  2359. uniform mat3 lightMapTransform;
  2360. varying vec2 vLightMapUv;
  2361. #endif
  2362. #ifdef USE_AOMAP
  2363. uniform mat3 aoMapTransform;
  2364. varying vec2 vAoMapUv;
  2365. #endif
  2366. #ifdef USE_BUMPMAP
  2367. uniform mat3 bumpMapTransform;
  2368. varying vec2 vBumpMapUv;
  2369. #endif
  2370. #ifdef USE_NORMALMAP
  2371. uniform mat3 normalMapTransform;
  2372. varying vec2 vNormalMapUv;
  2373. #endif
  2374. #ifdef USE_DISPLACEMENTMAP
  2375. uniform mat3 displacementMapTransform;
  2376. varying vec2 vDisplacementMapUv;
  2377. #endif
  2378. #ifdef USE_EMISSIVEMAP
  2379. uniform mat3 emissiveMapTransform;
  2380. varying vec2 vEmissiveMapUv;
  2381. #endif
  2382. #ifdef USE_METALNESSMAP
  2383. uniform mat3 metalnessMapTransform;
  2384. varying vec2 vMetalnessMapUv;
  2385. #endif
  2386. #ifdef USE_ROUGHNESSMAP
  2387. uniform mat3 roughnessMapTransform;
  2388. varying vec2 vRoughnessMapUv;
  2389. #endif
  2390. #ifdef USE_ANISOTROPYMAP
  2391. uniform mat3 anisotropyMapTransform;
  2392. varying vec2 vAnisotropyMapUv;
  2393. #endif
  2394. #ifdef USE_CLEARCOATMAP
  2395. uniform mat3 clearcoatMapTransform;
  2396. varying vec2 vClearcoatMapUv;
  2397. #endif
  2398. #ifdef USE_CLEARCOAT_NORMALMAP
  2399. uniform mat3 clearcoatNormalMapTransform;
  2400. varying vec2 vClearcoatNormalMapUv;
  2401. #endif
  2402. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2403. uniform mat3 clearcoatRoughnessMapTransform;
  2404. varying vec2 vClearcoatRoughnessMapUv;
  2405. #endif
  2406. #ifdef USE_SHEEN_COLORMAP
  2407. uniform mat3 sheenColorMapTransform;
  2408. varying vec2 vSheenColorMapUv;
  2409. #endif
  2410. #ifdef USE_SHEEN_ROUGHNESSMAP
  2411. uniform mat3 sheenRoughnessMapTransform;
  2412. varying vec2 vSheenRoughnessMapUv;
  2413. #endif
  2414. #ifdef USE_IRIDESCENCEMAP
  2415. uniform mat3 iridescenceMapTransform;
  2416. varying vec2 vIridescenceMapUv;
  2417. #endif
  2418. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2419. uniform mat3 iridescenceThicknessMapTransform;
  2420. varying vec2 vIridescenceThicknessMapUv;
  2421. #endif
  2422. #ifdef USE_SPECULARMAP
  2423. uniform mat3 specularMapTransform;
  2424. varying vec2 vSpecularMapUv;
  2425. #endif
  2426. #ifdef USE_SPECULAR_COLORMAP
  2427. uniform mat3 specularColorMapTransform;
  2428. varying vec2 vSpecularColorMapUv;
  2429. #endif
  2430. #ifdef USE_SPECULAR_INTENSITYMAP
  2431. uniform mat3 specularIntensityMapTransform;
  2432. varying vec2 vSpecularIntensityMapUv;
  2433. #endif
  2434. #ifdef USE_TRANSMISSIONMAP
  2435. uniform mat3 transmissionMapTransform;
  2436. varying vec2 vTransmissionMapUv;
  2437. #endif
  2438. #ifdef USE_THICKNESSMAP
  2439. uniform mat3 thicknessMapTransform;
  2440. varying vec2 vThicknessMapUv;
  2441. #endif`,dve=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  2442. vUv = vec3( uv, 1 ).xy;
  2443. #endif
  2444. #ifdef USE_MAP
  2445. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  2446. #endif
  2447. #ifdef USE_ALPHAMAP
  2448. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  2449. #endif
  2450. #ifdef USE_LIGHTMAP
  2451. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  2452. #endif
  2453. #ifdef USE_AOMAP
  2454. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  2455. #endif
  2456. #ifdef USE_BUMPMAP
  2457. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  2458. #endif
  2459. #ifdef USE_NORMALMAP
  2460. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  2461. #endif
  2462. #ifdef USE_DISPLACEMENTMAP
  2463. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  2464. #endif
  2465. #ifdef USE_EMISSIVEMAP
  2466. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  2467. #endif
  2468. #ifdef USE_METALNESSMAP
  2469. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  2470. #endif
  2471. #ifdef USE_ROUGHNESSMAP
  2472. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  2473. #endif
  2474. #ifdef USE_ANISOTROPYMAP
  2475. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  2476. #endif
  2477. #ifdef USE_CLEARCOATMAP
  2478. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  2479. #endif
  2480. #ifdef USE_CLEARCOAT_NORMALMAP
  2481. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  2482. #endif
  2483. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  2484. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  2485. #endif
  2486. #ifdef USE_IRIDESCENCEMAP
  2487. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  2488. #endif
  2489. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  2490. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  2491. #endif
  2492. #ifdef USE_SHEEN_COLORMAP
  2493. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  2494. #endif
  2495. #ifdef USE_SHEEN_ROUGHNESSMAP
  2496. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  2497. #endif
  2498. #ifdef USE_SPECULARMAP
  2499. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  2500. #endif
  2501. #ifdef USE_SPECULAR_COLORMAP
  2502. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  2503. #endif
  2504. #ifdef USE_SPECULAR_INTENSITYMAP
  2505. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  2506. #endif
  2507. #ifdef USE_TRANSMISSIONMAP
  2508. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  2509. #endif
  2510. #ifdef USE_THICKNESSMAP
  2511. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  2512. #endif`,hve=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  2513. vec4 worldPosition = vec4( transformed, 1.0 );
  2514. #ifdef USE_BATCHING
  2515. worldPosition = batchingMatrix * worldPosition;
  2516. #endif
  2517. #ifdef USE_INSTANCING
  2518. worldPosition = instanceMatrix * worldPosition;
  2519. #endif
  2520. worldPosition = modelMatrix * worldPosition;
  2521. #endif`;const mve=`varying vec2 vUv;
  2522. uniform mat3 uvTransform;
  2523. void main() {
  2524. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  2525. gl_Position = vec4( position.xy, 1.0, 1.0 );
  2526. }`,fve=`uniform sampler2D t2D;
  2527. uniform float backgroundIntensity;
  2528. varying vec2 vUv;
  2529. void main() {
  2530. vec4 texColor = texture2D( t2D, vUv );
  2531. #ifdef DECODE_VIDEO_TEXTURE
  2532. texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
  2533. #endif
  2534. texColor.rgb *= backgroundIntensity;
  2535. gl_FragColor = texColor;
  2536. #include <tonemapping_fragment>
  2537. #include <colorspace_fragment>
  2538. }`,pve=`varying vec3 vWorldDirection;
  2539. #include <common>
  2540. void main() {
  2541. vWorldDirection = transformDirection( position, modelMatrix );
  2542. #include <begin_vertex>
  2543. #include <project_vertex>
  2544. gl_Position.z = gl_Position.w;
  2545. }`,gve=`#ifdef ENVMAP_TYPE_CUBE
  2546. uniform samplerCube envMap;
  2547. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2548. uniform sampler2D envMap;
  2549. #endif
  2550. uniform float flipEnvMap;
  2551. uniform float backgroundBlurriness;
  2552. uniform float backgroundIntensity;
  2553. uniform mat3 backgroundRotation;
  2554. varying vec3 vWorldDirection;
  2555. #include <cube_uv_reflection_fragment>
  2556. void main() {
  2557. #ifdef ENVMAP_TYPE_CUBE
  2558. vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  2559. #elif defined( ENVMAP_TYPE_CUBE_UV )
  2560. vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
  2561. #else
  2562. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  2563. #endif
  2564. texColor.rgb *= backgroundIntensity;
  2565. gl_FragColor = texColor;
  2566. #include <tonemapping_fragment>
  2567. #include <colorspace_fragment>
  2568. }`,bve=`varying vec3 vWorldDirection;
  2569. #include <common>
  2570. void main() {
  2571. vWorldDirection = transformDirection( position, modelMatrix );
  2572. #include <begin_vertex>
  2573. #include <project_vertex>
  2574. gl_Position.z = gl_Position.w;
  2575. }`,xve=`uniform samplerCube tCube;
  2576. uniform float tFlip;
  2577. uniform float opacity;
  2578. varying vec3 vWorldDirection;
  2579. void main() {
  2580. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  2581. gl_FragColor = texColor;
  2582. gl_FragColor.a *= opacity;
  2583. #include <tonemapping_fragment>
  2584. #include <colorspace_fragment>
  2585. }`,yve=`#include <common>
  2586. #include <batching_pars_vertex>
  2587. #include <uv_pars_vertex>
  2588. #include <displacementmap_pars_vertex>
  2589. #include <morphtarget_pars_vertex>
  2590. #include <skinning_pars_vertex>
  2591. #include <logdepthbuf_pars_vertex>
  2592. #include <clipping_planes_pars_vertex>
  2593. varying vec2 vHighPrecisionZW;
  2594. void main() {
  2595. #include <uv_vertex>
  2596. #include <batching_vertex>
  2597. #include <skinbase_vertex>
  2598. #include <morphinstance_vertex>
  2599. #ifdef USE_DISPLACEMENTMAP
  2600. #include <beginnormal_vertex>
  2601. #include <morphnormal_vertex>
  2602. #include <skinnormal_vertex>
  2603. #endif
  2604. #include <begin_vertex>
  2605. #include <morphtarget_vertex>
  2606. #include <skinning_vertex>
  2607. #include <displacementmap_vertex>
  2608. #include <project_vertex>
  2609. #include <logdepthbuf_vertex>
  2610. #include <clipping_planes_vertex>
  2611. vHighPrecisionZW = gl_Position.zw;
  2612. }`,vve=`#if DEPTH_PACKING == 3200
  2613. uniform float opacity;
  2614. #endif
  2615. #include <common>
  2616. #include <packing>
  2617. #include <uv_pars_fragment>
  2618. #include <map_pars_fragment>
  2619. #include <alphamap_pars_fragment>
  2620. #include <alphatest_pars_fragment>
  2621. #include <alphahash_pars_fragment>
  2622. #include <logdepthbuf_pars_fragment>
  2623. #include <clipping_planes_pars_fragment>
  2624. varying vec2 vHighPrecisionZW;
  2625. void main() {
  2626. vec4 diffuseColor = vec4( 1.0 );
  2627. #include <clipping_planes_fragment>
  2628. #if DEPTH_PACKING == 3200
  2629. diffuseColor.a = opacity;
  2630. #endif
  2631. #include <map_fragment>
  2632. #include <alphamap_fragment>
  2633. #include <alphatest_fragment>
  2634. #include <alphahash_fragment>
  2635. #include <logdepthbuf_fragment>
  2636. #ifdef USE_REVERSED_DEPTH_BUFFER
  2637. float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
  2638. #else
  2639. float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
  2640. #endif
  2641. #if DEPTH_PACKING == 3200
  2642. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  2643. #elif DEPTH_PACKING == 3201
  2644. gl_FragColor = packDepthToRGBA( fragCoordZ );
  2645. #elif DEPTH_PACKING == 3202
  2646. gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
  2647. #elif DEPTH_PACKING == 3203
  2648. gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
  2649. #endif
  2650. }`,wve=`#define DISTANCE
  2651. varying vec3 vWorldPosition;
  2652. #include <common>
  2653. #include <batching_pars_vertex>
  2654. #include <uv_pars_vertex>
  2655. #include <displacementmap_pars_vertex>
  2656. #include <morphtarget_pars_vertex>
  2657. #include <skinning_pars_vertex>
  2658. #include <clipping_planes_pars_vertex>
  2659. void main() {
  2660. #include <uv_vertex>
  2661. #include <batching_vertex>
  2662. #include <skinbase_vertex>
  2663. #include <morphinstance_vertex>
  2664. #ifdef USE_DISPLACEMENTMAP
  2665. #include <beginnormal_vertex>
  2666. #include <morphnormal_vertex>
  2667. #include <skinnormal_vertex>
  2668. #endif
  2669. #include <begin_vertex>
  2670. #include <morphtarget_vertex>
  2671. #include <skinning_vertex>
  2672. #include <displacementmap_vertex>
  2673. #include <project_vertex>
  2674. #include <worldpos_vertex>
  2675. #include <clipping_planes_vertex>
  2676. vWorldPosition = worldPosition.xyz;
  2677. }`,Sve=`#define DISTANCE
  2678. uniform vec3 referencePosition;
  2679. uniform float nearDistance;
  2680. uniform float farDistance;
  2681. varying vec3 vWorldPosition;
  2682. #include <common>
  2683. #include <packing>
  2684. #include <uv_pars_fragment>
  2685. #include <map_pars_fragment>
  2686. #include <alphamap_pars_fragment>
  2687. #include <alphatest_pars_fragment>
  2688. #include <alphahash_pars_fragment>
  2689. #include <clipping_planes_pars_fragment>
  2690. void main () {
  2691. vec4 diffuseColor = vec4( 1.0 );
  2692. #include <clipping_planes_fragment>
  2693. #include <map_fragment>
  2694. #include <alphamap_fragment>
  2695. #include <alphatest_fragment>
  2696. #include <alphahash_fragment>
  2697. float dist = length( vWorldPosition - referencePosition );
  2698. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  2699. dist = saturate( dist );
  2700. gl_FragColor = packDepthToRGBA( dist );
  2701. }`,_ve=`varying vec3 vWorldDirection;
  2702. #include <common>
  2703. void main() {
  2704. vWorldDirection = transformDirection( position, modelMatrix );
  2705. #include <begin_vertex>
  2706. #include <project_vertex>
  2707. }`,Nve=`uniform sampler2D tEquirect;
  2708. varying vec3 vWorldDirection;
  2709. #include <common>
  2710. void main() {
  2711. vec3 direction = normalize( vWorldDirection );
  2712. vec2 sampleUV = equirectUv( direction );
  2713. gl_FragColor = texture2D( tEquirect, sampleUV );
  2714. #include <tonemapping_fragment>
  2715. #include <colorspace_fragment>
  2716. }`,Cve=`uniform float scale;
  2717. attribute float lineDistance;
  2718. varying float vLineDistance;
  2719. #include <common>
  2720. #include <uv_pars_vertex>
  2721. #include <color_pars_vertex>
  2722. #include <fog_pars_vertex>
  2723. #include <morphtarget_pars_vertex>
  2724. #include <logdepthbuf_pars_vertex>
  2725. #include <clipping_planes_pars_vertex>
  2726. void main() {
  2727. vLineDistance = scale * lineDistance;
  2728. #include <uv_vertex>
  2729. #include <color_vertex>
  2730. #include <morphinstance_vertex>
  2731. #include <morphcolor_vertex>
  2732. #include <begin_vertex>
  2733. #include <morphtarget_vertex>
  2734. #include <project_vertex>
  2735. #include <logdepthbuf_vertex>
  2736. #include <clipping_planes_vertex>
  2737. #include <fog_vertex>
  2738. }`,kve=`uniform vec3 diffuse;
  2739. uniform float opacity;
  2740. uniform float dashSize;
  2741. uniform float totalSize;
  2742. varying float vLineDistance;
  2743. #include <common>
  2744. #include <color_pars_fragment>
  2745. #include <uv_pars_fragment>
  2746. #include <map_pars_fragment>
  2747. #include <fog_pars_fragment>
  2748. #include <logdepthbuf_pars_fragment>
  2749. #include <clipping_planes_pars_fragment>
  2750. void main() {
  2751. vec4 diffuseColor = vec4( diffuse, opacity );
  2752. #include <clipping_planes_fragment>
  2753. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  2754. discard;
  2755. }
  2756. vec3 outgoingLight = vec3( 0.0 );
  2757. #include <logdepthbuf_fragment>
  2758. #include <map_fragment>
  2759. #include <color_fragment>
  2760. outgoingLight = diffuseColor.rgb;
  2761. #include <opaque_fragment>
  2762. #include <tonemapping_fragment>
  2763. #include <colorspace_fragment>
  2764. #include <fog_fragment>
  2765. #include <premultiplied_alpha_fragment>
  2766. }`,Ave=`#include <common>
  2767. #include <batching_pars_vertex>
  2768. #include <uv_pars_vertex>
  2769. #include <envmap_pars_vertex>
  2770. #include <color_pars_vertex>
  2771. #include <fog_pars_vertex>
  2772. #include <morphtarget_pars_vertex>
  2773. #include <skinning_pars_vertex>
  2774. #include <logdepthbuf_pars_vertex>
  2775. #include <clipping_planes_pars_vertex>
  2776. void main() {
  2777. #include <uv_vertex>
  2778. #include <color_vertex>
  2779. #include <morphinstance_vertex>
  2780. #include <morphcolor_vertex>
  2781. #include <batching_vertex>
  2782. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  2783. #include <beginnormal_vertex>
  2784. #include <morphnormal_vertex>
  2785. #include <skinbase_vertex>
  2786. #include <skinnormal_vertex>
  2787. #include <defaultnormal_vertex>
  2788. #endif
  2789. #include <begin_vertex>
  2790. #include <morphtarget_vertex>
  2791. #include <skinning_vertex>
  2792. #include <project_vertex>
  2793. #include <logdepthbuf_vertex>
  2794. #include <clipping_planes_vertex>
  2795. #include <worldpos_vertex>
  2796. #include <envmap_vertex>
  2797. #include <fog_vertex>
  2798. }`,Tve=`uniform vec3 diffuse;
  2799. uniform float opacity;
  2800. #ifndef FLAT_SHADED
  2801. varying vec3 vNormal;
  2802. #endif
  2803. #include <common>
  2804. #include <dithering_pars_fragment>
  2805. #include <color_pars_fragment>
  2806. #include <uv_pars_fragment>
  2807. #include <map_pars_fragment>
  2808. #include <alphamap_pars_fragment>
  2809. #include <alphatest_pars_fragment>
  2810. #include <alphahash_pars_fragment>
  2811. #include <aomap_pars_fragment>
  2812. #include <lightmap_pars_fragment>
  2813. #include <envmap_common_pars_fragment>
  2814. #include <envmap_pars_fragment>
  2815. #include <fog_pars_fragment>
  2816. #include <specularmap_pars_fragment>
  2817. #include <logdepthbuf_pars_fragment>
  2818. #include <clipping_planes_pars_fragment>
  2819. void main() {
  2820. vec4 diffuseColor = vec4( diffuse, opacity );
  2821. #include <clipping_planes_fragment>
  2822. #include <logdepthbuf_fragment>
  2823. #include <map_fragment>
  2824. #include <color_fragment>
  2825. #include <alphamap_fragment>
  2826. #include <alphatest_fragment>
  2827. #include <alphahash_fragment>
  2828. #include <specularmap_fragment>
  2829. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2830. #ifdef USE_LIGHTMAP
  2831. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  2832. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  2833. #else
  2834. reflectedLight.indirectDiffuse += vec3( 1.0 );
  2835. #endif
  2836. #include <aomap_fragment>
  2837. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  2838. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  2839. #include <envmap_fragment>
  2840. #include <opaque_fragment>
  2841. #include <tonemapping_fragment>
  2842. #include <colorspace_fragment>
  2843. #include <fog_fragment>
  2844. #include <premultiplied_alpha_fragment>
  2845. #include <dithering_fragment>
  2846. }`,Mve=`#define LAMBERT
  2847. varying vec3 vViewPosition;
  2848. #include <common>
  2849. #include <batching_pars_vertex>
  2850. #include <uv_pars_vertex>
  2851. #include <displacementmap_pars_vertex>
  2852. #include <envmap_pars_vertex>
  2853. #include <color_pars_vertex>
  2854. #include <fog_pars_vertex>
  2855. #include <normal_pars_vertex>
  2856. #include <morphtarget_pars_vertex>
  2857. #include <skinning_pars_vertex>
  2858. #include <shadowmap_pars_vertex>
  2859. #include <logdepthbuf_pars_vertex>
  2860. #include <clipping_planes_pars_vertex>
  2861. void main() {
  2862. #include <uv_vertex>
  2863. #include <color_vertex>
  2864. #include <morphinstance_vertex>
  2865. #include <morphcolor_vertex>
  2866. #include <batching_vertex>
  2867. #include <beginnormal_vertex>
  2868. #include <morphnormal_vertex>
  2869. #include <skinbase_vertex>
  2870. #include <skinnormal_vertex>
  2871. #include <defaultnormal_vertex>
  2872. #include <normal_vertex>
  2873. #include <begin_vertex>
  2874. #include <morphtarget_vertex>
  2875. #include <skinning_vertex>
  2876. #include <displacementmap_vertex>
  2877. #include <project_vertex>
  2878. #include <logdepthbuf_vertex>
  2879. #include <clipping_planes_vertex>
  2880. vViewPosition = - mvPosition.xyz;
  2881. #include <worldpos_vertex>
  2882. #include <envmap_vertex>
  2883. #include <shadowmap_vertex>
  2884. #include <fog_vertex>
  2885. }`,Pve=`#define LAMBERT
  2886. uniform vec3 diffuse;
  2887. uniform vec3 emissive;
  2888. uniform float opacity;
  2889. #include <common>
  2890. #include <packing>
  2891. #include <dithering_pars_fragment>
  2892. #include <color_pars_fragment>
  2893. #include <uv_pars_fragment>
  2894. #include <map_pars_fragment>
  2895. #include <alphamap_pars_fragment>
  2896. #include <alphatest_pars_fragment>
  2897. #include <alphahash_pars_fragment>
  2898. #include <aomap_pars_fragment>
  2899. #include <lightmap_pars_fragment>
  2900. #include <emissivemap_pars_fragment>
  2901. #include <envmap_common_pars_fragment>
  2902. #include <envmap_pars_fragment>
  2903. #include <fog_pars_fragment>
  2904. #include <bsdfs>
  2905. #include <lights_pars_begin>
  2906. #include <normal_pars_fragment>
  2907. #include <lights_lambert_pars_fragment>
  2908. #include <shadowmap_pars_fragment>
  2909. #include <bumpmap_pars_fragment>
  2910. #include <normalmap_pars_fragment>
  2911. #include <specularmap_pars_fragment>
  2912. #include <logdepthbuf_pars_fragment>
  2913. #include <clipping_planes_pars_fragment>
  2914. void main() {
  2915. vec4 diffuseColor = vec4( diffuse, opacity );
  2916. #include <clipping_planes_fragment>
  2917. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  2918. vec3 totalEmissiveRadiance = emissive;
  2919. #include <logdepthbuf_fragment>
  2920. #include <map_fragment>
  2921. #include <color_fragment>
  2922. #include <alphamap_fragment>
  2923. #include <alphatest_fragment>
  2924. #include <alphahash_fragment>
  2925. #include <specularmap_fragment>
  2926. #include <normal_fragment_begin>
  2927. #include <normal_fragment_maps>
  2928. #include <emissivemap_fragment>
  2929. #include <lights_lambert_fragment>
  2930. #include <lights_fragment_begin>
  2931. #include <lights_fragment_maps>
  2932. #include <lights_fragment_end>
  2933. #include <aomap_fragment>
  2934. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  2935. #include <envmap_fragment>
  2936. #include <opaque_fragment>
  2937. #include <tonemapping_fragment>
  2938. #include <colorspace_fragment>
  2939. #include <fog_fragment>
  2940. #include <premultiplied_alpha_fragment>
  2941. #include <dithering_fragment>
  2942. }`,Eve=`#define MATCAP
  2943. varying vec3 vViewPosition;
  2944. #include <common>
  2945. #include <batching_pars_vertex>
  2946. #include <uv_pars_vertex>
  2947. #include <color_pars_vertex>
  2948. #include <displacementmap_pars_vertex>
  2949. #include <fog_pars_vertex>
  2950. #include <normal_pars_vertex>
  2951. #include <morphtarget_pars_vertex>
  2952. #include <skinning_pars_vertex>
  2953. #include <logdepthbuf_pars_vertex>
  2954. #include <clipping_planes_pars_vertex>
  2955. void main() {
  2956. #include <uv_vertex>
  2957. #include <color_vertex>
  2958. #include <morphinstance_vertex>
  2959. #include <morphcolor_vertex>
  2960. #include <batching_vertex>
  2961. #include <beginnormal_vertex>
  2962. #include <morphnormal_vertex>
  2963. #include <skinbase_vertex>
  2964. #include <skinnormal_vertex>
  2965. #include <defaultnormal_vertex>
  2966. #include <normal_vertex>
  2967. #include <begin_vertex>
  2968. #include <morphtarget_vertex>
  2969. #include <skinning_vertex>
  2970. #include <displacementmap_vertex>
  2971. #include <project_vertex>
  2972. #include <logdepthbuf_vertex>
  2973. #include <clipping_planes_vertex>
  2974. #include <fog_vertex>
  2975. vViewPosition = - mvPosition.xyz;
  2976. }`,jve=`#define MATCAP
  2977. uniform vec3 diffuse;
  2978. uniform float opacity;
  2979. uniform sampler2D matcap;
  2980. varying vec3 vViewPosition;
  2981. #include <common>
  2982. #include <dithering_pars_fragment>
  2983. #include <color_pars_fragment>
  2984. #include <uv_pars_fragment>
  2985. #include <map_pars_fragment>
  2986. #include <alphamap_pars_fragment>
  2987. #include <alphatest_pars_fragment>
  2988. #include <alphahash_pars_fragment>
  2989. #include <fog_pars_fragment>
  2990. #include <normal_pars_fragment>
  2991. #include <bumpmap_pars_fragment>
  2992. #include <normalmap_pars_fragment>
  2993. #include <logdepthbuf_pars_fragment>
  2994. #include <clipping_planes_pars_fragment>
  2995. void main() {
  2996. vec4 diffuseColor = vec4( diffuse, opacity );
  2997. #include <clipping_planes_fragment>
  2998. #include <logdepthbuf_fragment>
  2999. #include <map_fragment>
  3000. #include <color_fragment>
  3001. #include <alphamap_fragment>
  3002. #include <alphatest_fragment>
  3003. #include <alphahash_fragment>
  3004. #include <normal_fragment_begin>
  3005. #include <normal_fragment_maps>
  3006. vec3 viewDir = normalize( vViewPosition );
  3007. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  3008. vec3 y = cross( viewDir, x );
  3009. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  3010. #ifdef USE_MATCAP
  3011. vec4 matcapColor = texture2D( matcap, uv );
  3012. #else
  3013. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  3014. #endif
  3015. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  3016. #include <opaque_fragment>
  3017. #include <tonemapping_fragment>
  3018. #include <colorspace_fragment>
  3019. #include <fog_fragment>
  3020. #include <premultiplied_alpha_fragment>
  3021. #include <dithering_fragment>
  3022. }`,Dve=`#define NORMAL
  3023. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3024. varying vec3 vViewPosition;
  3025. #endif
  3026. #include <common>
  3027. #include <batching_pars_vertex>
  3028. #include <uv_pars_vertex>
  3029. #include <displacementmap_pars_vertex>
  3030. #include <normal_pars_vertex>
  3031. #include <morphtarget_pars_vertex>
  3032. #include <skinning_pars_vertex>
  3033. #include <logdepthbuf_pars_vertex>
  3034. #include <clipping_planes_pars_vertex>
  3035. void main() {
  3036. #include <uv_vertex>
  3037. #include <batching_vertex>
  3038. #include <beginnormal_vertex>
  3039. #include <morphinstance_vertex>
  3040. #include <morphnormal_vertex>
  3041. #include <skinbase_vertex>
  3042. #include <skinnormal_vertex>
  3043. #include <defaultnormal_vertex>
  3044. #include <normal_vertex>
  3045. #include <begin_vertex>
  3046. #include <morphtarget_vertex>
  3047. #include <skinning_vertex>
  3048. #include <displacementmap_vertex>
  3049. #include <project_vertex>
  3050. #include <logdepthbuf_vertex>
  3051. #include <clipping_planes_vertex>
  3052. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3053. vViewPosition = - mvPosition.xyz;
  3054. #endif
  3055. }`,Rve=`#define NORMAL
  3056. uniform float opacity;
  3057. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  3058. varying vec3 vViewPosition;
  3059. #endif
  3060. #include <packing>
  3061. #include <uv_pars_fragment>
  3062. #include <normal_pars_fragment>
  3063. #include <bumpmap_pars_fragment>
  3064. #include <normalmap_pars_fragment>
  3065. #include <logdepthbuf_pars_fragment>
  3066. #include <clipping_planes_pars_fragment>
  3067. void main() {
  3068. vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
  3069. #include <clipping_planes_fragment>
  3070. #include <logdepthbuf_fragment>
  3071. #include <normal_fragment_begin>
  3072. #include <normal_fragment_maps>
  3073. gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
  3074. #ifdef OPAQUE
  3075. gl_FragColor.a = 1.0;
  3076. #endif
  3077. }`,Fve=`#define PHONG
  3078. varying vec3 vViewPosition;
  3079. #include <common>
  3080. #include <batching_pars_vertex>
  3081. #include <uv_pars_vertex>
  3082. #include <displacementmap_pars_vertex>
  3083. #include <envmap_pars_vertex>
  3084. #include <color_pars_vertex>
  3085. #include <fog_pars_vertex>
  3086. #include <normal_pars_vertex>
  3087. #include <morphtarget_pars_vertex>
  3088. #include <skinning_pars_vertex>
  3089. #include <shadowmap_pars_vertex>
  3090. #include <logdepthbuf_pars_vertex>
  3091. #include <clipping_planes_pars_vertex>
  3092. void main() {
  3093. #include <uv_vertex>
  3094. #include <color_vertex>
  3095. #include <morphcolor_vertex>
  3096. #include <batching_vertex>
  3097. #include <beginnormal_vertex>
  3098. #include <morphinstance_vertex>
  3099. #include <morphnormal_vertex>
  3100. #include <skinbase_vertex>
  3101. #include <skinnormal_vertex>
  3102. #include <defaultnormal_vertex>
  3103. #include <normal_vertex>
  3104. #include <begin_vertex>
  3105. #include <morphtarget_vertex>
  3106. #include <skinning_vertex>
  3107. #include <displacementmap_vertex>
  3108. #include <project_vertex>
  3109. #include <logdepthbuf_vertex>
  3110. #include <clipping_planes_vertex>
  3111. vViewPosition = - mvPosition.xyz;
  3112. #include <worldpos_vertex>
  3113. #include <envmap_vertex>
  3114. #include <shadowmap_vertex>
  3115. #include <fog_vertex>
  3116. }`,Lve=`#define PHONG
  3117. uniform vec3 diffuse;
  3118. uniform vec3 emissive;
  3119. uniform vec3 specular;
  3120. uniform float shininess;
  3121. uniform float opacity;
  3122. #include <common>
  3123. #include <packing>
  3124. #include <dithering_pars_fragment>
  3125. #include <color_pars_fragment>
  3126. #include <uv_pars_fragment>
  3127. #include <map_pars_fragment>
  3128. #include <alphamap_pars_fragment>
  3129. #include <alphatest_pars_fragment>
  3130. #include <alphahash_pars_fragment>
  3131. #include <aomap_pars_fragment>
  3132. #include <lightmap_pars_fragment>
  3133. #include <emissivemap_pars_fragment>
  3134. #include <envmap_common_pars_fragment>
  3135. #include <envmap_pars_fragment>
  3136. #include <fog_pars_fragment>
  3137. #include <bsdfs>
  3138. #include <lights_pars_begin>
  3139. #include <normal_pars_fragment>
  3140. #include <lights_phong_pars_fragment>
  3141. #include <shadowmap_pars_fragment>
  3142. #include <bumpmap_pars_fragment>
  3143. #include <normalmap_pars_fragment>
  3144. #include <specularmap_pars_fragment>
  3145. #include <logdepthbuf_pars_fragment>
  3146. #include <clipping_planes_pars_fragment>
  3147. void main() {
  3148. vec4 diffuseColor = vec4( diffuse, opacity );
  3149. #include <clipping_planes_fragment>
  3150. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3151. vec3 totalEmissiveRadiance = emissive;
  3152. #include <logdepthbuf_fragment>
  3153. #include <map_fragment>
  3154. #include <color_fragment>
  3155. #include <alphamap_fragment>
  3156. #include <alphatest_fragment>
  3157. #include <alphahash_fragment>
  3158. #include <specularmap_fragment>
  3159. #include <normal_fragment_begin>
  3160. #include <normal_fragment_maps>
  3161. #include <emissivemap_fragment>
  3162. #include <lights_phong_fragment>
  3163. #include <lights_fragment_begin>
  3164. #include <lights_fragment_maps>
  3165. #include <lights_fragment_end>
  3166. #include <aomap_fragment>
  3167. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  3168. #include <envmap_fragment>
  3169. #include <opaque_fragment>
  3170. #include <tonemapping_fragment>
  3171. #include <colorspace_fragment>
  3172. #include <fog_fragment>
  3173. #include <premultiplied_alpha_fragment>
  3174. #include <dithering_fragment>
  3175. }`,Ove=`#define STANDARD
  3176. varying vec3 vViewPosition;
  3177. #ifdef USE_TRANSMISSION
  3178. varying vec3 vWorldPosition;
  3179. #endif
  3180. #include <common>
  3181. #include <batching_pars_vertex>
  3182. #include <uv_pars_vertex>
  3183. #include <displacementmap_pars_vertex>
  3184. #include <color_pars_vertex>
  3185. #include <fog_pars_vertex>
  3186. #include <normal_pars_vertex>
  3187. #include <morphtarget_pars_vertex>
  3188. #include <skinning_pars_vertex>
  3189. #include <shadowmap_pars_vertex>
  3190. #include <logdepthbuf_pars_vertex>
  3191. #include <clipping_planes_pars_vertex>
  3192. void main() {
  3193. #include <uv_vertex>
  3194. #include <color_vertex>
  3195. #include <morphinstance_vertex>
  3196. #include <morphcolor_vertex>
  3197. #include <batching_vertex>
  3198. #include <beginnormal_vertex>
  3199. #include <morphnormal_vertex>
  3200. #include <skinbase_vertex>
  3201. #include <skinnormal_vertex>
  3202. #include <defaultnormal_vertex>
  3203. #include <normal_vertex>
  3204. #include <begin_vertex>
  3205. #include <morphtarget_vertex>
  3206. #include <skinning_vertex>
  3207. #include <displacementmap_vertex>
  3208. #include <project_vertex>
  3209. #include <logdepthbuf_vertex>
  3210. #include <clipping_planes_vertex>
  3211. vViewPosition = - mvPosition.xyz;
  3212. #include <worldpos_vertex>
  3213. #include <shadowmap_vertex>
  3214. #include <fog_vertex>
  3215. #ifdef USE_TRANSMISSION
  3216. vWorldPosition = worldPosition.xyz;
  3217. #endif
  3218. }`,Ive=`#define STANDARD
  3219. #ifdef PHYSICAL
  3220. #define IOR
  3221. #define USE_SPECULAR
  3222. #endif
  3223. uniform vec3 diffuse;
  3224. uniform vec3 emissive;
  3225. uniform float roughness;
  3226. uniform float metalness;
  3227. uniform float opacity;
  3228. #ifdef IOR
  3229. uniform float ior;
  3230. #endif
  3231. #ifdef USE_SPECULAR
  3232. uniform float specularIntensity;
  3233. uniform vec3 specularColor;
  3234. #ifdef USE_SPECULAR_COLORMAP
  3235. uniform sampler2D specularColorMap;
  3236. #endif
  3237. #ifdef USE_SPECULAR_INTENSITYMAP
  3238. uniform sampler2D specularIntensityMap;
  3239. #endif
  3240. #endif
  3241. #ifdef USE_CLEARCOAT
  3242. uniform float clearcoat;
  3243. uniform float clearcoatRoughness;
  3244. #endif
  3245. #ifdef USE_DISPERSION
  3246. uniform float dispersion;
  3247. #endif
  3248. #ifdef USE_IRIDESCENCE
  3249. uniform float iridescence;
  3250. uniform float iridescenceIOR;
  3251. uniform float iridescenceThicknessMinimum;
  3252. uniform float iridescenceThicknessMaximum;
  3253. #endif
  3254. #ifdef USE_SHEEN
  3255. uniform vec3 sheenColor;
  3256. uniform float sheenRoughness;
  3257. #ifdef USE_SHEEN_COLORMAP
  3258. uniform sampler2D sheenColorMap;
  3259. #endif
  3260. #ifdef USE_SHEEN_ROUGHNESSMAP
  3261. uniform sampler2D sheenRoughnessMap;
  3262. #endif
  3263. #endif
  3264. #ifdef USE_ANISOTROPY
  3265. uniform vec2 anisotropyVector;
  3266. #ifdef USE_ANISOTROPYMAP
  3267. uniform sampler2D anisotropyMap;
  3268. #endif
  3269. #endif
  3270. varying vec3 vViewPosition;
  3271. #include <common>
  3272. #include <packing>
  3273. #include <dithering_pars_fragment>
  3274. #include <color_pars_fragment>
  3275. #include <uv_pars_fragment>
  3276. #include <map_pars_fragment>
  3277. #include <alphamap_pars_fragment>
  3278. #include <alphatest_pars_fragment>
  3279. #include <alphahash_pars_fragment>
  3280. #include <aomap_pars_fragment>
  3281. #include <lightmap_pars_fragment>
  3282. #include <emissivemap_pars_fragment>
  3283. #include <iridescence_fragment>
  3284. #include <cube_uv_reflection_fragment>
  3285. #include <envmap_common_pars_fragment>
  3286. #include <envmap_physical_pars_fragment>
  3287. #include <fog_pars_fragment>
  3288. #include <lights_pars_begin>
  3289. #include <normal_pars_fragment>
  3290. #include <lights_physical_pars_fragment>
  3291. #include <transmission_pars_fragment>
  3292. #include <shadowmap_pars_fragment>
  3293. #include <bumpmap_pars_fragment>
  3294. #include <normalmap_pars_fragment>
  3295. #include <clearcoat_pars_fragment>
  3296. #include <iridescence_pars_fragment>
  3297. #include <roughnessmap_pars_fragment>
  3298. #include <metalnessmap_pars_fragment>
  3299. #include <logdepthbuf_pars_fragment>
  3300. #include <clipping_planes_pars_fragment>
  3301. void main() {
  3302. vec4 diffuseColor = vec4( diffuse, opacity );
  3303. #include <clipping_planes_fragment>
  3304. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3305. vec3 totalEmissiveRadiance = emissive;
  3306. #include <logdepthbuf_fragment>
  3307. #include <map_fragment>
  3308. #include <color_fragment>
  3309. #include <alphamap_fragment>
  3310. #include <alphatest_fragment>
  3311. #include <alphahash_fragment>
  3312. #include <roughnessmap_fragment>
  3313. #include <metalnessmap_fragment>
  3314. #include <normal_fragment_begin>
  3315. #include <normal_fragment_maps>
  3316. #include <clearcoat_normal_fragment_begin>
  3317. #include <clearcoat_normal_fragment_maps>
  3318. #include <emissivemap_fragment>
  3319. #include <lights_physical_fragment>
  3320. #include <lights_fragment_begin>
  3321. #include <lights_fragment_maps>
  3322. #include <lights_fragment_end>
  3323. #include <aomap_fragment>
  3324. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  3325. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  3326. #include <transmission_fragment>
  3327. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  3328. #ifdef USE_SHEEN
  3329. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  3330. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  3331. #endif
  3332. #ifdef USE_CLEARCOAT
  3333. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  3334. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  3335. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  3336. #endif
  3337. #include <opaque_fragment>
  3338. #include <tonemapping_fragment>
  3339. #include <colorspace_fragment>
  3340. #include <fog_fragment>
  3341. #include <premultiplied_alpha_fragment>
  3342. #include <dithering_fragment>
  3343. }`,zve=`#define TOON
  3344. varying vec3 vViewPosition;
  3345. #include <common>
  3346. #include <batching_pars_vertex>
  3347. #include <uv_pars_vertex>
  3348. #include <displacementmap_pars_vertex>
  3349. #include <color_pars_vertex>
  3350. #include <fog_pars_vertex>
  3351. #include <normal_pars_vertex>
  3352. #include <morphtarget_pars_vertex>
  3353. #include <skinning_pars_vertex>
  3354. #include <shadowmap_pars_vertex>
  3355. #include <logdepthbuf_pars_vertex>
  3356. #include <clipping_planes_pars_vertex>
  3357. void main() {
  3358. #include <uv_vertex>
  3359. #include <color_vertex>
  3360. #include <morphinstance_vertex>
  3361. #include <morphcolor_vertex>
  3362. #include <batching_vertex>
  3363. #include <beginnormal_vertex>
  3364. #include <morphnormal_vertex>
  3365. #include <skinbase_vertex>
  3366. #include <skinnormal_vertex>
  3367. #include <defaultnormal_vertex>
  3368. #include <normal_vertex>
  3369. #include <begin_vertex>
  3370. #include <morphtarget_vertex>
  3371. #include <skinning_vertex>
  3372. #include <displacementmap_vertex>
  3373. #include <project_vertex>
  3374. #include <logdepthbuf_vertex>
  3375. #include <clipping_planes_vertex>
  3376. vViewPosition = - mvPosition.xyz;
  3377. #include <worldpos_vertex>
  3378. #include <shadowmap_vertex>
  3379. #include <fog_vertex>
  3380. }`,Uve=`#define TOON
  3381. uniform vec3 diffuse;
  3382. uniform vec3 emissive;
  3383. uniform float opacity;
  3384. #include <common>
  3385. #include <packing>
  3386. #include <dithering_pars_fragment>
  3387. #include <color_pars_fragment>
  3388. #include <uv_pars_fragment>
  3389. #include <map_pars_fragment>
  3390. #include <alphamap_pars_fragment>
  3391. #include <alphatest_pars_fragment>
  3392. #include <alphahash_pars_fragment>
  3393. #include <aomap_pars_fragment>
  3394. #include <lightmap_pars_fragment>
  3395. #include <emissivemap_pars_fragment>
  3396. #include <gradientmap_pars_fragment>
  3397. #include <fog_pars_fragment>
  3398. #include <bsdfs>
  3399. #include <lights_pars_begin>
  3400. #include <normal_pars_fragment>
  3401. #include <lights_toon_pars_fragment>
  3402. #include <shadowmap_pars_fragment>
  3403. #include <bumpmap_pars_fragment>
  3404. #include <normalmap_pars_fragment>
  3405. #include <logdepthbuf_pars_fragment>
  3406. #include <clipping_planes_pars_fragment>
  3407. void main() {
  3408. vec4 diffuseColor = vec4( diffuse, opacity );
  3409. #include <clipping_planes_fragment>
  3410. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  3411. vec3 totalEmissiveRadiance = emissive;
  3412. #include <logdepthbuf_fragment>
  3413. #include <map_fragment>
  3414. #include <color_fragment>
  3415. #include <alphamap_fragment>
  3416. #include <alphatest_fragment>
  3417. #include <alphahash_fragment>
  3418. #include <normal_fragment_begin>
  3419. #include <normal_fragment_maps>
  3420. #include <emissivemap_fragment>
  3421. #include <lights_toon_fragment>
  3422. #include <lights_fragment_begin>
  3423. #include <lights_fragment_maps>
  3424. #include <lights_fragment_end>
  3425. #include <aomap_fragment>
  3426. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  3427. #include <opaque_fragment>
  3428. #include <tonemapping_fragment>
  3429. #include <colorspace_fragment>
  3430. #include <fog_fragment>
  3431. #include <premultiplied_alpha_fragment>
  3432. #include <dithering_fragment>
  3433. }`,Bve=`uniform float size;
  3434. uniform float scale;
  3435. #include <common>
  3436. #include <color_pars_vertex>
  3437. #include <fog_pars_vertex>
  3438. #include <morphtarget_pars_vertex>
  3439. #include <logdepthbuf_pars_vertex>
  3440. #include <clipping_planes_pars_vertex>
  3441. #ifdef USE_POINTS_UV
  3442. varying vec2 vUv;
  3443. uniform mat3 uvTransform;
  3444. #endif
  3445. void main() {
  3446. #ifdef USE_POINTS_UV
  3447. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  3448. #endif
  3449. #include <color_vertex>
  3450. #include <morphinstance_vertex>
  3451. #include <morphcolor_vertex>
  3452. #include <begin_vertex>
  3453. #include <morphtarget_vertex>
  3454. #include <project_vertex>
  3455. gl_PointSize = size;
  3456. #ifdef USE_SIZEATTENUATION
  3457. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3458. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  3459. #endif
  3460. #include <logdepthbuf_vertex>
  3461. #include <clipping_planes_vertex>
  3462. #include <worldpos_vertex>
  3463. #include <fog_vertex>
  3464. }`,Hve=`uniform vec3 diffuse;
  3465. uniform float opacity;
  3466. #include <common>
  3467. #include <color_pars_fragment>
  3468. #include <map_particle_pars_fragment>
  3469. #include <alphatest_pars_fragment>
  3470. #include <alphahash_pars_fragment>
  3471. #include <fog_pars_fragment>
  3472. #include <logdepthbuf_pars_fragment>
  3473. #include <clipping_planes_pars_fragment>
  3474. void main() {
  3475. vec4 diffuseColor = vec4( diffuse, opacity );
  3476. #include <clipping_planes_fragment>
  3477. vec3 outgoingLight = vec3( 0.0 );
  3478. #include <logdepthbuf_fragment>
  3479. #include <map_particle_fragment>
  3480. #include <color_fragment>
  3481. #include <alphatest_fragment>
  3482. #include <alphahash_fragment>
  3483. outgoingLight = diffuseColor.rgb;
  3484. #include <opaque_fragment>
  3485. #include <tonemapping_fragment>
  3486. #include <colorspace_fragment>
  3487. #include <fog_fragment>
  3488. #include <premultiplied_alpha_fragment>
  3489. }`,$ve=`#include <common>
  3490. #include <batching_pars_vertex>
  3491. #include <fog_pars_vertex>
  3492. #include <morphtarget_pars_vertex>
  3493. #include <skinning_pars_vertex>
  3494. #include <logdepthbuf_pars_vertex>
  3495. #include <shadowmap_pars_vertex>
  3496. void main() {
  3497. #include <batching_vertex>
  3498. #include <beginnormal_vertex>
  3499. #include <morphinstance_vertex>
  3500. #include <morphnormal_vertex>
  3501. #include <skinbase_vertex>
  3502. #include <skinnormal_vertex>
  3503. #include <defaultnormal_vertex>
  3504. #include <begin_vertex>
  3505. #include <morphtarget_vertex>
  3506. #include <skinning_vertex>
  3507. #include <project_vertex>
  3508. #include <logdepthbuf_vertex>
  3509. #include <worldpos_vertex>
  3510. #include <shadowmap_vertex>
  3511. #include <fog_vertex>
  3512. }`,Vve=`uniform vec3 color;
  3513. uniform float opacity;
  3514. #include <common>
  3515. #include <packing>
  3516. #include <fog_pars_fragment>
  3517. #include <bsdfs>
  3518. #include <lights_pars_begin>
  3519. #include <logdepthbuf_pars_fragment>
  3520. #include <shadowmap_pars_fragment>
  3521. #include <shadowmask_pars_fragment>
  3522. void main() {
  3523. #include <logdepthbuf_fragment>
  3524. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  3525. #include <tonemapping_fragment>
  3526. #include <colorspace_fragment>
  3527. #include <fog_fragment>
  3528. }`,qve=`uniform float rotation;
  3529. uniform vec2 center;
  3530. #include <common>
  3531. #include <uv_pars_vertex>
  3532. #include <fog_pars_vertex>
  3533. #include <logdepthbuf_pars_vertex>
  3534. #include <clipping_planes_pars_vertex>
  3535. void main() {
  3536. #include <uv_vertex>
  3537. vec4 mvPosition = modelViewMatrix[ 3 ];
  3538. vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
  3539. #ifndef USE_SIZEATTENUATION
  3540. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  3541. if ( isPerspective ) scale *= - mvPosition.z;
  3542. #endif
  3543. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  3544. vec2 rotatedPosition;
  3545. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  3546. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  3547. mvPosition.xy += rotatedPosition;
  3548. gl_Position = projectionMatrix * mvPosition;
  3549. #include <logdepthbuf_vertex>
  3550. #include <clipping_planes_vertex>
  3551. #include <fog_vertex>
  3552. }`,Gve=`uniform vec3 diffuse;
  3553. uniform float opacity;
  3554. #include <common>
  3555. #include <uv_pars_fragment>
  3556. #include <map_pars_fragment>
  3557. #include <alphamap_pars_fragment>
  3558. #include <alphatest_pars_fragment>
  3559. #include <alphahash_pars_fragment>
  3560. #include <fog_pars_fragment>
  3561. #include <logdepthbuf_pars_fragment>
  3562. #include <clipping_planes_pars_fragment>
  3563. void main() {
  3564. vec4 diffuseColor = vec4( diffuse, opacity );
  3565. #include <clipping_planes_fragment>
  3566. vec3 outgoingLight = vec3( 0.0 );
  3567. #include <logdepthbuf_fragment>
  3568. #include <map_fragment>
  3569. #include <alphamap_fragment>
  3570. #include <alphatest_fragment>
  3571. #include <alphahash_fragment>
  3572. outgoingLight = diffuseColor.rgb;
  3573. #include <opaque_fragment>
  3574. #include <tonemapping_fragment>
  3575. #include <colorspace_fragment>
  3576. #include <fog_fragment>
  3577. }`,Ln={alphahash_fragment:fxe,alphahash_pars_fragment:pxe,alphamap_fragment:gxe,alphamap_pars_fragment:bxe,alphatest_fragment:xxe,alphatest_pars_fragment:yxe,aomap_fragment:vxe,aomap_pars_fragment:wxe,batching_pars_vertex:Sxe,batching_vertex:_xe,begin_vertex:Nxe,beginnormal_vertex:Cxe,bsdfs:kxe,iridescence_fragment:Axe,bumpmap_pars_fragment:Txe,clipping_planes_fragment:Mxe,clipping_planes_pars_fragment:Pxe,clipping_planes_pars_vertex:Exe,clipping_planes_vertex:jxe,color_fragment:Dxe,color_pars_fragment:Rxe,color_pars_vertex:Fxe,color_vertex:Lxe,common:Oxe,cube_uv_reflection_fragment:Ixe,defaultnormal_vertex:zxe,displacementmap_pars_vertex:Uxe,displacementmap_vertex:Bxe,emissivemap_fragment:Hxe,emissivemap_pars_fragment:$xe,colorspace_fragment:Vxe,colorspace_pars_fragment:qxe,envmap_fragment:Gxe,envmap_common_pars_fragment:Wxe,envmap_pars_fragment:Kxe,envmap_pars_vertex:Xxe,envmap_physical_pars_fragment:sye,envmap_vertex:Yxe,fog_vertex:Qxe,fog_pars_vertex:Zxe,fog_fragment:Jxe,fog_pars_fragment:eye,gradientmap_pars_fragment:tye,lightmap_pars_fragment:nye,lights_lambert_fragment:rye,lights_lambert_pars_fragment:aye,lights_pars_begin:iye,lights_toon_fragment:oye,lights_toon_pars_fragment:lye,lights_phong_fragment:cye,lights_phong_pars_fragment:uye,lights_physical_fragment:dye,lights_physical_pars_fragment:hye,lights_fragment_begin:mye,lights_fragment_maps:fye,lights_fragment_end:pye,logdepthbuf_fragment:gye,logdepthbuf_pars_fragment:bye,logdepthbuf_pars_vertex:xye,logdepthbuf_vertex:yye,map_fragment:vye,map_pars_fragment:wye,map_particle_fragment:Sye,map_particle_pars_fragment:_ye,metalnessmap_fragment:Nye,metalnessmap_pars_fragment:Cye,morphinstance_vertex:kye,morphcolor_vertex:Aye,morphnormal_vertex:Tye,morphtarget_pars_vertex:Mye,morphtarget_vertex:Pye,normal_fragment_begin:Eye,normal_fragment_maps:jye,normal_pars_fragment:Dye,normal_pars_vertex:Rye,normal_vertex:Fye,normalmap_pars_fragment:Lye,clearcoat_normal_fragment_begin:Oye,clearcoat_normal_fragment_maps:Iye,clearcoat_pars_fragment:zye,iridescence_pars_fragment:Uye,opaque_fragment:Bye,packing:Hye,premultiplied_alpha_fragment:$ye,project_vertex:Vye,dithering_fragment:qye,dithering_pars_fragment:Gye,roughnessmap_fragment:Wye,roughnessmap_pars_fragment:Kye,shadowmap_pars_fragment:Xye,shadowmap_pars_vertex:Yye,shadowmap_vertex:Qye,shadowmask_pars_fragment:Zye,skinbase_vertex:Jye,skinning_pars_vertex:eve,skinning_vertex:tve,skinnormal_vertex:nve,specularmap_fragment:rve,specularmap_pars_fragment:ave,tonemapping_fragment:ive,tonemapping_pars_fragment:sve,transmission_fragment:ove,transmission_pars_fragment:lve,uv_pars_fragment:cve,uv_pars_vertex:uve,uv_vertex:dve,worldpos_vertex:hve,background_vert:mve,background_frag:fve,backgroundCube_vert:pve,backgroundCube_frag:gve,cube_vert:bve,cube_frag:xve,depth_vert:yve,depth_frag:vve,distanceRGBA_vert:wve,distanceRGBA_frag:Sve,equirect_vert:_ve,equirect_frag:Nve,linedashed_vert:Cve,linedashed_frag:kve,meshbasic_vert:Ave,meshbasic_frag:Tve,meshlambert_vert:Mve,meshlambert_frag:Pve,meshmatcap_vert:Eve,meshmatcap_frag:jve,meshnormal_vert:Dve,meshnormal_frag:Rve,meshphong_vert:Fve,meshphong_frag:Lve,meshphysical_vert:Ove,meshphysical_frag:Ive,meshtoon_vert:zve,meshtoon_frag:Uve,points_vert:Bve,points_frag:Hve,shadow_vert:$ve,shadow_frag:Vve,sprite_vert:qve,sprite_frag:Gve},Bt={common:{diffuse:{value:new $n(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Hn},alphaMap:{value:null},alphaMapTransform:{value:new Hn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Hn}},envmap:{envMap:{value:null},envMapRotation:{value:new Hn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Hn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Hn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Hn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Hn},normalScale:{value:new Un(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Hn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Hn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Hn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Hn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new $n(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new $n(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Hn},alphaTest:{value:0},uvTransform:{value:new Hn}},sprite:{diffuse:{value:new $n(16777215)},opacity:{value:1},center:{value:new Un(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Hn},alphaMap:{value:null},alphaMapTransform:{value:new Hn},alphaTest:{value:0}}},wc={basic:{uniforms:ks([Bt.common,Bt.specularmap,Bt.envmap,Bt.aomap,Bt.lightmap,Bt.fog]),vertexShader:Ln.meshbasic_vert,fragmentShader:Ln.meshbasic_frag},lambert:{uniforms:ks([Bt.common,Bt.specularmap,Bt.envmap,Bt.aomap,Bt.lightmap,Bt.emissivemap,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,Bt.fog,Bt.lights,{emissive:{value:new $n(0)}}]),vertexShader:Ln.meshlambert_vert,fragmentShader:Ln.meshlambert_frag},phong:{uniforms:ks([Bt.common,Bt.specularmap,Bt.envmap,Bt.aomap,Bt.lightmap,Bt.emissivemap,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,Bt.fog,Bt.lights,{emissive:{value:new $n(0)},specular:{value:new $n(1118481)},shininess:{value:30}}]),vertexShader:Ln.meshphong_vert,fragmentShader:Ln.meshphong_frag},standard:{uniforms:ks([Bt.common,Bt.envmap,Bt.aomap,Bt.lightmap,Bt.emissivemap,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,Bt.roughnessmap,Bt.metalnessmap,Bt.fog,Bt.lights,{emissive:{value:new $n(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ln.meshphysical_vert,fragmentShader:Ln.meshphysical_frag},toon:{uniforms:ks([Bt.common,Bt.aomap,Bt.lightmap,Bt.emissivemap,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,Bt.gradientmap,Bt.fog,Bt.lights,{emissive:{value:new $n(0)}}]),vertexShader:Ln.meshtoon_vert,fragmentShader:Ln.meshtoon_frag},matcap:{uniforms:ks([Bt.common,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,Bt.fog,{matcap:{value:null}}]),vertexShader:Ln.meshmatcap_vert,fragmentShader:Ln.meshmatcap_frag},points:{uniforms:ks([Bt.points,Bt.fog]),vertexShader:Ln.points_vert,fragmentShader:Ln.points_frag},dashed:{uniforms:ks([Bt.common,Bt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ln.linedashed_vert,fragmentShader:Ln.linedashed_frag},depth:{uniforms:ks([Bt.common,Bt.displacementmap]),vertexShader:Ln.depth_vert,fragmentShader:Ln.depth_frag},normal:{uniforms:ks([Bt.common,Bt.bumpmap,Bt.normalmap,Bt.displacementmap,{opacity:{value:1}}]),vertexShader:Ln.meshnormal_vert,fragmentShader:Ln.meshnormal_frag},sprite:{uniforms:ks([Bt.sprite,Bt.fog]),vertexShader:Ln.sprite_vert,fragmentShader:Ln.sprite_frag},background:{uniforms:{uvTransform:{value:new Hn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ln.background_vert,fragmentShader:Ln.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Hn}},vertexShader:Ln.backgroundCube_vert,fragmentShader:Ln.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ln.cube_vert,fragmentShader:Ln.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ln.equirect_vert,fragmentShader:Ln.equirect_frag},distanceRGBA:{uniforms:ks([Bt.common,Bt.displacementmap,{referencePosition:{value:new ft},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ln.distanceRGBA_vert,fragmentShader:Ln.distanceRGBA_frag},shadow:{uniforms:ks([Bt.lights,Bt.fog,{color:{value:new $n(0)},opacity:{value:1}}]),vertexShader:Ln.shadow_vert,fragmentShader:Ln.shadow_frag}};wc.physical={uniforms:ks([wc.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Hn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Hn},clearcoatNormalScale:{value:new Un(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Hn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Hn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Hn},sheen:{value:0},sheenColor:{value:new $n(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Hn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Hn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Hn},transmissionSamplerSize:{value:new Un},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Hn},attenuationDistance:{value:0},attenuationColor:{value:new $n(0)},specularColor:{value:new $n(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Hn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Hn},anisotropyVector:{value:new Un},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Hn}}]),vertexShader:Ln.meshphysical_vert,fragmentShader:Ln.meshphysical_frag};const CS={r:0,b:0,g:0},Pm=new Gh,Wve=new ri;function Kve(t,e,n,r,a,s,o){const l=new $n(0);let c=s===!0?0:1,u,d,h=null,f=0,p=null;function x(N){let k=N.isScene===!0?N.background:null;return k&&k.isTexture&&(k=(N.backgroundBlurriness>0?n:e).get(k)),k}function v(N){let k=!1;const A=x(N);A===null?y(l,c):A&&A.isColor&&(y(A,1),k=!0);const M=t.xr.getEnvironmentBlendMode();M==="additive"?r.buffers.color.setClear(0,0,0,1,o):M==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||k)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))}function g(N,k){const A=x(k);A&&(A.isCubeTexture||A.mapping===nk)?(d===void 0&&(d=new Sl(new GF(1,1,1),new ad({name:"BackgroundCubeMaterial",uniforms:xb(wc.backgroundCube.uniforms),vertexShader:wc.backgroundCube.vertexShader,fragmentShader:wc.backgroundCube.fragmentShader,side:to,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(M,C,j){this.matrixWorld.copyPosition(j.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),a.update(d)),Pm.copy(k.backgroundRotation),Pm.x*=-1,Pm.y*=-1,Pm.z*=-1,A.isCubeTexture&&A.isRenderTargetTexture===!1&&(Pm.y*=-1,Pm.z*=-1),d.material.uniforms.envMap.value=A,d.material.uniforms.flipEnvMap.value=A.isCubeTexture&&A.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=k.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=k.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(Wve.makeRotationFromEuler(Pm)),d.material.toneMapped=cr.getTransfer(A.colorSpace)!==Dr,(h!==A||f!==A.version||p!==t.toneMapping)&&(d.material.needsUpdate=!0,h=A,f=A.version,p=t.toneMapping),d.layers.enableAll(),N.unshift(d,d.geometry,d.material,0,0,null)):A&&A.isTexture&&(u===void 0&&(u=new Sl(new KF(2,2),new ad({name:"BackgroundMaterial",uniforms:xb(wc.background.uniforms),vertexShader:wc.background.vertexShader,fragmentShader:wc.background.fragmentShader,side:qh,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),a.update(u)),u.material.uniforms.t2D.value=A,u.material.uniforms.backgroundIntensity.value=k.backgroundIntensity,u.material.toneMapped=cr.getTransfer(A.colorSpace)!==Dr,A.matrixAutoUpdate===!0&&A.updateMatrix(),u.material.uniforms.uvTransform.value.copy(A.matrix),(h!==A||f!==A.version||p!==t.toneMapping)&&(u.material.needsUpdate=!0,h=A,f=A.version,p=t.toneMapping),u.layers.enableAll(),N.unshift(u,u.geometry,u.material,0,0,null))}function y(N,k){N.getRGB(CS,nY(t)),r.buffers.color.setClear(CS.r,CS.g,CS.b,k,o)}function _(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0)}return{getClearColor:function(){return l},setClearColor:function(N,k=1){l.set(N),c=k,y(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(N){c=N,y(l,c)},render:v,addToRenderList:g,dispose:_}}function Xve(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),r={},a=f(null);let s=a,o=!1;function l(E,U,L,B,D){let $=!1;const G=h(B,L,U);s!==G&&(s=G,u(s.object)),$=p(E,B,L,D),$&&x(E,B,L,D),D!==null&&e.update(D,t.ELEMENT_ARRAY_BUFFER),($||o)&&(o=!1,k(E,U,L,B),D!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,e.get(D).buffer))}function c(){return t.createVertexArray()}function u(E){return t.bindVertexArray(E)}function d(E){return t.deleteVertexArray(E)}function h(E,U,L){const B=L.wireframe===!0;let D=r[E.id];D===void 0&&(D={},r[E.id]=D);let $=D[U.id];$===void 0&&($={},D[U.id]=$);let G=$[B];return G===void 0&&(G=f(c()),$[B]=G),G}function f(E){const U=[],L=[],B=[];for(let D=0;D<n;D++)U[D]=0,L[D]=0,B[D]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:U,enabledAttributes:L,attributeDivisors:B,object:E,attributes:{},index:null}}function p(E,U,L,B){const D=s.attributes,$=U.attributes;let G=0;const z=L.getAttributes();for(const W in z)if(z[W].location>=0){const ae=D[W];let H=$[W];if(H===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(H=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(H=E.instanceColor)),ae===void 0||ae.attribute!==H||H&&ae.data!==H.data)return!0;G++}return s.attributesNum!==G||s.index!==B}function x(E,U,L,B){const D={},$=U.attributes;let G=0;const z=L.getAttributes();for(const W in z)if(z[W].location>=0){let ae=$[W];ae===void 0&&(W==="instanceMatrix"&&E.instanceMatrix&&(ae=E.instanceMatrix),W==="instanceColor"&&E.instanceColor&&(ae=E.instanceColor));const H={};H.attribute=ae,ae&&ae.data&&(H.data=ae.data),D[W]=H,G++}s.attributes=D,s.attributesNum=G,s.index=B}function v(){const E=s.newAttributes;for(let U=0,L=E.length;U<L;U++)E[U]=0}function g(E){y(E,0)}function y(E,U){const L=s.newAttributes,B=s.enabledAttributes,D=s.attributeDivisors;L[E]=1,B[E]===0&&(t.enableVertexAttribArray(E),B[E]=1),D[E]!==U&&(t.vertexAttribDivisor(E,U),D[E]=U)}function _(){const E=s.newAttributes,U=s.enabledAttributes;for(let L=0,B=U.length;L<B;L++)U[L]!==E[L]&&(t.disableVertexAttribArray(L),U[L]=0)}function N(E,U,L,B,D,$,G){G===!0?t.vertexAttribIPointer(E,U,L,D,$):t.vertexAttribPointer(E,U,L,B,D,$)}function k(E,U,L,B){v();const D=B.attributes,$=L.getAttributes(),G=U.defaultAttributeValues;for(const z in $){const W=$[z];if(W.location>=0){let X=D[z];if(X===void 0&&(z==="instanceMatrix"&&E.instanceMatrix&&(X=E.instanceMatrix),z==="instanceColor"&&E.instanceColor&&(X=E.instanceColor)),X!==void 0){const ae=X.normalized,H=X.itemSize,K=e.get(X);if(K===void 0)continue;const te=K.buffer,Z=K.type,ve=K.bytesPerElement,ce=Z===t.INT||Z===t.UNSIGNED_INT||X.gpuType===LF;if(X.isInterleavedBufferAttribute){const ee=X.data,je=ee.stride,he=X.offset;if(ee.isInstancedInterleavedBuffer){for(let oe=0;oe<W.locationSize;oe++)y(W.location+oe,ee.meshPerAttribute);E.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ee.meshPerAttribute*ee.count)}else for(let oe=0;oe<W.locationSize;oe++)g(W.location+oe);t.bindBuffer(t.ARRAY_BUFFER,te);for(let oe=0;oe<W.locationSize;oe++)N(W.location+oe,H/W.locationSize,Z,ae,je*ve,(he+H/W.locationSize*oe)*ve,ce)}else{if(X.isInstancedBufferAttribute){for(let ee=0;ee<W.locationSize;ee++)y(W.location+ee,X.meshPerAttribute);E.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=X.meshPerAttribute*X.count)}else for(let ee=0;ee<W.locationSize;ee++)g(W.location+ee);t.bindBuffer(t.ARRAY_BUFFER,te);for(let ee=0;ee<W.locationSize;ee++)N(W.location+ee,H/W.locationSize,Z,ae,H*ve,H/W.locationSize*ee*ve,ce)}}else if(G!==void 0){const ae=G[z];if(ae!==void 0)switch(ae.length){case 2:t.vertexAttrib2fv(W.location,ae);break;case 3:t.vertexAttrib3fv(W.location,ae);break;case 4:t.vertexAttrib4fv(W.location,ae);break;default:t.vertexAttrib1fv(W.location,ae)}}}}_()}function A(){j();for(const E in r){const U=r[E];for(const L in U){const B=U[L];for(const D in B)d(B[D].object),delete B[D];delete U[L]}delete r[E]}}function M(E){if(r[E.id]===void 0)return;const U=r[E.id];for(const L in U){const B=U[L];for(const D in B)d(B[D].object),delete B[D];delete U[L]}delete r[E.id]}function C(E){for(const U in r){const L=r[U];if(L[E.id]===void 0)continue;const B=L[E.id];for(const D in B)d(B[D].object),delete B[D];delete L[E.id]}}function j(){P(),o=!0,s!==a&&(s=a,u(s.object))}function P(){a.geometry=null,a.program=null,a.wireframe=!1}return{setup:l,reset:j,resetDefaultState:P,dispose:A,releaseStatesOfGeometry:M,releaseStatesOfProgram:C,initAttributes:v,enableAttribute:g,disableUnusedAttributes:_}}function Yve(t,e,n){let r;function a(u){r=u}function s(u,d){t.drawArrays(r,u,d),n.update(d,r,1)}function o(u,d,h){h!==0&&(t.drawArraysInstanced(r,u,d,h),n.update(d,r,h))}function l(u,d,h){if(h===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r,u,0,d,0,h);let p=0;for(let x=0;x<h;x++)p+=d[x];n.update(p,r,1)}function c(u,d,h,f){if(h===0)return;const p=e.get("WEBGL_multi_draw");if(p===null)for(let x=0;x<u.length;x++)o(u[x],d[x],f[x]);else{p.multiDrawArraysInstancedWEBGL(r,u,0,d,0,f,0,h);let x=0;for(let v=0;v<h;v++)x+=d[v]*f[v];n.update(x,r,1)}}this.setMode=a,this.render=s,this.renderInstances=o,this.renderMultiDraw=l,this.renderMultiDrawInstances=c}function Qve(t,e,n,r){let a;function s(){if(a!==void 0)return a;if(e.has("EXT_texture_filter_anisotropic")===!0){const C=e.get("EXT_texture_filter_anisotropic");a=t.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else a=0;return a}function o(C){return!(C!==ql&&r.convert(C)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT))}function l(C){const j=C===Gb&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(C!==Lc&&r.convert(C)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&C!==Iu&&!j)}function c(C){if(C==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let u=n.precision!==void 0?n.precision:"highp";const d=c(u);d!==u&&(vn("WebGLRenderer:",u,"not supported, using",d,"instead."),u=d);const h=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),p=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),x=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=t.getParameter(t.MAX_TEXTURE_SIZE),g=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),y=t.getParameter(t.MAX_VERTEX_ATTRIBS),_=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),N=t.getParameter(t.MAX_VARYING_VECTORS),k=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),A=x>0,M=t.getParameter(t.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:l,precision:u,logarithmicDepthBuffer:h,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:x,maxTextureSize:v,maxCubemapSize:g,maxAttributes:y,maxVertexUniforms:_,maxVaryings:N,maxFragmentUniforms:k,vertexTextures:A,maxSamples:M}}function Zve(t){const e=this;let n=null,r=0,a=!1,s=!1;const o=new ih,l=new Hn,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,f){const p=h.length!==0||f||r!==0||a;return a=f,r=h.length,p},this.beginShadows=function(){s=!0,d(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,f){n=d(h,f,0)},this.setState=function(h,f,p){const x=h.clippingPlanes,v=h.clipIntersection,g=h.clipShadows,y=t.get(h);if(!a||x===null||x.length===0||s&&!g)s?d(null):u();else{const _=s?0:r,N=_*4;let k=y.clippingState||null;c.value=k,k=d(x,f,N,p);for(let A=0;A!==N;++A)k[A]=n[A];y.clippingState=k,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function u(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function d(h,f,p,x){const v=h!==null?h.length:0;let g=null;if(v!==0){if(g=c.value,x!==!0||g===null){const y=p+v*4,_=f.matrixWorldInverse;l.getNormalMatrix(_),(g===null||g.length<y)&&(g=new Float32Array(y));for(let N=0,k=p;N!==v;++N,k+=4)o.copy(h[N]).applyMatrix4(_,l),o.normal.toArray(g,k),g[k+3]=o.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,g}}function Jve(t){let e=new WeakMap;function n(o,l){return l===w3?o.mapping=pb:l===S3&&(o.mapping=gb),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===w3||l===S3)if(e.has(o)){const c=e.get(o).texture;return n(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const u=new qbe(c.height);return u.fromEquirectangularTexture(t,o),e.set(o,u),o.addEventListener("dispose",a),n(u.texture,o.mapping)}else return null}}return o}function a(o){const l=o.target;l.removeEventListener("dispose",a);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}const vh=4,C8=[.125,.215,.35,.446,.526,.582],Wm=20,e0e=256,oy=new dY,k8=new $n;let fP=null,pP=0,gP=0,bP=!1;const t0e=new ft;let A8=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,n=0,r=.1,a=100,s={}){const{size:o=256,position:l=t0e}=s;fP=this._renderer.getRenderTarget(),pP=this._renderer.getActiveCubeFace(),gP=this._renderer.getActiveMipmapLevel(),bP=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,r,a,c,l),n>0&&this._blur(c,0,0,n),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=P8(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=M8(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(fP,pP,gP),this._renderer.xr.enabled=bP,e.scissorTest=!1,tg(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===pb||e.mapping===gb?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),fP=this._renderer.getRenderTarget(),pP=this._renderer.getActiveCubeFace(),gP=this._renderer.getActiveMipmapLevel(),bP=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const r=n||this._allocateTargets();return this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,r={magFilter:hl,minFilter:hl,generateMipmaps:!1,type:Gb,format:ql,colorSpace:bb,depthBuffer:!1},a=T8(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=T8(e,n,r);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=n0e(s)),this._blurMaterial=a0e(s,e,n),this._ggxMaterial=r0e(s,e,n)}return a}_compileMaterial(e){const n=new Sl(new wl,e);this._renderer.compile(n,oy)}_sceneToCubeUV(e,n,r,a,s){const c=new sl(90,1,n,r),u=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],h=this._renderer,f=h.autoClear,p=h.toneMapping;h.getClearColor(k8),h.toneMapping=Dh,h.autoClear=!1,h.state.buffers.depth.getReversed()&&(h.setRenderTarget(a),h.clearDepth(),h.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Sl(new GF,new qF({name:"PMREM.Background",side:to,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,g=v.material;let y=!1;const _=e.background;_?_.isColor&&(g.color.copy(_),e.background=null,y=!0):(g.color.copy(k8),y=!0);for(let N=0;N<6;N++){const k=N%3;k===0?(c.up.set(0,u[N],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+d[N],s.y,s.z)):k===1?(c.up.set(0,0,u[N]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+d[N],s.z)):(c.up.set(0,u[N],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+d[N]));const A=this._cubeSize;tg(a,k*A,N>2?A:0,A,A),h.setRenderTarget(a),y&&h.render(v,c),h.render(e,c)}h.toneMapping=p,h.autoClear=f,e.background=_}_textureToCubeUV(e,n){const r=this._renderer,a=e.mapping===pb||e.mapping===gb;a?(this._cubemapMaterial===null&&(this._cubemapMaterial=P8()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=M8());const s=a?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=s;const l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;tg(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,oy)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;const a=this._lodMeshes.length;for(let s=1;s<a;s++)this._applyGGXFilter(e,s-1,s);n.autoClear=r}_applyGGXFilter(e,n,r){const a=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,l=this._lodMeshes[r];l.material=o;const c=o.uniforms,u=r/(this._lodMeshes.length-1),d=n/(this._lodMeshes.length-1),h=Math.sqrt(u*u-d*d),f=.05+u*.95,p=h*f,{_lodMax:x}=this,v=this._sizeLods[r],g=3*v*(r>x-vh?r-x+vh:0),y=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=p,c.mipInt.value=x-n,tg(s,g,y,3*v,2*v),a.setRenderTarget(s),a.render(l,oy),c.envMap.value=s.texture,c.roughness.value=0,c.mipInt.value=x-r,tg(e,g,y,3*v,2*v),a.setRenderTarget(e),a.render(l,oy)}_blur(e,n,r,a,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,a,"latitudinal",s),this._halfBlur(o,e,r,r,a,"longitudinal",s)}_halfBlur(e,n,r,a,s,o,l){const c=this._renderer,u=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&Ua("blur direction must be either latitudinal or longitudinal!");const d=3,h=this._lodMeshes[a];h.material=u;const f=u.uniforms,p=this._sizeLods[r]-1,x=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Wm-1),v=s/x,g=isFinite(s)?1+Math.floor(d*v):Wm;g>Wm&&vn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Wm}`);const y=[];let _=0;for(let C=0;C<Wm;++C){const j=C/v,P=Math.exp(-j*j/2);y.push(P),C===0?_+=P:C<g&&(_+=2*P)}for(let C=0;C<y.length;C++)y[C]=y[C]/_;f.envMap.value=e.texture,f.samples.value=g,f.weights.value=y,f.latitudinal.value=o==="latitudinal",l&&(f.poleAxis.value=l);const{_lodMax:N}=this;f.dTheta.value=x,f.mipInt.value=N-r;const k=this._sizeLods[a],A=3*k*(a>N-vh?a-N+vh:0),M=4*(this._cubeSize-k);tg(n,A,M,3*k,2*k),c.setRenderTarget(n),c.render(h,oy)}};function n0e(t){const e=[],n=[],r=[];let a=t;const s=t-vh+1+C8.length;for(let o=0;o<s;o++){const l=Math.pow(2,a);e.push(l);let c=1/l;o>t-vh?c=C8[o-t+vh-1]:o===0&&(c=0),n.push(c);const u=1/(l-2),d=-u,h=1+u,f=[d,d,h,d,h,h,d,d,h,h,d,h],p=6,x=6,v=3,g=2,y=1,_=new Float32Array(v*x*p),N=new Float32Array(g*x*p),k=new Float32Array(y*x*p);for(let M=0;M<p;M++){const C=M%3*2/3-1,j=M>2?0:-1,P=[C,j,0,C+2/3,j,0,C+2/3,j+1,0,C,j,0,C+2/3,j+1,0,C,j+1,0];_.set(P,v*x*M),N.set(f,g*x*M);const E=[M,M,M,M,M,M];k.set(E,y*x*M)}const A=new wl;A.setAttribute("position",new Ds(_,v)),A.setAttribute("uv",new Ds(N,g)),A.setAttribute("faceIndex",new Ds(k,y)),r.push(new Sl(A,null)),a>vh&&a--}return{lodMeshes:r,sizeLods:e,sigmas:n}}function T8(t,e,n){const r=new Of(t,e,n);return r.texture.mapping=nk,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function tg(t,e,n,r,a){t.viewport.set(e,n,r,a),t.scissor.set(e,n,r,a)}function r0e(t,e,n){return new ad({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:e0e,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:ak(),fragmentShader:`
  3578. precision highp float;
  3579. precision highp int;
  3580. varying vec3 vOutputDirection;
  3581. uniform sampler2D envMap;
  3582. uniform float roughness;
  3583. uniform float mipInt;
  3584. #define ENVMAP_TYPE_CUBE_UV
  3585. #include <cube_uv_reflection_fragment>
  3586. #define PI 3.14159265359
  3587. // Van der Corput radical inverse
  3588. float radicalInverse_VdC(uint bits) {
  3589. bits = (bits << 16u) | (bits >> 16u);
  3590. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  3591. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  3592. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  3593. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  3594. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  3595. }
  3596. // Hammersley sequence
  3597. vec2 hammersley(uint i, uint N) {
  3598. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  3599. }
  3600. // GGX VNDF importance sampling (Eric Heitz 2018)
  3601. // "Sampling the GGX Distribution of Visible Normals"
  3602. // https://jcgt.org/published/0007/04/01/
  3603. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  3604. float alpha = roughness * roughness;
  3605. // Section 3.2: Transform view direction to hemisphere configuration
  3606. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  3607. // Section 4.1: Orthonormal basis
  3608. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  3609. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  3610. vec3 T2 = cross(Vh, T1);
  3611. // Section 4.2: Parameterization of projected area
  3612. float r = sqrt(Xi.x);
  3613. float phi = 2.0 * PI * Xi.y;
  3614. float t1 = r * cos(phi);
  3615. float t2 = r * sin(phi);
  3616. float s = 0.5 * (1.0 + Vh.z);
  3617. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  3618. // Section 4.3: Reprojection onto hemisphere
  3619. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  3620. // Section 3.4: Transform back to ellipsoid configuration
  3621. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  3622. }
  3623. void main() {
  3624. vec3 N = normalize(vOutputDirection);
  3625. vec3 V = N; // Assume view direction equals normal for pre-filtering
  3626. vec3 prefilteredColor = vec3(0.0);
  3627. float totalWeight = 0.0;
  3628. // For very low roughness, just sample the environment directly
  3629. if (roughness < 0.001) {
  3630. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  3631. return;
  3632. }
  3633. // Tangent space basis for VNDF sampling
  3634. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  3635. vec3 tangent = normalize(cross(up, N));
  3636. vec3 bitangent = cross(N, tangent);
  3637. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  3638. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  3639. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  3640. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  3641. // Transform H back to world space
  3642. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  3643. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  3644. float NdotL = max(dot(N, L), 0.0);
  3645. if(NdotL > 0.0) {
  3646. // Sample environment at fixed mip level
  3647. // VNDF importance sampling handles the distribution filtering
  3648. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  3649. // Weight by NdotL for the split-sum approximation
  3650. // VNDF PDF naturally accounts for the visible microfacet distribution
  3651. prefilteredColor += sampleColor * NdotL;
  3652. totalWeight += NdotL;
  3653. }
  3654. }
  3655. if (totalWeight > 0.0) {
  3656. prefilteredColor = prefilteredColor / totalWeight;
  3657. }
  3658. gl_FragColor = vec4(prefilteredColor, 1.0);
  3659. }
  3660. `,blending:Vu,depthTest:!1,depthWrite:!1})}function a0e(t,e,n){const r=new Float32Array(Wm),a=new ft(0,1,0);return new ad({name:"SphericalGaussianBlur",defines:{n:Wm,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:ak(),fragmentShader:`
  3661. precision mediump float;
  3662. precision mediump int;
  3663. varying vec3 vOutputDirection;
  3664. uniform sampler2D envMap;
  3665. uniform int samples;
  3666. uniform float weights[ n ];
  3667. uniform bool latitudinal;
  3668. uniform float dTheta;
  3669. uniform float mipInt;
  3670. uniform vec3 poleAxis;
  3671. #define ENVMAP_TYPE_CUBE_UV
  3672. #include <cube_uv_reflection_fragment>
  3673. vec3 getSample( float theta, vec3 axis ) {
  3674. float cosTheta = cos( theta );
  3675. // Rodrigues' axis-angle rotation
  3676. vec3 sampleDirection = vOutputDirection * cosTheta
  3677. + cross( axis, vOutputDirection ) * sin( theta )
  3678. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  3679. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  3680. }
  3681. void main() {
  3682. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  3683. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  3684. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  3685. }
  3686. axis = normalize( axis );
  3687. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  3688. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  3689. for ( int i = 1; i < n; i++ ) {
  3690. if ( i >= samples ) {
  3691. break;
  3692. }
  3693. float theta = dTheta * float( i );
  3694. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  3695. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  3696. }
  3697. }
  3698. `,blending:Vu,depthTest:!1,depthWrite:!1})}function M8(){return new ad({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ak(),fragmentShader:`
  3699. precision mediump float;
  3700. precision mediump int;
  3701. varying vec3 vOutputDirection;
  3702. uniform sampler2D envMap;
  3703. #include <common>
  3704. void main() {
  3705. vec3 outputDirection = normalize( vOutputDirection );
  3706. vec2 uv = equirectUv( outputDirection );
  3707. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  3708. }
  3709. `,blending:Vu,depthTest:!1,depthWrite:!1})}function P8(){return new ad({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ak(),fragmentShader:`
  3710. precision mediump float;
  3711. precision mediump int;
  3712. uniform float flipEnvMap;
  3713. varying vec3 vOutputDirection;
  3714. uniform samplerCube envMap;
  3715. void main() {
  3716. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  3717. }
  3718. `,blending:Vu,depthTest:!1,depthWrite:!1})}function ak(){return`
  3719. precision mediump float;
  3720. precision mediump int;
  3721. attribute float faceIndex;
  3722. varying vec3 vOutputDirection;
  3723. // RH coordinate system; PMREM face-indexing convention
  3724. vec3 getDirection( vec2 uv, float face ) {
  3725. uv = 2.0 * uv - 1.0;
  3726. vec3 direction = vec3( uv, 1.0 );
  3727. if ( face == 0.0 ) {
  3728. direction = direction.zyx; // ( 1, v, u ) pos x
  3729. } else if ( face == 1.0 ) {
  3730. direction = direction.xzy;
  3731. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  3732. } else if ( face == 2.0 ) {
  3733. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  3734. } else if ( face == 3.0 ) {
  3735. direction = direction.zyx;
  3736. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  3737. } else if ( face == 4.0 ) {
  3738. direction = direction.xzy;
  3739. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  3740. } else if ( face == 5.0 ) {
  3741. direction.z *= -1.0; // ( u, v, -1 ) neg z
  3742. }
  3743. return direction;
  3744. }
  3745. void main() {
  3746. vOutputDirection = getDirection( uv, faceIndex );
  3747. gl_Position = vec4( position, 1.0 );
  3748. }
  3749. `}function i0e(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,u=c===w3||c===S3,d=c===pb||c===gb;if(u||d){let h=e.get(l);const f=h!==void 0?h.texture.pmremVersion:0;if(l.isRenderTargetTexture&&l.pmremVersion!==f)return n===null&&(n=new A8(t)),h=u?n.fromEquirectangular(l,h):n.fromCubemap(l,h),h.texture.pmremVersion=l.pmremVersion,e.set(l,h),h.texture;if(h!==void 0)return h.texture;{const p=l.image;return u&&p&&p.height>0||d&&p&&a(p)?(n===null&&(n=new A8(t)),h=u?n.fromEquirectangular(l):n.fromCubemap(l),h.texture.pmremVersion=l.pmremVersion,e.set(l,h),l.addEventListener("dispose",s),h.texture):null}}}return l}function a(l){let c=0;const u=6;for(let d=0;d<u;d++)l[d]!==void 0&&c++;return c===u}function s(l){const c=l.target;c.removeEventListener("dispose",s);const u=e.get(c);u!==void 0&&(e.delete(c),u.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function s0e(t){const e={};function n(r){if(e[r]!==void 0)return e[r];const a=t.getExtension(r);return e[r]=a,a}return{has:function(r){return n(r)!==null},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(r){const a=n(r);return a===null&&Nv("WebGLRenderer: "+r+" extension not supported."),a}}}function o0e(t,e,n,r){const a={},s=new WeakMap;function o(h){const f=h.target;f.index!==null&&e.remove(f.index);for(const x in f.attributes)e.remove(f.attributes[x]);f.removeEventListener("dispose",o),delete a[f.id];const p=s.get(f);p&&(e.remove(p),s.delete(f)),r.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0&&delete f._maxInstanceCount,n.memory.geometries--}function l(h,f){return a[f.id]===!0||(f.addEventListener("dispose",o),a[f.id]=!0,n.memory.geometries++),f}function c(h){const f=h.attributes;for(const p in f)e.update(f[p],t.ARRAY_BUFFER)}function u(h){const f=[],p=h.index,x=h.attributes.position;let v=0;if(p!==null){const _=p.array;v=p.version;for(let N=0,k=_.length;N<k;N+=3){const A=_[N+0],M=_[N+1],C=_[N+2];f.push(A,M,M,C,C,A)}}else if(x!==void 0){const _=x.array;v=x.version;for(let N=0,k=_.length/3-1;N<k;N+=3){const A=N+0,M=N+1,C=N+2;f.push(A,M,M,C,C,A)}}else return;const g=new($X(f)?JX:ZX)(f,1);g.version=v;const y=s.get(h);y&&e.remove(y),s.set(h,g)}function d(h){const f=s.get(h);if(f){const p=h.index;p!==null&&f.version<p.version&&u(h)}else u(h);return s.get(h)}return{get:l,update:c,getWireframeAttribute:d}}function l0e(t,e,n){let r;function a(f){r=f}let s,o;function l(f){s=f.type,o=f.bytesPerElement}function c(f,p){t.drawElements(r,p,s,f*o),n.update(p,r,1)}function u(f,p,x){x!==0&&(t.drawElementsInstanced(r,p,s,f*o,x),n.update(p,r,x))}function d(f,p,x){if(x===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r,p,0,s,f,0,x);let g=0;for(let y=0;y<x;y++)g+=p[y];n.update(g,r,1)}function h(f,p,x,v){if(x===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let y=0;y<f.length;y++)u(f[y]/o,p[y],v[y]);else{g.multiDrawElementsInstancedWEBGL(r,p,0,s,f,0,v,0,x);let y=0;for(let _=0;_<x;_++)y+=p[_]*v[_];n.update(y,r,1)}}this.setMode=a,this.setIndex=l,this.render=c,this.renderInstances=u,this.renderMultiDraw=d,this.renderMultiDrawInstances=h}function c0e(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(s,o,l){switch(n.calls++,o){case t.TRIANGLES:n.triangles+=l*(s/3);break;case t.LINES:n.lines+=l*(s/2);break;case t.LINE_STRIP:n.lines+=l*(s-1);break;case t.LINE_LOOP:n.lines+=l*s;break;case t.POINTS:n.points+=l*s;break;default:Ua("WebGLInfo: Unknown draw mode:",o);break}}function a(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:a,update:r}}function u0e(t,e,n){const r=new WeakMap,a=new Za;function s(o,l,c){const u=o.morphTargetInfluences,d=l.morphAttributes.position||l.morphAttributes.normal||l.morphAttributes.color,h=d!==void 0?d.length:0;let f=r.get(l);if(f===void 0||f.count!==h){let E=function(){j.dispose(),r.delete(l),l.removeEventListener("dispose",E)};var p=E;f!==void 0&&f.texture.dispose();const x=l.morphAttributes.position!==void 0,v=l.morphAttributes.normal!==void 0,g=l.morphAttributes.color!==void 0,y=l.morphAttributes.position||[],_=l.morphAttributes.normal||[],N=l.morphAttributes.color||[];let k=0;x===!0&&(k=1),v===!0&&(k=2),g===!0&&(k=3);let A=l.attributes.position.count*k,M=1;A>e.maxTextureSize&&(M=Math.ceil(A/e.maxTextureSize),A=e.maxTextureSize);const C=new Float32Array(A*M*4*h),j=new KX(C,A,M,h);j.type=Iu,j.needsUpdate=!0;const P=k*4;for(let U=0;U<h;U++){const L=y[U],B=_[U],D=N[U],$=A*M*4*U;for(let G=0;G<L.count;G++){const z=G*P;x===!0&&(a.fromBufferAttribute(L,G),C[$+z+0]=a.x,C[$+z+1]=a.y,C[$+z+2]=a.z,C[$+z+3]=0),v===!0&&(a.fromBufferAttribute(B,G),C[$+z+4]=a.x,C[$+z+5]=a.y,C[$+z+6]=a.z,C[$+z+7]=0),g===!0&&(a.fromBufferAttribute(D,G),C[$+z+8]=a.x,C[$+z+9]=a.y,C[$+z+10]=a.z,C[$+z+11]=D.itemSize===4?a.w:1)}}f={count:h,texture:j,size:new Un(A,M)},r.set(l,f),l.addEventListener("dispose",E)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(t,"morphTexture",o.morphTexture,n);else{let x=0;for(let g=0;g<u.length;g++)x+=u[g];const v=l.morphTargetsRelative?1:1-x;c.getUniforms().setValue(t,"morphTargetBaseInfluence",v),c.getUniforms().setValue(t,"morphTargetInfluences",u)}c.getUniforms().setValue(t,"morphTargetsTexture",f.texture,n),c.getUniforms().setValue(t,"morphTargetsTextureSize",f.size)}return{update:s}}function d0e(t,e,n,r){let a=new WeakMap;function s(c){const u=r.render.frame,d=c.geometry,h=e.get(c,d);if(a.get(h)!==u&&(e.update(h),a.set(h,u)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),a.get(c)!==u&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),a.set(c,u))),c.isSkinnedMesh){const f=c.skeleton;a.get(f)!==u&&(f.update(),a.set(f,u))}return h}function o(){a=new WeakMap}function l(c){const u=c.target;u.removeEventListener("dispose",l),n.remove(u.instanceMatrix),u.instanceColor!==null&&n.remove(u.instanceColor)}return{update:s,dispose:o}}const mY=new ac,E8=new sY(1,1),fY=new KX,pY=new Tbe,gY=new aY,j8=[],D8=[],R8=new Float32Array(16),F8=new Float32Array(9),L8=new Float32Array(4);function Kb(t,e,n){const r=t[0];if(r<=0||r>0)return t;const a=e*n;let s=j8[a];if(s===void 0&&(s=new Float32Array(a),j8[a]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function gi(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n<r;n++)if(t[n]!==e[n])return!1;return!0}function bi(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function ik(t,e){let n=D8[e];n===void 0&&(n=new Int32Array(e),D8[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function h0e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function m0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2f(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(gi(n,e))return;t.uniform2fv(this.addr,e),bi(n,e)}}function f0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3f(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else if(e.r!==void 0)(n[0]!==e.r||n[1]!==e.g||n[2]!==e.b)&&(t.uniform3f(this.addr,e.r,e.g,e.b),n[0]=e.r,n[1]=e.g,n[2]=e.b);else{if(gi(n,e))return;t.uniform3fv(this.addr,e),bi(n,e)}}function p0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(gi(n,e))return;t.uniform4fv(this.addr,e),bi(n,e)}}function g0e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(gi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),bi(n,e)}else{if(gi(n,r))return;L8.set(r),t.uniformMatrix2fv(this.addr,!1,L8),bi(n,r)}}function b0e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(gi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),bi(n,e)}else{if(gi(n,r))return;F8.set(r),t.uniformMatrix3fv(this.addr,!1,F8),bi(n,r)}}function x0e(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(gi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),bi(n,e)}else{if(gi(n,r))return;R8.set(r),t.uniformMatrix4fv(this.addr,!1,R8),bi(n,r)}}function y0e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function v0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2i(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(gi(n,e))return;t.uniform2iv(this.addr,e),bi(n,e)}}function w0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3i(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(gi(n,e))return;t.uniform3iv(this.addr,e),bi(n,e)}}function S0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4i(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(gi(n,e))return;t.uniform4iv(this.addr,e),bi(n,e)}}function _0e(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function N0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2ui(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(gi(n,e))return;t.uniform2uiv(this.addr,e),bi(n,e)}}function C0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3ui(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(gi(n,e))return;t.uniform3uiv(this.addr,e),bi(n,e)}}function k0e(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(gi(n,e))return;t.uniform4uiv(this.addr,e),bi(n,e)}}function A0e(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a);let s;this.type===t.SAMPLER_2D_SHADOW?(E8.compareFunction=HX,s=E8):s=mY,n.setTexture2D(e||s,a)}function T0e(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTexture3D(e||pY,a)}function M0e(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTextureCube(e||gY,a)}function P0e(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTexture2DArray(e||fY,a)}function E0e(t){switch(t){case 5126:return h0e;case 35664:return m0e;case 35665:return f0e;case 35666:return p0e;case 35674:return g0e;case 35675:return b0e;case 35676:return x0e;case 5124:case 35670:return y0e;case 35667:case 35671:return v0e;case 35668:case 35672:return w0e;case 35669:case 35673:return S0e;case 5125:return _0e;case 36294:return N0e;case 36295:return C0e;case 36296:return k0e;case 35678:case 36198:case 36298:case 36306:case 35682:return A0e;case 35679:case 36299:case 36307:return T0e;case 35680:case 36300:case 36308:case 36293:return M0e;case 36289:case 36303:case 36311:case 36292:return P0e}}function j0e(t,e){t.uniform1fv(this.addr,e)}function D0e(t,e){const n=Kb(e,this.size,2);t.uniform2fv(this.addr,n)}function R0e(t,e){const n=Kb(e,this.size,3);t.uniform3fv(this.addr,n)}function F0e(t,e){const n=Kb(e,this.size,4);t.uniform4fv(this.addr,n)}function L0e(t,e){const n=Kb(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function O0e(t,e){const n=Kb(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function I0e(t,e){const n=Kb(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function z0e(t,e){t.uniform1iv(this.addr,e)}function U0e(t,e){t.uniform2iv(this.addr,e)}function B0e(t,e){t.uniform3iv(this.addr,e)}function H0e(t,e){t.uniform4iv(this.addr,e)}function $0e(t,e){t.uniform1uiv(this.addr,e)}function V0e(t,e){t.uniform2uiv(this.addr,e)}function q0e(t,e){t.uniform3uiv(this.addr,e)}function G0e(t,e){t.uniform4uiv(this.addr,e)}function W0e(t,e,n){const r=this.cache,a=e.length,s=ik(n,a);gi(r,s)||(t.uniform1iv(this.addr,s),bi(r,s));for(let o=0;o!==a;++o)n.setTexture2D(e[o]||mY,s[o])}function K0e(t,e,n){const r=this.cache,a=e.length,s=ik(n,a);gi(r,s)||(t.uniform1iv(this.addr,s),bi(r,s));for(let o=0;o!==a;++o)n.setTexture3D(e[o]||pY,s[o])}function X0e(t,e,n){const r=this.cache,a=e.length,s=ik(n,a);gi(r,s)||(t.uniform1iv(this.addr,s),bi(r,s));for(let o=0;o!==a;++o)n.setTextureCube(e[o]||gY,s[o])}function Y0e(t,e,n){const r=this.cache,a=e.length,s=ik(n,a);gi(r,s)||(t.uniform1iv(this.addr,s),bi(r,s));for(let o=0;o!==a;++o)n.setTexture2DArray(e[o]||fY,s[o])}function Q0e(t){switch(t){case 5126:return j0e;case 35664:return D0e;case 35665:return R0e;case 35666:return F0e;case 35674:return L0e;case 35675:return O0e;case 35676:return I0e;case 5124:case 35670:return z0e;case 35667:case 35671:return U0e;case 35668:case 35672:return B0e;case 35669:case 35673:return H0e;case 5125:return $0e;case 36294:return V0e;case 36295:return q0e;case 36296:return G0e;case 35678:case 36198:case 36298:case 36306:case 35682:return W0e;case 35679:case 36299:case 36307:return K0e;case 35680:case 36300:case 36308:case 36293:return X0e;case 36289:case 36303:case 36311:case 36292:return Y0e}}let Z0e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=E0e(n.type)}},J0e=class{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=Q0e(n.type)}},ewe=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const a=this.seq;for(let s=0,o=a.length;s!==o;++s){const l=a[s];l.setValue(e,n[l.id],r)}}};const xP=/(\w+)(\])?(\[|\.)?/g;function O8(t,e){t.seq.push(e),t.map[e.id]=e}function twe(t,e,n){const r=t.name,a=r.length;for(xP.lastIndex=0;;){const s=xP.exec(r),o=xP.lastIndex;let l=s[1];const c=s[2]==="]",u=s[3];if(c&&(l=l|0),u===void 0||u==="["&&o+2===a){O8(n,u===void 0?new Z0e(l,t,e):new J0e(l,t,e));break}else{let h=n.map[l];h===void 0&&(h=new ewe(l),O8(n,h)),n=h}}}let Q_=class{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let a=0;a<r;++a){const s=e.getActiveUniform(n,a),o=e.getUniformLocation(n,s.name);twe(s,o,this)}}setValue(e,n,r,a){const s=this.map[n];s!==void 0&&s.setValue(e,r,a)}setOptional(e,n,r){const a=n[r];a!==void 0&&this.setValue(e,r,a)}static upload(e,n,r,a){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=r[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,a)}}static seqWithValue(e,n){const r=[];for(let a=0,s=e.length;a!==s;++a){const o=e[a];o.id in n&&r.push(o)}return r}};function I8(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const nwe=37297;let rwe=0;function awe(t,e){const n=t.split(`
  3750. `),r=[],a=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=a;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
  3751. `)}const z8=new Hn;function iwe(t){cr._getMatrix(z8,cr.workingColorSpace,t);const e=`mat3( ${z8.elements.map(n=>n.toFixed(4))} )`;switch(cr.getTransfer(t)){case A1:return[e,"LinearTransferOETF"];case Dr:return[e,"sRGBTransferOETF"];default:return vn("WebGLProgram: Unsupported color space: ",t),[e,"LinearTransferOETF"]}}function U8(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),s=(t.getShaderInfoLog(e)||"").trim();if(r&&s==="")return"";const o=/ERROR: 0:(\d+)/.exec(s);if(o){const l=parseInt(o[1]);return n.toUpperCase()+`
  3752. `+s+`
  3753. `+awe(t.getShaderSource(e),l)}else return s}function swe(t,e){const n=iwe(e);return[`vec4 ${t}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join(`
  3754. `)}function owe(t,e){let n;switch(e){case tbe:n="Linear";break;case nbe:n="Reinhard";break;case rbe:n="Cineon";break;case abe:n="ACESFilmic";break;case sbe:n="AgX";break;case obe:n="Neutral";break;case ibe:n="Custom";break;default:vn("WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const kS=new ft;function lwe(){cr.getLuminanceCoefficients(kS);const t=kS.x.toFixed(4),e=kS.y.toFixed(4),n=kS.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${t}, ${e}, ${n} );`," return dot( weights, rgb );","}"].join(`
  3755. `)}function cwe(t){return[t.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",t.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Ay).join(`
  3756. `)}function uwe(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
  3757. `)}function dwe(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let a=0;a<r;a++){const s=t.getActiveAttrib(e,a),o=s.name;let l=1;s.type===t.FLOAT_MAT2&&(l=2),s.type===t.FLOAT_MAT3&&(l=3),s.type===t.FLOAT_MAT4&&(l=4),n[o]={type:s.type,location:t.getAttribLocation(e,o),locationSize:l}}return n}function Ay(t){return t!==""}function B8(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function H8(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const hwe=/^[ \t]*#include +<([\w\d./]+)>/gm;function tD(t){return t.replace(hwe,fwe)}const mwe=new Map;function fwe(t,e){let n=Ln[e];if(n===void 0){const r=mwe.get(e);if(r!==void 0)n=Ln[r],vn('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return tD(n)}const pwe=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function $8(t){return t.replace(pwe,gwe)}function gwe(t,e,n,r){let a="";for(let s=parseInt(e);s<parseInt(n);s++)a+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return a}function V8(t){let e=`precision ${t.precision} float;
  3758. precision ${t.precision} int;
  3759. precision ${t.precision} sampler2D;
  3760. precision ${t.precision} samplerCube;
  3761. precision ${t.precision} sampler3D;
  3762. precision ${t.precision} sampler2DArray;
  3763. precision ${t.precision} sampler2DShadow;
  3764. precision ${t.precision} samplerCubeShadow;
  3765. precision ${t.precision} sampler2DArrayShadow;
  3766. precision ${t.precision} isampler2D;
  3767. precision ${t.precision} isampler3D;
  3768. precision ${t.precision} isamplerCube;
  3769. precision ${t.precision} isampler2DArray;
  3770. precision ${t.precision} usampler2D;
  3771. precision ${t.precision} usampler3D;
  3772. precision ${t.precision} usamplerCube;
  3773. precision ${t.precision} usampler2DArray;
  3774. `;return t.precision==="highp"?e+=`
  3775. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  3776. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  3777. #define LOW_PRECISION`),e}function bwe(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===jX?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===Rge?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===Tu&&(e="SHADOWMAP_TYPE_VSM"),e}function xwe(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case pb:case gb:e="ENVMAP_TYPE_CUBE";break;case nk:e="ENVMAP_TYPE_CUBE_UV";break}return e}function ywe(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===gb&&(e="ENVMAP_MODE_REFRACTION"),e}function vwe(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case FF:e="ENVMAP_BLENDING_MULTIPLY";break;case Jge:e="ENVMAP_BLENDING_MIX";break;case ebe:e="ENVMAP_BLENDING_ADD";break}return e}function wwe(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:r,maxMip:n}}function Swe(t,e,n,r){const a=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=bwe(n),u=xwe(n),d=ywe(n),h=vwe(n),f=wwe(n),p=cwe(n),x=uwe(s),v=a.createProgram();let g,y,_=n.glslVersion?"#version "+n.glslVersion+`
  3778. `:"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Ay).join(`
  3779. `),g.length>0&&(g+=`
  3780. `),y=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Ay).join(`
  3781. `),y.length>0&&(y+=`
  3782. `)):(g=[V8(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",`
  3783. `].filter(Ay).join(`
  3784. `),y=[V8(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+d:"",n.envMap?"#define "+h:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==Dh?"#define TONE_MAPPING":"",n.toneMapping!==Dh?Ln.tonemapping_pars_fragment:"",n.toneMapping!==Dh?owe("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Ln.colorspace_pars_fragment,swe("linearToOutputTexel",n.outputColorSpace),lwe(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  3785. `].filter(Ay).join(`
  3786. `)),o=tD(o),o=B8(o,n),o=H8(o,n),l=tD(l),l=B8(l,n),l=H8(l,n),o=$8(o),l=$8(l),n.isRawShaderMaterial!==!0&&(_=`#version 300 es
  3787. `,g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`
  3788. `)+`
  3789. `+g,y=["#define varying in",n.glslVersion===YB?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===YB?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
  3790. `)+`
  3791. `+y);const N=_+g+o,k=_+y+l,A=I8(a,a.VERTEX_SHADER,N),M=I8(a,a.FRAGMENT_SHADER,k);a.attachShader(v,A),a.attachShader(v,M),n.index0AttributeName!==void 0?a.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&a.bindAttribLocation(v,0,"position"),a.linkProgram(v);function C(U){if(t.debug.checkShaderErrors){const L=a.getProgramInfoLog(v)||"",B=a.getShaderInfoLog(A)||"",D=a.getShaderInfoLog(M)||"",$=L.trim(),G=B.trim(),z=D.trim();let W=!0,X=!0;if(a.getProgramParameter(v,a.LINK_STATUS)===!1)if(W=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(a,v,A,M);else{const ae=U8(a,A,"vertex"),H=U8(a,M,"fragment");Ua("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(v,a.VALIDATE_STATUS)+`
  3792. Material Name: `+U.name+`
  3793. Material Type: `+U.type+`
  3794. Program Info Log: `+$+`
  3795. `+ae+`
  3796. `+H)}else $!==""?vn("WebGLProgram: Program Info Log:",$):(G===""||z==="")&&(X=!1);X&&(U.diagnostics={runnable:W,programLog:$,vertexShader:{log:G,prefix:g},fragmentShader:{log:z,prefix:y}})}a.deleteShader(A),a.deleteShader(M),j=new Q_(a,v),P=dwe(a,v)}let j;this.getUniforms=function(){return j===void 0&&C(this),j};let P;this.getAttributes=function(){return P===void 0&&C(this),P};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=a.getProgramParameter(v,nwe)),E},this.destroy=function(){r.releaseStatesOfProgram(this),a.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=rwe++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=A,this.fragmentShader=M,this}let _we=0,Nwe=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,a=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(a)===!1&&(o.add(a),a.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new Cwe(e),n.set(e,r)),r}},Cwe=class{constructor(e){this.id=_we++,this.code=e,this.usedTimes=0}};function kwe(t,e,n,r,a,s,o){const l=new YX,c=new Nwe,u=new Set,d=[],h=a.logarithmicDepthBuffer,f=a.vertexTextures;let p=a.precision;const x={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(P){return u.add(P),P===0?"uv":`uv${P}`}function g(P,E,U,L,B){const D=L.fog,$=B.geometry,G=P.isMeshStandardMaterial?L.environment:null,z=(P.isMeshStandardMaterial?n:e).get(P.envMap||G),W=z&&z.mapping===nk?z.image.height:null,X=x[P.type];P.precision!==null&&(p=a.getMaxPrecision(P.precision),p!==P.precision&&vn("WebGLProgram.getParameters:",P.precision,"not supported, using",p,"instead."));const ae=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,H=ae!==void 0?ae.length:0;let K=0;$.morphAttributes.position!==void 0&&(K=1),$.morphAttributes.normal!==void 0&&(K=2),$.morphAttributes.color!==void 0&&(K=3);let te,Z,ve,ce;if(X){const Dt=wc[X];te=Dt.vertexShader,Z=Dt.fragmentShader}else te=P.vertexShader,Z=P.fragmentShader,c.update(P),ve=c.getVertexShaderID(P),ce=c.getFragmentShaderID(P);const ee=t.getRenderTarget(),je=t.state.buffers.depth.getReversed(),he=B.isInstancedMesh===!0,oe=B.isBatchedMesh===!0,_e=!!P.map,ie=!!P.matcap,ze=!!z,V=!!P.aoMap,Y=!!P.lightMap,me=!!P.bumpMap,Q=!!P.normalMap,se=!!P.displacementMap,de=!!P.emissiveMap,Le=!!P.metalnessMap,Ne=!!P.roughnessMap,be=P.anisotropy>0,O=P.clearcoat>0,R=P.dispersion>0,q=P.iridescence>0,J=P.sheen>0,fe=P.transmission>0,le=be&&!!P.anisotropyMap,Be=O&&!!P.clearcoatMap,Ie=O&&!!P.clearcoatNormalMap,Ke=O&&!!P.clearcoatRoughnessMap,Oe=q&&!!P.iridescenceMap,pe=q&&!!P.iridescenceThicknessMap,xe=J&&!!P.sheenColorMap,ke=J&&!!P.sheenRoughnessMap,ge=!!P.specularMap,we=!!P.specularColorMap,qe=!!P.specularIntensityMap,Ee=fe&&!!P.transmissionMap,tt=fe&&!!P.thicknessMap,De=!!P.gradientMap,We=!!P.alphaMap,Ae=P.alphaTest>0,Re=!!P.alphaHash,$e=!!P.extensions;let ht=Dh;P.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(ht=t.toneMapping);const At={shaderID:X,shaderType:P.type,shaderName:P.name,vertexShader:te,fragmentShader:Z,defines:P.defines,customVertexShaderID:ve,customFragmentShaderID:ce,isRawShaderMaterial:P.isRawShaderMaterial===!0,glslVersion:P.glslVersion,precision:p,batching:oe,batchingColor:oe&&B._colorsTexture!==null,instancing:he,instancingColor:he&&B.instanceColor!==null,instancingMorph:he&&B.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:ee===null?t.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:bb,alphaToCoverage:!!P.alphaToCoverage,map:_e,matcap:ie,envMap:ze,envMapMode:ze&&z.mapping,envMapCubeUVHeight:W,aoMap:V,lightMap:Y,bumpMap:me,normalMap:Q,displacementMap:f&&se,emissiveMap:de,normalMapObjectSpace:Q&&P.normalMapType===dbe,normalMapTangentSpace:Q&&P.normalMapType===BX,metalnessMap:Le,roughnessMap:Ne,anisotropy:be,anisotropyMap:le,clearcoat:O,clearcoatMap:Be,clearcoatNormalMap:Ie,clearcoatRoughnessMap:Ke,dispersion:R,iridescence:q,iridescenceMap:Oe,iridescenceThicknessMap:pe,sheen:J,sheenColorMap:xe,sheenRoughnessMap:ke,specularMap:ge,specularColorMap:we,specularIntensityMap:qe,transmission:fe,transmissionMap:Ee,thicknessMap:tt,gradientMap:De,opaque:P.transparent===!1&&P.blending===Yg&&P.alphaToCoverage===!1,alphaMap:We,alphaTest:Ae,alphaHash:Re,combine:P.combine,mapUv:_e&&v(P.map.channel),aoMapUv:V&&v(P.aoMap.channel),lightMapUv:Y&&v(P.lightMap.channel),bumpMapUv:me&&v(P.bumpMap.channel),normalMapUv:Q&&v(P.normalMap.channel),displacementMapUv:se&&v(P.displacementMap.channel),emissiveMapUv:de&&v(P.emissiveMap.channel),metalnessMapUv:Le&&v(P.metalnessMap.channel),roughnessMapUv:Ne&&v(P.roughnessMap.channel),anisotropyMapUv:le&&v(P.anisotropyMap.channel),clearcoatMapUv:Be&&v(P.clearcoatMap.channel),clearcoatNormalMapUv:Ie&&v(P.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ke&&v(P.clearcoatRoughnessMap.channel),iridescenceMapUv:Oe&&v(P.iridescenceMap.channel),iridescenceThicknessMapUv:pe&&v(P.iridescenceThicknessMap.channel),sheenColorMapUv:xe&&v(P.sheenColorMap.channel),sheenRoughnessMapUv:ke&&v(P.sheenRoughnessMap.channel),specularMapUv:ge&&v(P.specularMap.channel),specularColorMapUv:we&&v(P.specularColorMap.channel),specularIntensityMapUv:qe&&v(P.specularIntensityMap.channel),transmissionMapUv:Ee&&v(P.transmissionMap.channel),thicknessMapUv:tt&&v(P.thicknessMap.channel),alphaMapUv:We&&v(P.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(Q||be),vertexColors:P.vertexColors,vertexAlphas:P.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,pointsUvs:B.isPoints===!0&&!!$.attributes.uv&&(_e||We),fog:!!D,useFog:P.fog===!0,fogExp2:!!D&&D.isFogExp2,flatShading:P.flatShading===!0&&P.wireframe===!1,sizeAttenuation:P.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:je,skinning:B.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:H,morphTextureStride:K,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:P.dithering,shadowMapEnabled:t.shadowMap.enabled&&U.length>0,shadowMapType:t.shadowMap.type,toneMapping:ht,decodeVideoTexture:_e&&P.map.isVideoTexture===!0&&cr.getTransfer(P.map.colorSpace)===Dr,decodeVideoTextureEmissive:de&&P.emissiveMap.isVideoTexture===!0&&cr.getTransfer(P.emissiveMap.colorSpace)===Dr,premultipliedAlpha:P.premultipliedAlpha,doubleSided:P.side===_c,flipSided:P.side===to,useDepthPacking:P.depthPacking>=0,depthPacking:P.depthPacking||0,index0AttributeName:P.index0AttributeName,extensionClipCullDistance:$e&&P.extensions.clipCullDistance===!0&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:($e&&P.extensions.multiDraw===!0||oe)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:P.customProgramCacheKey()};return At.vertexUv1s=u.has(1),At.vertexUv2s=u.has(2),At.vertexUv3s=u.has(3),u.clear(),At}function y(P){const E=[];if(P.shaderID?E.push(P.shaderID):(E.push(P.customVertexShaderID),E.push(P.customFragmentShaderID)),P.defines!==void 0)for(const U in P.defines)E.push(U),E.push(P.defines[U]);return P.isRawShaderMaterial===!1&&(_(E,P),N(E,P),E.push(t.outputColorSpace)),E.push(P.customProgramCacheKey),E.join()}function _(P,E){P.push(E.precision),P.push(E.outputColorSpace),P.push(E.envMapMode),P.push(E.envMapCubeUVHeight),P.push(E.mapUv),P.push(E.alphaMapUv),P.push(E.lightMapUv),P.push(E.aoMapUv),P.push(E.bumpMapUv),P.push(E.normalMapUv),P.push(E.displacementMapUv),P.push(E.emissiveMapUv),P.push(E.metalnessMapUv),P.push(E.roughnessMapUv),P.push(E.anisotropyMapUv),P.push(E.clearcoatMapUv),P.push(E.clearcoatNormalMapUv),P.push(E.clearcoatRoughnessMapUv),P.push(E.iridescenceMapUv),P.push(E.iridescenceThicknessMapUv),P.push(E.sheenColorMapUv),P.push(E.sheenRoughnessMapUv),P.push(E.specularMapUv),P.push(E.specularColorMapUv),P.push(E.specularIntensityMapUv),P.push(E.transmissionMapUv),P.push(E.thicknessMapUv),P.push(E.combine),P.push(E.fogExp2),P.push(E.sizeAttenuation),P.push(E.morphTargetsCount),P.push(E.morphAttributeCount),P.push(E.numDirLights),P.push(E.numPointLights),P.push(E.numSpotLights),P.push(E.numSpotLightMaps),P.push(E.numHemiLights),P.push(E.numRectAreaLights),P.push(E.numDirLightShadows),P.push(E.numPointLightShadows),P.push(E.numSpotLightShadows),P.push(E.numSpotLightShadowsWithMaps),P.push(E.numLightProbes),P.push(E.shadowMapType),P.push(E.toneMapping),P.push(E.numClippingPlanes),P.push(E.numClipIntersection),P.push(E.depthPacking)}function N(P,E){l.disableAll(),E.supportsVertexTextures&&l.enable(0),E.instancing&&l.enable(1),E.instancingColor&&l.enable(2),E.instancingMorph&&l.enable(3),E.matcap&&l.enable(4),E.envMap&&l.enable(5),E.normalMapObjectSpace&&l.enable(6),E.normalMapTangentSpace&&l.enable(7),E.clearcoat&&l.enable(8),E.iridescence&&l.enable(9),E.alphaTest&&l.enable(10),E.vertexColors&&l.enable(11),E.vertexAlphas&&l.enable(12),E.vertexUv1s&&l.enable(13),E.vertexUv2s&&l.enable(14),E.vertexUv3s&&l.enable(15),E.vertexTangents&&l.enable(16),E.anisotropy&&l.enable(17),E.alphaHash&&l.enable(18),E.batching&&l.enable(19),E.dispersion&&l.enable(20),E.batchingColor&&l.enable(21),E.gradientMap&&l.enable(22),P.push(l.mask),l.disableAll(),E.fog&&l.enable(0),E.useFog&&l.enable(1),E.flatShading&&l.enable(2),E.logarithmicDepthBuffer&&l.enable(3),E.reversedDepthBuffer&&l.enable(4),E.skinning&&l.enable(5),E.morphTargets&&l.enable(6),E.morphNormals&&l.enable(7),E.morphColors&&l.enable(8),E.premultipliedAlpha&&l.enable(9),E.shadowMapEnabled&&l.enable(10),E.doubleSided&&l.enable(11),E.flipSided&&l.enable(12),E.useDepthPacking&&l.enable(13),E.dithering&&l.enable(14),E.transmission&&l.enable(15),E.sheen&&l.enable(16),E.opaque&&l.enable(17),E.pointsUvs&&l.enable(18),E.decodeVideoTexture&&l.enable(19),E.decodeVideoTextureEmissive&&l.enable(20),E.alphaToCoverage&&l.enable(21),P.push(l.mask)}function k(P){const E=x[P.type];let U;if(E){const L=wc[E];U=Bbe.clone(L.uniforms)}else U=P.uniforms;return U}function A(P,E){let U;for(let L=0,B=d.length;L<B;L++){const D=d[L];if(D.cacheKey===E){U=D,++U.usedTimes;break}}return U===void 0&&(U=new Swe(t,E,P,s),d.push(U)),U}function M(P){if(--P.usedTimes===0){const E=d.indexOf(P);d[E]=d[d.length-1],d.pop(),P.destroy()}}function C(P){c.remove(P)}function j(){c.dispose()}return{getParameters:g,getProgramCacheKey:y,getUniforms:k,acquireProgram:A,releaseProgram:M,releaseShaderCache:C,programs:d,dispose:j}}function Awe(){let t=new WeakMap;function e(o){return t.has(o)}function n(o){let l=t.get(o);return l===void 0&&(l={},t.set(o,l)),l}function r(o){t.delete(o)}function a(o,l,c){t.get(o)[l]=c}function s(){t=new WeakMap}return{has:e,get:n,remove:r,update:a,dispose:s}}function Twe(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function q8(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function G8(){const t=[];let e=0;const n=[],r=[],a=[];function s(){e=0,n.length=0,r.length=0,a.length=0}function o(h,f,p,x,v,g){let y=t[e];return y===void 0?(y={id:h.id,object:h,geometry:f,material:p,groupOrder:x,renderOrder:h.renderOrder,z:v,group:g},t[e]=y):(y.id=h.id,y.object=h,y.geometry=f,y.material=p,y.groupOrder=x,y.renderOrder=h.renderOrder,y.z=v,y.group=g),e++,y}function l(h,f,p,x,v,g){const y=o(h,f,p,x,v,g);p.transmission>0?r.push(y):p.transparent===!0?a.push(y):n.push(y)}function c(h,f,p,x,v,g){const y=o(h,f,p,x,v,g);p.transmission>0?r.unshift(y):p.transparent===!0?a.unshift(y):n.unshift(y)}function u(h,f){n.length>1&&n.sort(h||Twe),r.length>1&&r.sort(f||q8),a.length>1&&a.sort(f||q8)}function d(){for(let h=e,f=t.length;h<f;h++){const p=t[h];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:n,transmissive:r,transparent:a,init:s,push:l,unshift:c,finish:d,sort:u}}function Mwe(){let t=new WeakMap;function e(r,a){const s=t.get(r);let o;return s===void 0?(o=new G8,t.set(r,[o])):a>=s.length?(o=new G8,s.push(o)):o=s[a],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function Pwe(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new ft,color:new $n};break;case"SpotLight":n={position:new ft,direction:new ft,color:new $n,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new ft,color:new $n,distance:0,decay:0};break;case"HemisphereLight":n={direction:new ft,skyColor:new $n,groundColor:new $n};break;case"RectAreaLight":n={color:new $n,position:new ft,halfWidth:new ft,halfHeight:new ft};break}return t[e.id]=n,n}}}function Ewe(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Un};break;case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Un};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Un,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let jwe=0;function Dwe(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Rwe(t){const e=new Pwe,n=Ewe(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let u=0;u<9;u++)r.probe.push(new ft);const a=new ft,s=new ri,o=new ri;function l(u){let d=0,h=0,f=0;for(let P=0;P<9;P++)r.probe[P].set(0,0,0);let p=0,x=0,v=0,g=0,y=0,_=0,N=0,k=0,A=0,M=0,C=0;u.sort(Dwe);for(let P=0,E=u.length;P<E;P++){const U=u[P],L=U.color,B=U.intensity,D=U.distance,$=U.shadow&&U.shadow.map?U.shadow.map.texture:null;if(U.isAmbientLight)d+=L.r*B,h+=L.g*B,f+=L.b*B;else if(U.isLightProbe){for(let G=0;G<9;G++)r.probe[G].addScaledVector(U.sh.coefficients[G],B);C++}else if(U.isDirectionalLight){const G=e.get(U);if(G.color.copy(U.color).multiplyScalar(U.intensity),U.castShadow){const z=U.shadow,W=n.get(U);W.shadowIntensity=z.intensity,W.shadowBias=z.bias,W.shadowNormalBias=z.normalBias,W.shadowRadius=z.radius,W.shadowMapSize=z.mapSize,r.directionalShadow[p]=W,r.directionalShadowMap[p]=$,r.directionalShadowMatrix[p]=U.shadow.matrix,_++}r.directional[p]=G,p++}else if(U.isSpotLight){const G=e.get(U);G.position.setFromMatrixPosition(U.matrixWorld),G.color.copy(L).multiplyScalar(B),G.distance=D,G.coneCos=Math.cos(U.angle),G.penumbraCos=Math.cos(U.angle*(1-U.penumbra)),G.decay=U.decay,r.spot[v]=G;const z=U.shadow;if(U.map&&(r.spotLightMap[A]=U.map,A++,z.updateMatrices(U),U.castShadow&&M++),r.spotLightMatrix[v]=z.matrix,U.castShadow){const W=n.get(U);W.shadowIntensity=z.intensity,W.shadowBias=z.bias,W.shadowNormalBias=z.normalBias,W.shadowRadius=z.radius,W.shadowMapSize=z.mapSize,r.spotShadow[v]=W,r.spotShadowMap[v]=$,k++}v++}else if(U.isRectAreaLight){const G=e.get(U);G.color.copy(L).multiplyScalar(B),G.halfWidth.set(U.width*.5,0,0),G.halfHeight.set(0,U.height*.5,0),r.rectArea[g]=G,g++}else if(U.isPointLight){const G=e.get(U);if(G.color.copy(U.color).multiplyScalar(U.intensity),G.distance=U.distance,G.decay=U.decay,U.castShadow){const z=U.shadow,W=n.get(U);W.shadowIntensity=z.intensity,W.shadowBias=z.bias,W.shadowNormalBias=z.normalBias,W.shadowRadius=z.radius,W.shadowMapSize=z.mapSize,W.shadowCameraNear=z.camera.near,W.shadowCameraFar=z.camera.far,r.pointShadow[x]=W,r.pointShadowMap[x]=$,r.pointShadowMatrix[x]=U.shadow.matrix,N++}r.point[x]=G,x++}else if(U.isHemisphereLight){const G=e.get(U);G.skyColor.copy(U.color).multiplyScalar(B),G.groundColor.copy(U.groundColor).multiplyScalar(B),r.hemi[y]=G,y++}}g>0&&(t.has("OES_texture_float_linear")===!0?(r.rectAreaLTC1=Bt.LTC_FLOAT_1,r.rectAreaLTC2=Bt.LTC_FLOAT_2):(r.rectAreaLTC1=Bt.LTC_HALF_1,r.rectAreaLTC2=Bt.LTC_HALF_2)),r.ambient[0]=d,r.ambient[1]=h,r.ambient[2]=f;const j=r.hash;(j.directionalLength!==p||j.pointLength!==x||j.spotLength!==v||j.rectAreaLength!==g||j.hemiLength!==y||j.numDirectionalShadows!==_||j.numPointShadows!==N||j.numSpotShadows!==k||j.numSpotMaps!==A||j.numLightProbes!==C)&&(r.directional.length=p,r.spot.length=v,r.rectArea.length=g,r.point.length=x,r.hemi.length=y,r.directionalShadow.length=_,r.directionalShadowMap.length=_,r.pointShadow.length=N,r.pointShadowMap.length=N,r.spotShadow.length=k,r.spotShadowMap.length=k,r.directionalShadowMatrix.length=_,r.pointShadowMatrix.length=N,r.spotLightMatrix.length=k+A-M,r.spotLightMap.length=A,r.numSpotLightShadowsWithMaps=M,r.numLightProbes=C,j.directionalLength=p,j.pointLength=x,j.spotLength=v,j.rectAreaLength=g,j.hemiLength=y,j.numDirectionalShadows=_,j.numPointShadows=N,j.numSpotShadows=k,j.numSpotMaps=A,j.numLightProbes=C,r.version=jwe++)}function c(u,d){let h=0,f=0,p=0,x=0,v=0;const g=d.matrixWorldInverse;for(let y=0,_=u.length;y<_;y++){const N=u[y];if(N.isDirectionalLight){const k=r.directional[h];k.direction.setFromMatrixPosition(N.matrixWorld),a.setFromMatrixPosition(N.target.matrixWorld),k.direction.sub(a),k.direction.transformDirection(g),h++}else if(N.isSpotLight){const k=r.spot[p];k.position.setFromMatrixPosition(N.matrixWorld),k.position.applyMatrix4(g),k.direction.setFromMatrixPosition(N.matrixWorld),a.setFromMatrixPosition(N.target.matrixWorld),k.direction.sub(a),k.direction.transformDirection(g),p++}else if(N.isRectAreaLight){const k=r.rectArea[x];k.position.setFromMatrixPosition(N.matrixWorld),k.position.applyMatrix4(g),o.identity(),s.copy(N.matrixWorld),s.premultiply(g),o.extractRotation(s),k.halfWidth.set(N.width*.5,0,0),k.halfHeight.set(0,N.height*.5,0),k.halfWidth.applyMatrix4(o),k.halfHeight.applyMatrix4(o),x++}else if(N.isPointLight){const k=r.point[f];k.position.setFromMatrixPosition(N.matrixWorld),k.position.applyMatrix4(g),f++}else if(N.isHemisphereLight){const k=r.hemi[v];k.direction.setFromMatrixPosition(N.matrixWorld),k.direction.transformDirection(g),v++}}}return{setup:l,setupView:c,state:r}}function W8(t){const e=new Rwe(t),n=[],r=[];function a(d){u.camera=d,n.length=0,r.length=0}function s(d){n.push(d)}function o(d){r.push(d)}function l(){e.setup(n)}function c(d){e.setupView(n,d)}const u={lightsArray:n,shadowsArray:r,camera:null,lights:e,transmissionRenderTarget:{}};return{init:a,state:u,setupLights:l,setupLightsView:c,pushLight:s,pushShadow:o}}function Fwe(t){let e=new WeakMap;function n(a,s=0){const o=e.get(a);let l;return o===void 0?(l=new W8(t),e.set(a,[l])):s>=o.length?(l=new W8(t),o.push(l)):l=o[s],l}function r(){e=new WeakMap}return{get:n,dispose:r}}const Lwe=`void main() {
  3797. gl_Position = vec4( position, 1.0 );
  3798. }`,Owe=`uniform sampler2D shadow_pass;
  3799. uniform vec2 resolution;
  3800. uniform float radius;
  3801. #include <packing>
  3802. void main() {
  3803. const float samples = float( VSM_SAMPLES );
  3804. float mean = 0.0;
  3805. float squared_mean = 0.0;
  3806. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  3807. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  3808. for ( float i = 0.0; i < samples; i ++ ) {
  3809. float uvOffset = uvStart + i * uvStride;
  3810. #ifdef HORIZONTAL_PASS
  3811. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  3812. mean += distribution.x;
  3813. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  3814. #else
  3815. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  3816. mean += depth;
  3817. squared_mean += depth * depth;
  3818. #endif
  3819. }
  3820. mean = mean / samples;
  3821. squared_mean = squared_mean / samples;
  3822. float std_dev = sqrt( squared_mean - mean * mean );
  3823. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  3824. }`;function Iwe(t,e,n){let r=new WF;const a=new Un,s=new Un,o=new Za,l=new exe({depthPacking:ube}),c=new txe,u={},d=n.maxTextureSize,h={[qh]:to,[to]:qh,[_c]:_c},f=new ad({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Un},radius:{value:4}},vertexShader:Lwe,fragmentShader:Owe}),p=f.clone();p.defines.HORIZONTAL_PASS=1;const x=new wl;x.setAttribute("position",new Ds(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Sl(x,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=jX;let y=this.type;this.render=function(M,C,j){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||M.length===0)return;const P=t.getRenderTarget(),E=t.getActiveCubeFace(),U=t.getActiveMipmapLevel(),L=t.state;L.setBlending(Vu),L.buffers.depth.getReversed()===!0?L.buffers.color.setClear(0,0,0,0):L.buffers.color.setClear(1,1,1,1),L.buffers.depth.setTest(!0),L.setScissorTest(!1);const B=y!==Tu&&this.type===Tu,D=y===Tu&&this.type!==Tu;for(let $=0,G=M.length;$<G;$++){const z=M[$],W=z.shadow;if(W===void 0){vn("WebGLShadowMap:",z,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;a.copy(W.mapSize);const X=W.getFrameExtents();if(a.multiply(X),s.copy(W.mapSize),(a.x>d||a.y>d)&&(a.x>d&&(s.x=Math.floor(d/X.x),a.x=s.x*X.x,W.mapSize.x=s.x),a.y>d&&(s.y=Math.floor(d/X.y),a.y=s.y*X.y,W.mapSize.y=s.y)),W.map===null||B===!0||D===!0){const H=this.type!==Tu?{minFilter:Eo,magFilter:Eo}:{};W.map!==null&&W.map.dispose(),W.map=new Of(a.x,a.y,H),W.map.texture.name=z.name+".shadowMap",W.camera.updateProjectionMatrix()}t.setRenderTarget(W.map),t.clear();const ae=W.getViewportCount();for(let H=0;H<ae;H++){const K=W.getViewport(H);o.set(s.x*K.x,s.y*K.y,s.x*K.z,s.y*K.w),L.viewport(o),W.updateMatrices(z,H),r=W.getFrustum(),k(C,j,W.camera,z,this.type)}W.isPointLightShadow!==!0&&this.type===Tu&&_(W,j),W.needsUpdate=!1}y=this.type,g.needsUpdate=!1,t.setRenderTarget(P,E,U)};function _(M,C){const j=e.update(v);f.defines.VSM_SAMPLES!==M.blurSamples&&(f.defines.VSM_SAMPLES=M.blurSamples,p.defines.VSM_SAMPLES=M.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new Of(a.x,a.y)),f.uniforms.shadow_pass.value=M.map.texture,f.uniforms.resolution.value=M.mapSize,f.uniforms.radius.value=M.radius,t.setRenderTarget(M.mapPass),t.clear(),t.renderBufferDirect(C,null,j,f,v,null),p.uniforms.shadow_pass.value=M.mapPass.texture,p.uniforms.resolution.value=M.mapSize,p.uniforms.radius.value=M.radius,t.setRenderTarget(M.map),t.clear(),t.renderBufferDirect(C,null,j,p,v,null)}function N(M,C,j,P){let E=null;const U=j.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if(U!==void 0)E=U;else if(E=j.isPointLight===!0?c:l,t.localClippingEnabled&&C.clipShadows===!0&&Array.isArray(C.clippingPlanes)&&C.clippingPlanes.length!==0||C.displacementMap&&C.displacementScale!==0||C.alphaMap&&C.alphaTest>0||C.map&&C.alphaTest>0||C.alphaToCoverage===!0){const L=E.uuid,B=C.uuid;let D=u[L];D===void 0&&(D={},u[L]=D);let $=D[B];$===void 0&&($=E.clone(),D[B]=$,C.addEventListener("dispose",A)),E=$}if(E.visible=C.visible,E.wireframe=C.wireframe,P===Tu?E.side=C.shadowSide!==null?C.shadowSide:C.side:E.side=C.shadowSide!==null?C.shadowSide:h[C.side],E.alphaMap=C.alphaMap,E.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,E.map=C.map,E.clipShadows=C.clipShadows,E.clippingPlanes=C.clippingPlanes,E.clipIntersection=C.clipIntersection,E.displacementMap=C.displacementMap,E.displacementScale=C.displacementScale,E.displacementBias=C.displacementBias,E.wireframeLinewidth=C.wireframeLinewidth,E.linewidth=C.linewidth,j.isPointLight===!0&&E.isMeshDistanceMaterial===!0){const L=t.properties.get(E);L.light=j}return E}function k(M,C,j,P,E){if(M.visible===!1)return;if(M.layers.test(C.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&E===Tu)&&(!M.frustumCulled||r.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(j.matrixWorldInverse,M.matrixWorld);const B=e.update(M),D=M.material;if(Array.isArray(D)){const $=B.groups;for(let G=0,z=$.length;G<z;G++){const W=$[G],X=D[W.materialIndex];if(X&&X.visible){const ae=N(M,X,P,E);M.onBeforeShadow(t,M,C,j,B,ae,W),t.renderBufferDirect(j,null,B,ae,M,W),M.onAfterShadow(t,M,C,j,B,ae,W)}}}else if(D.visible){const $=N(M,D,P,E);M.onBeforeShadow(t,M,C,j,B,$,null),t.renderBufferDirect(j,null,B,$,M,null),M.onAfterShadow(t,M,C,j,B,$,null)}}const L=M.children;for(let B=0,D=L.length;B<D;B++)k(L[B],C,j,P,E)}function A(M){M.target.removeEventListener("dispose",A);for(const j in u){const P=u[j],E=M.target.uuid;E in P&&(P[E].dispose(),delete P[E])}}}const zwe={[f3]:p3,[g3]:y3,[b3]:v3,[fb]:x3,[p3]:f3,[y3]:g3,[v3]:b3,[x3]:fb};function Uwe(t,e){function n(){let Ee=!1;const tt=new Za;let De=null;const We=new Za(0,0,0,0);return{setMask:function(Ae){De!==Ae&&!Ee&&(t.colorMask(Ae,Ae,Ae,Ae),De=Ae)},setLocked:function(Ae){Ee=Ae},setClear:function(Ae,Re,$e,ht,At){At===!0&&(Ae*=ht,Re*=ht,$e*=ht),tt.set(Ae,Re,$e,ht),We.equals(tt)===!1&&(t.clearColor(Ae,Re,$e,ht),We.copy(tt))},reset:function(){Ee=!1,De=null,We.set(-1,0,0,0)}}}function r(){let Ee=!1,tt=!1,De=null,We=null,Ae=null;return{setReversed:function(Re){if(tt!==Re){const $e=e.get("EXT_clip_control");Re?$e.clipControlEXT($e.LOWER_LEFT_EXT,$e.ZERO_TO_ONE_EXT):$e.clipControlEXT($e.LOWER_LEFT_EXT,$e.NEGATIVE_ONE_TO_ONE_EXT),tt=Re;const ht=Ae;Ae=null,this.setClear(ht)}},getReversed:function(){return tt},setTest:function(Re){Re?ee(t.DEPTH_TEST):je(t.DEPTH_TEST)},setMask:function(Re){De!==Re&&!Ee&&(t.depthMask(Re),De=Re)},setFunc:function(Re){if(tt&&(Re=zwe[Re]),We!==Re){switch(Re){case f3:t.depthFunc(t.NEVER);break;case p3:t.depthFunc(t.ALWAYS);break;case g3:t.depthFunc(t.LESS);break;case fb:t.depthFunc(t.LEQUAL);break;case b3:t.depthFunc(t.EQUAL);break;case x3:t.depthFunc(t.GEQUAL);break;case y3:t.depthFunc(t.GREATER);break;case v3:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}We=Re}},setLocked:function(Re){Ee=Re},setClear:function(Re){Ae!==Re&&(tt&&(Re=1-Re),t.clearDepth(Re),Ae=Re)},reset:function(){Ee=!1,De=null,We=null,Ae=null,tt=!1}}}function a(){let Ee=!1,tt=null,De=null,We=null,Ae=null,Re=null,$e=null,ht=null,At=null;return{setTest:function(Dt){Ee||(Dt?ee(t.STENCIL_TEST):je(t.STENCIL_TEST))},setMask:function(Dt){tt!==Dt&&!Ee&&(t.stencilMask(Dt),tt=Dt)},setFunc:function(Dt,It,kt){(De!==Dt||We!==It||Ae!==kt)&&(t.stencilFunc(Dt,It,kt),De=Dt,We=It,Ae=kt)},setOp:function(Dt,It,kt){(Re!==Dt||$e!==It||ht!==kt)&&(t.stencilOp(Dt,It,kt),Re=Dt,$e=It,ht=kt)},setLocked:function(Dt){Ee=Dt},setClear:function(Dt){At!==Dt&&(t.clearStencil(Dt),At=Dt)},reset:function(){Ee=!1,tt=null,De=null,We=null,Ae=null,Re=null,$e=null,ht=null,At=null}}}const s=new n,o=new r,l=new a,c=new WeakMap,u=new WeakMap;let d={},h={},f=new WeakMap,p=[],x=null,v=!1,g=null,y=null,_=null,N=null,k=null,A=null,M=null,C=new $n(0,0,0),j=0,P=!1,E=null,U=null,L=null,B=null,D=null;const $=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let G=!1,z=0;const W=t.getParameter(t.VERSION);W.indexOf("WebGL")!==-1?(z=parseFloat(/^WebGL (\d)/.exec(W)[1]),G=z>=1):W.indexOf("OpenGL ES")!==-1&&(z=parseFloat(/^OpenGL ES (\d)/.exec(W)[1]),G=z>=2);let X=null,ae={};const H=t.getParameter(t.SCISSOR_BOX),K=t.getParameter(t.VIEWPORT),te=new Za().fromArray(H),Z=new Za().fromArray(K);function ve(Ee,tt,De,We){const Ae=new Uint8Array(4),Re=t.createTexture();t.bindTexture(Ee,Re),t.texParameteri(Ee,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(Ee,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let $e=0;$e<De;$e++)Ee===t.TEXTURE_3D||Ee===t.TEXTURE_2D_ARRAY?t.texImage3D(tt,0,t.RGBA,1,1,We,0,t.RGBA,t.UNSIGNED_BYTE,Ae):t.texImage2D(tt+$e,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Ae);return Re}const ce={};ce[t.TEXTURE_2D]=ve(t.TEXTURE_2D,t.TEXTURE_2D,1),ce[t.TEXTURE_CUBE_MAP]=ve(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),ce[t.TEXTURE_2D_ARRAY]=ve(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),ce[t.TEXTURE_3D]=ve(t.TEXTURE_3D,t.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),l.setClear(0),ee(t.DEPTH_TEST),o.setFunc(fb),me(!1),Q(VB),ee(t.CULL_FACE),V(Vu);function ee(Ee){d[Ee]!==!0&&(t.enable(Ee),d[Ee]=!0)}function je(Ee){d[Ee]!==!1&&(t.disable(Ee),d[Ee]=!1)}function he(Ee,tt){return h[Ee]!==tt?(t.bindFramebuffer(Ee,tt),h[Ee]=tt,Ee===t.DRAW_FRAMEBUFFER&&(h[t.FRAMEBUFFER]=tt),Ee===t.FRAMEBUFFER&&(h[t.DRAW_FRAMEBUFFER]=tt),!0):!1}function oe(Ee,tt){let De=p,We=!1;if(Ee){De=f.get(tt),De===void 0&&(De=[],f.set(tt,De));const Ae=Ee.textures;if(De.length!==Ae.length||De[0]!==t.COLOR_ATTACHMENT0){for(let Re=0,$e=Ae.length;Re<$e;Re++)De[Re]=t.COLOR_ATTACHMENT0+Re;De.length=Ae.length,We=!0}}else De[0]!==t.BACK&&(De[0]=t.BACK,We=!0);We&&t.drawBuffers(De)}function _e(Ee){return x!==Ee?(t.useProgram(Ee),x=Ee,!0):!1}const ie={[Gm]:t.FUNC_ADD,[Lge]:t.FUNC_SUBTRACT,[Oge]:t.FUNC_REVERSE_SUBTRACT};ie[Ige]=t.MIN,ie[zge]=t.MAX;const ze={[Uge]:t.ZERO,[Bge]:t.ONE,[Hge]:t.SRC_COLOR,[h3]:t.SRC_ALPHA,[Kge]:t.SRC_ALPHA_SATURATE,[Gge]:t.DST_COLOR,[Vge]:t.DST_ALPHA,[$ge]:t.ONE_MINUS_SRC_COLOR,[m3]:t.ONE_MINUS_SRC_ALPHA,[Wge]:t.ONE_MINUS_DST_COLOR,[qge]:t.ONE_MINUS_DST_ALPHA,[Xge]:t.CONSTANT_COLOR,[Yge]:t.ONE_MINUS_CONSTANT_COLOR,[Qge]:t.CONSTANT_ALPHA,[Zge]:t.ONE_MINUS_CONSTANT_ALPHA};function V(Ee,tt,De,We,Ae,Re,$e,ht,At,Dt){if(Ee===Vu){v===!0&&(je(t.BLEND),v=!1);return}if(v===!1&&(ee(t.BLEND),v=!0),Ee!==Fge){if(Ee!==g||Dt!==P){if((y!==Gm||k!==Gm)&&(t.blendEquation(t.FUNC_ADD),y=Gm,k=Gm),Dt)switch(Ee){case Yg:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case qB:t.blendFunc(t.ONE,t.ONE);break;case GB:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case WB:t.blendFuncSeparate(t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ZERO,t.ONE);break;default:Ua("WebGLState: Invalid blending: ",Ee);break}else switch(Ee){case Yg:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case qB:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE,t.ONE,t.ONE);break;case GB:Ua("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case WB:Ua("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ua("WebGLState: Invalid blending: ",Ee);break}_=null,N=null,A=null,M=null,C.set(0,0,0),j=0,g=Ee,P=Dt}return}Ae=Ae||tt,Re=Re||De,$e=$e||We,(tt!==y||Ae!==k)&&(t.blendEquationSeparate(ie[tt],ie[Ae]),y=tt,k=Ae),(De!==_||We!==N||Re!==A||$e!==M)&&(t.blendFuncSeparate(ze[De],ze[We],ze[Re],ze[$e]),_=De,N=We,A=Re,M=$e),(ht.equals(C)===!1||At!==j)&&(t.blendColor(ht.r,ht.g,ht.b,At),C.copy(ht),j=At),g=Ee,P=!1}function Y(Ee,tt){Ee.side===_c?je(t.CULL_FACE):ee(t.CULL_FACE);let De=Ee.side===to;tt&&(De=!De),me(De),Ee.blending===Yg&&Ee.transparent===!1?V(Vu):V(Ee.blending,Ee.blendEquation,Ee.blendSrc,Ee.blendDst,Ee.blendEquationAlpha,Ee.blendSrcAlpha,Ee.blendDstAlpha,Ee.blendColor,Ee.blendAlpha,Ee.premultipliedAlpha),o.setFunc(Ee.depthFunc),o.setTest(Ee.depthTest),o.setMask(Ee.depthWrite),s.setMask(Ee.colorWrite);const We=Ee.stencilWrite;l.setTest(We),We&&(l.setMask(Ee.stencilWriteMask),l.setFunc(Ee.stencilFunc,Ee.stencilRef,Ee.stencilFuncMask),l.setOp(Ee.stencilFail,Ee.stencilZFail,Ee.stencilZPass)),de(Ee.polygonOffset,Ee.polygonOffsetFactor,Ee.polygonOffsetUnits),Ee.alphaToCoverage===!0?ee(t.SAMPLE_ALPHA_TO_COVERAGE):je(t.SAMPLE_ALPHA_TO_COVERAGE)}function me(Ee){E!==Ee&&(Ee?t.frontFace(t.CW):t.frontFace(t.CCW),E=Ee)}function Q(Ee){Ee!==jge?(ee(t.CULL_FACE),Ee!==U&&(Ee===VB?t.cullFace(t.BACK):Ee===Dge?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):je(t.CULL_FACE),U=Ee}function se(Ee){Ee!==L&&(G&&t.lineWidth(Ee),L=Ee)}function de(Ee,tt,De){Ee?(ee(t.POLYGON_OFFSET_FILL),(B!==tt||D!==De)&&(t.polygonOffset(tt,De),B=tt,D=De)):je(t.POLYGON_OFFSET_FILL)}function Le(Ee){Ee?ee(t.SCISSOR_TEST):je(t.SCISSOR_TEST)}function Ne(Ee){Ee===void 0&&(Ee=t.TEXTURE0+$-1),X!==Ee&&(t.activeTexture(Ee),X=Ee)}function be(Ee,tt,De){De===void 0&&(X===null?De=t.TEXTURE0+$-1:De=X);let We=ae[De];We===void 0&&(We={type:void 0,texture:void 0},ae[De]=We),(We.type!==Ee||We.texture!==tt)&&(X!==De&&(t.activeTexture(De),X=De),t.bindTexture(Ee,tt||ce[Ee]),We.type=Ee,We.texture=tt)}function O(){const Ee=ae[X];Ee!==void 0&&Ee.type!==void 0&&(t.bindTexture(Ee.type,null),Ee.type=void 0,Ee.texture=void 0)}function R(){try{t.compressedTexImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function q(){try{t.compressedTexImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function J(){try{t.texSubImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function fe(){try{t.texSubImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function le(){try{t.compressedTexSubImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Be(){try{t.compressedTexSubImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Ie(){try{t.texStorage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Ke(){try{t.texStorage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function Oe(){try{t.texImage2D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function pe(){try{t.texImage3D(...arguments)}catch(Ee){Ee("WebGLState:",Ee)}}function xe(Ee){te.equals(Ee)===!1&&(t.scissor(Ee.x,Ee.y,Ee.z,Ee.w),te.copy(Ee))}function ke(Ee){Z.equals(Ee)===!1&&(t.viewport(Ee.x,Ee.y,Ee.z,Ee.w),Z.copy(Ee))}function ge(Ee,tt){let De=u.get(tt);De===void 0&&(De=new WeakMap,u.set(tt,De));let We=De.get(Ee);We===void 0&&(We=t.getUniformBlockIndex(tt,Ee.name),De.set(Ee,We))}function we(Ee,tt){const We=u.get(tt).get(Ee);c.get(tt)!==We&&(t.uniformBlockBinding(tt,We,Ee.__bindingPointIndex),c.set(tt,We))}function qe(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),o.setReversed(!1),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),d={},X=null,ae={},h={},f=new WeakMap,p=[],x=null,v=!1,g=null,y=null,_=null,N=null,k=null,A=null,M=null,C=new $n(0,0,0),j=0,P=!1,E=null,U=null,L=null,B=null,D=null,te.set(0,0,t.canvas.width,t.canvas.height),Z.set(0,0,t.canvas.width,t.canvas.height),s.reset(),o.reset(),l.reset()}return{buffers:{color:s,depth:o,stencil:l},enable:ee,disable:je,bindFramebuffer:he,drawBuffers:oe,useProgram:_e,setBlending:V,setMaterial:Y,setFlipSided:me,setCullFace:Q,setLineWidth:se,setPolygonOffset:de,setScissorTest:Le,activeTexture:Ne,bindTexture:be,unbindTexture:O,compressedTexImage2D:R,compressedTexImage3D:q,texImage2D:Oe,texImage3D:pe,updateUBOMapping:ge,uniformBlockBinding:we,texStorage2D:Ie,texStorage3D:Ke,texSubImage2D:J,texSubImage3D:fe,compressedTexSubImage2D:le,compressedTexSubImage3D:Be,scissor:xe,viewport:ke,reset:qe}}function Bwe(t,e,n,r,a,s,o){const l=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),u=new Un,d=new WeakMap;let h;const f=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function x(O,R){return p?new OffscreenCanvas(O,R):M1("canvas")}function v(O,R,q){let J=1;const fe=be(O);if((fe.width>q||fe.height>q)&&(J=q/Math.max(fe.width,fe.height)),J<1)if(typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&O instanceof ImageBitmap||typeof VideoFrame<"u"&&O instanceof VideoFrame){const le=Math.floor(J*fe.width),Be=Math.floor(J*fe.height);h===void 0&&(h=x(le,Be));const Ie=R?x(le,Be):h;return Ie.width=le,Ie.height=Be,Ie.getContext("2d").drawImage(O,0,0,le,Be),vn("WebGLRenderer: Texture has been resized from ("+fe.width+"x"+fe.height+") to ("+le+"x"+Be+")."),Ie}else return"data"in O&&vn("WebGLRenderer: Image in DataTexture is too big ("+fe.width+"x"+fe.height+")."),O;return O}function g(O){return O.generateMipmaps}function y(O){t.generateMipmap(O)}function _(O){return O.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:O.isWebGL3DRenderTarget?t.TEXTURE_3D:O.isWebGLArrayRenderTarget||O.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:t.TEXTURE_2D}function N(O,R,q,J,fe=!1){if(O!==null){if(t[O]!==void 0)return t[O];vn("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+O+"'")}let le=R;if(R===t.RED&&(q===t.FLOAT&&(le=t.R32F),q===t.HALF_FLOAT&&(le=t.R16F),q===t.UNSIGNED_BYTE&&(le=t.R8)),R===t.RED_INTEGER&&(q===t.UNSIGNED_BYTE&&(le=t.R8UI),q===t.UNSIGNED_SHORT&&(le=t.R16UI),q===t.UNSIGNED_INT&&(le=t.R32UI),q===t.BYTE&&(le=t.R8I),q===t.SHORT&&(le=t.R16I),q===t.INT&&(le=t.R32I)),R===t.RG&&(q===t.FLOAT&&(le=t.RG32F),q===t.HALF_FLOAT&&(le=t.RG16F),q===t.UNSIGNED_BYTE&&(le=t.RG8)),R===t.RG_INTEGER&&(q===t.UNSIGNED_BYTE&&(le=t.RG8UI),q===t.UNSIGNED_SHORT&&(le=t.RG16UI),q===t.UNSIGNED_INT&&(le=t.RG32UI),q===t.BYTE&&(le=t.RG8I),q===t.SHORT&&(le=t.RG16I),q===t.INT&&(le=t.RG32I)),R===t.RGB_INTEGER&&(q===t.UNSIGNED_BYTE&&(le=t.RGB8UI),q===t.UNSIGNED_SHORT&&(le=t.RGB16UI),q===t.UNSIGNED_INT&&(le=t.RGB32UI),q===t.BYTE&&(le=t.RGB8I),q===t.SHORT&&(le=t.RGB16I),q===t.INT&&(le=t.RGB32I)),R===t.RGBA_INTEGER&&(q===t.UNSIGNED_BYTE&&(le=t.RGBA8UI),q===t.UNSIGNED_SHORT&&(le=t.RGBA16UI),q===t.UNSIGNED_INT&&(le=t.RGBA32UI),q===t.BYTE&&(le=t.RGBA8I),q===t.SHORT&&(le=t.RGBA16I),q===t.INT&&(le=t.RGBA32I)),R===t.RGB&&(q===t.UNSIGNED_INT_5_9_9_9_REV&&(le=t.RGB9_E5),q===t.UNSIGNED_INT_10F_11F_11F_REV&&(le=t.R11F_G11F_B10F)),R===t.RGBA){const Be=fe?A1:cr.getTransfer(J);q===t.FLOAT&&(le=t.RGBA32F),q===t.HALF_FLOAT&&(le=t.RGBA16F),q===t.UNSIGNED_BYTE&&(le=Be===Dr?t.SRGB8_ALPHA8:t.RGBA8),q===t.UNSIGNED_SHORT_4_4_4_4&&(le=t.RGBA4),q===t.UNSIGNED_SHORT_5_5_5_1&&(le=t.RGB5_A1)}return(le===t.R16F||le===t.R32F||le===t.RG16F||le===t.RG32F||le===t.RGBA16F||le===t.RGBA32F)&&e.get("EXT_color_buffer_float"),le}function k(O,R){let q;return O?R===null||R===Ff||R===wv?q=t.DEPTH24_STENCIL8:R===Iu?q=t.DEPTH32F_STENCIL8:R===vv&&(q=t.DEPTH24_STENCIL8,vn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):R===null||R===Ff||R===wv?q=t.DEPTH_COMPONENT24:R===Iu?q=t.DEPTH_COMPONENT32F:R===vv&&(q=t.DEPTH_COMPONENT16),q}function A(O,R){return g(O)===!0||O.isFramebufferTexture&&O.minFilter!==Eo&&O.minFilter!==hl?Math.log2(Math.max(R.width,R.height))+1:O.mipmaps!==void 0&&O.mipmaps.length>0?O.mipmaps.length:O.isCompressedTexture&&Array.isArray(O.image)?R.mipmaps.length:1}function M(O){const R=O.target;R.removeEventListener("dispose",M),j(R),R.isVideoTexture&&d.delete(R)}function C(O){const R=O.target;R.removeEventListener("dispose",C),E(R)}function j(O){const R=r.get(O);if(R.__webglInit===void 0)return;const q=O.source,J=f.get(q);if(J){const fe=J[R.__cacheKey];fe.usedTimes--,fe.usedTimes===0&&P(O),Object.keys(J).length===0&&f.delete(q)}r.remove(O)}function P(O){const R=r.get(O);t.deleteTexture(R.__webglTexture);const q=O.source,J=f.get(q);delete J[R.__cacheKey],o.memory.textures--}function E(O){const R=r.get(O);if(O.depthTexture&&(O.depthTexture.dispose(),r.remove(O.depthTexture)),O.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(R.__webglFramebuffer[J]))for(let fe=0;fe<R.__webglFramebuffer[J].length;fe++)t.deleteFramebuffer(R.__webglFramebuffer[J][fe]);else t.deleteFramebuffer(R.__webglFramebuffer[J]);R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer[J])}else{if(Array.isArray(R.__webglFramebuffer))for(let J=0;J<R.__webglFramebuffer.length;J++)t.deleteFramebuffer(R.__webglFramebuffer[J]);else t.deleteFramebuffer(R.__webglFramebuffer);if(R.__webglDepthbuffer&&t.deleteRenderbuffer(R.__webglDepthbuffer),R.__webglMultisampledFramebuffer&&t.deleteFramebuffer(R.__webglMultisampledFramebuffer),R.__webglColorRenderbuffer)for(let J=0;J<R.__webglColorRenderbuffer.length;J++)R.__webglColorRenderbuffer[J]&&t.deleteRenderbuffer(R.__webglColorRenderbuffer[J]);R.__webglDepthRenderbuffer&&t.deleteRenderbuffer(R.__webglDepthRenderbuffer)}const q=O.textures;for(let J=0,fe=q.length;J<fe;J++){const le=r.get(q[J]);le.__webglTexture&&(t.deleteTexture(le.__webglTexture),o.memory.textures--),r.remove(q[J])}r.remove(O)}let U=0;function L(){U=0}function B(){const O=U;return O>=a.maxTextures&&vn("WebGLTextures: Trying to use "+O+" texture units while this GPU supports only "+a.maxTextures),U+=1,O}function D(O){const R=[];return R.push(O.wrapS),R.push(O.wrapT),R.push(O.wrapR||0),R.push(O.magFilter),R.push(O.minFilter),R.push(O.anisotropy),R.push(O.internalFormat),R.push(O.format),R.push(O.type),R.push(O.generateMipmaps),R.push(O.premultiplyAlpha),R.push(O.flipY),R.push(O.unpackAlignment),R.push(O.colorSpace),R.join()}function $(O,R){const q=r.get(O);if(O.isVideoTexture&&Le(O),O.isRenderTargetTexture===!1&&O.isExternalTexture!==!0&&O.version>0&&q.__version!==O.version){const J=O.image;if(J===null)vn("WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)vn("WebGLRenderer: Texture marked for update but image is incomplete");else{ce(q,O,R);return}}else O.isExternalTexture&&(q.__webglTexture=O.sourceTexture?O.sourceTexture:null);n.bindTexture(t.TEXTURE_2D,q.__webglTexture,t.TEXTURE0+R)}function G(O,R){const q=r.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&q.__version!==O.version){ce(q,O,R);return}else O.isExternalTexture&&(q.__webglTexture=O.sourceTexture?O.sourceTexture:null);n.bindTexture(t.TEXTURE_2D_ARRAY,q.__webglTexture,t.TEXTURE0+R)}function z(O,R){const q=r.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&q.__version!==O.version){ce(q,O,R);return}n.bindTexture(t.TEXTURE_3D,q.__webglTexture,t.TEXTURE0+R)}function W(O,R){const q=r.get(O);if(O.version>0&&q.__version!==O.version){ee(q,O,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,q.__webglTexture,t.TEXTURE0+R)}const X={[_3]:t.REPEAT,[Ou]:t.CLAMP_TO_EDGE,[N3]:t.MIRRORED_REPEAT},ae={[Eo]:t.NEAREST,[lbe]:t.NEAREST_MIPMAP_NEAREST,[iS]:t.NEAREST_MIPMAP_LINEAR,[hl]:t.LINEAR,[HM]:t.LINEAR_MIPMAP_NEAREST,[tf]:t.LINEAR_MIPMAP_LINEAR},H={[hbe]:t.NEVER,[xbe]:t.ALWAYS,[mbe]:t.LESS,[HX]:t.LEQUAL,[fbe]:t.EQUAL,[bbe]:t.GEQUAL,[pbe]:t.GREATER,[gbe]:t.NOTEQUAL};function K(O,R){if(R.type===Iu&&e.has("OES_texture_float_linear")===!1&&(R.magFilter===hl||R.magFilter===HM||R.magFilter===iS||R.magFilter===tf||R.minFilter===hl||R.minFilter===HM||R.minFilter===iS||R.minFilter===tf)&&vn("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(O,t.TEXTURE_WRAP_S,X[R.wrapS]),t.texParameteri(O,t.TEXTURE_WRAP_T,X[R.wrapT]),(O===t.TEXTURE_3D||O===t.TEXTURE_2D_ARRAY)&&t.texParameteri(O,t.TEXTURE_WRAP_R,X[R.wrapR]),t.texParameteri(O,t.TEXTURE_MAG_FILTER,ae[R.magFilter]),t.texParameteri(O,t.TEXTURE_MIN_FILTER,ae[R.minFilter]),R.compareFunction&&(t.texParameteri(O,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(O,t.TEXTURE_COMPARE_FUNC,H[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(R.magFilter===Eo||R.minFilter!==iS&&R.minFilter!==tf||R.type===Iu&&e.has("OES_texture_float_linear")===!1)return;if(R.anisotropy>1||r.get(R).__currentAnisotropy){const q=e.get("EXT_texture_filter_anisotropic");t.texParameterf(O,q.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,a.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy}}}function te(O,R){let q=!1;O.__webglInit===void 0&&(O.__webglInit=!0,R.addEventListener("dispose",M));const J=R.source;let fe=f.get(J);fe===void 0&&(fe={},f.set(J,fe));const le=D(R);if(le!==O.__cacheKey){fe[le]===void 0&&(fe[le]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,q=!0),fe[le].usedTimes++;const Be=fe[O.__cacheKey];Be!==void 0&&(fe[O.__cacheKey].usedTimes--,Be.usedTimes===0&&P(R)),O.__cacheKey=le,O.__webglTexture=fe[le].texture}return q}function Z(O,R,q){return Math.floor(Math.floor(O/q)/R)}function ve(O,R,q,J){const le=O.updateRanges;if(le.length===0)n.texSubImage2D(t.TEXTURE_2D,0,0,0,R.width,R.height,q,J,R.data);else{le.sort((pe,xe)=>pe.start-xe.start);let Be=0;for(let pe=1;pe<le.length;pe++){const xe=le[Be],ke=le[pe],ge=xe.start+xe.count,we=Z(ke.start,R.width,4),qe=Z(xe.start,R.width,4);ke.start<=ge+1&&we===qe&&Z(ke.start+ke.count-1,R.width,4)===we?xe.count=Math.max(xe.count,ke.start+ke.count-xe.start):(++Be,le[Be]=ke)}le.length=Be+1;const Ie=t.getParameter(t.UNPACK_ROW_LENGTH),Ke=t.getParameter(t.UNPACK_SKIP_PIXELS),Oe=t.getParameter(t.UNPACK_SKIP_ROWS);t.pixelStorei(t.UNPACK_ROW_LENGTH,R.width);for(let pe=0,xe=le.length;pe<xe;pe++){const ke=le[pe],ge=Math.floor(ke.start/4),we=Math.ceil(ke.count/4),qe=ge%R.width,Ee=Math.floor(ge/R.width),tt=we,De=1;t.pixelStorei(t.UNPACK_SKIP_PIXELS,qe),t.pixelStorei(t.UNPACK_SKIP_ROWS,Ee),n.texSubImage2D(t.TEXTURE_2D,0,qe,Ee,tt,De,q,J,R.data)}O.clearUpdateRanges(),t.pixelStorei(t.UNPACK_ROW_LENGTH,Ie),t.pixelStorei(t.UNPACK_SKIP_PIXELS,Ke),t.pixelStorei(t.UNPACK_SKIP_ROWS,Oe)}}function ce(O,R,q){let J=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(J=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(J=t.TEXTURE_3D);const fe=te(O,R),le=R.source;n.bindTexture(J,O.__webglTexture,t.TEXTURE0+q);const Be=r.get(le);if(le.version!==Be.__version||fe===!0){n.activeTexture(t.TEXTURE0+q);const Ie=cr.getPrimaries(cr.workingColorSpace),Ke=R.colorSpace===fh?null:cr.getPrimaries(R.colorSpace),Oe=R.colorSpace===fh||Ie===Ke?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Oe);let pe=v(R.image,!1,a.maxTextureSize);pe=Ne(R,pe);const xe=s.convert(R.format,R.colorSpace),ke=s.convert(R.type);let ge=N(R.internalFormat,xe,ke,R.colorSpace,R.isVideoTexture);K(J,R);let we;const qe=R.mipmaps,Ee=R.isVideoTexture!==!0,tt=Be.__version===void 0||fe===!0,De=le.dataReady,We=A(R,pe);if(R.isDepthTexture)ge=k(R.format===_v,R.type),tt&&(Ee?n.texStorage2D(t.TEXTURE_2D,1,ge,pe.width,pe.height):n.texImage2D(t.TEXTURE_2D,0,ge,pe.width,pe.height,0,xe,ke,null));else if(R.isDataTexture)if(qe.length>0){Ee&&tt&&n.texStorage2D(t.TEXTURE_2D,We,ge,qe[0].width,qe[0].height);for(let Ae=0,Re=qe.length;Ae<Re;Ae++)we=qe[Ae],Ee?De&&n.texSubImage2D(t.TEXTURE_2D,Ae,0,0,we.width,we.height,xe,ke,we.data):n.texImage2D(t.TEXTURE_2D,Ae,ge,we.width,we.height,0,xe,ke,we.data);R.generateMipmaps=!1}else Ee?(tt&&n.texStorage2D(t.TEXTURE_2D,We,ge,pe.width,pe.height),De&&ve(R,pe,xe,ke)):n.texImage2D(t.TEXTURE_2D,0,ge,pe.width,pe.height,0,xe,ke,pe.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){Ee&&tt&&n.texStorage3D(t.TEXTURE_2D_ARRAY,We,ge,qe[0].width,qe[0].height,pe.depth);for(let Ae=0,Re=qe.length;Ae<Re;Ae++)if(we=qe[Ae],R.format!==ql)if(xe!==null)if(Ee){if(De)if(R.layerUpdates.size>0){const $e=N8(we.width,we.height,R.format,R.type);for(const ht of R.layerUpdates){const At=we.data.subarray(ht*$e/we.data.BYTES_PER_ELEMENT,(ht+1)*$e/we.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ae,0,0,ht,we.width,we.height,1,xe,At)}R.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Ae,0,0,0,we.width,we.height,pe.depth,xe,we.data)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Ae,ge,we.width,we.height,pe.depth,0,we.data,0,0);else vn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Ee?De&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,Ae,0,0,0,we.width,we.height,pe.depth,xe,ke,we.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Ae,ge,we.width,we.height,pe.depth,0,xe,ke,we.data)}else{Ee&&tt&&n.texStorage2D(t.TEXTURE_2D,We,ge,qe[0].width,qe[0].height);for(let Ae=0,Re=qe.length;Ae<Re;Ae++)we=qe[Ae],R.format!==ql?xe!==null?Ee?De&&n.compressedTexSubImage2D(t.TEXTURE_2D,Ae,0,0,we.width,we.height,xe,we.data):n.compressedTexImage2D(t.TEXTURE_2D,Ae,ge,we.width,we.height,0,we.data):vn("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Ee?De&&n.texSubImage2D(t.TEXTURE_2D,Ae,0,0,we.width,we.height,xe,ke,we.data):n.texImage2D(t.TEXTURE_2D,Ae,ge,we.width,we.height,0,xe,ke,we.data)}else if(R.isDataArrayTexture)if(Ee){if(tt&&n.texStorage3D(t.TEXTURE_2D_ARRAY,We,ge,pe.width,pe.height,pe.depth),De)if(R.layerUpdates.size>0){const Ae=N8(pe.width,pe.height,R.format,R.type);for(const Re of R.layerUpdates){const $e=pe.data.subarray(Re*Ae/pe.data.BYTES_PER_ELEMENT,(Re+1)*Ae/pe.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,Re,pe.width,pe.height,1,xe,ke,$e)}R.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,pe.width,pe.height,pe.depth,xe,ke,pe.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,ge,pe.width,pe.height,pe.depth,0,xe,ke,pe.data);else if(R.isData3DTexture)Ee?(tt&&n.texStorage3D(t.TEXTURE_3D,We,ge,pe.width,pe.height,pe.depth),De&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,pe.width,pe.height,pe.depth,xe,ke,pe.data)):n.texImage3D(t.TEXTURE_3D,0,ge,pe.width,pe.height,pe.depth,0,xe,ke,pe.data);else if(R.isFramebufferTexture){if(tt)if(Ee)n.texStorage2D(t.TEXTURE_2D,We,ge,pe.width,pe.height);else{let Ae=pe.width,Re=pe.height;for(let $e=0;$e<We;$e++)n.texImage2D(t.TEXTURE_2D,$e,ge,Ae,Re,0,xe,ke,null),Ae>>=1,Re>>=1}}else if(qe.length>0){if(Ee&&tt){const Ae=be(qe[0]);n.texStorage2D(t.TEXTURE_2D,We,ge,Ae.width,Ae.height)}for(let Ae=0,Re=qe.length;Ae<Re;Ae++)we=qe[Ae],Ee?De&&n.texSubImage2D(t.TEXTURE_2D,Ae,0,0,xe,ke,we):n.texImage2D(t.TEXTURE_2D,Ae,ge,xe,ke,we);R.generateMipmaps=!1}else if(Ee){if(tt){const Ae=be(pe);n.texStorage2D(t.TEXTURE_2D,We,ge,Ae.width,Ae.height)}De&&n.texSubImage2D(t.TEXTURE_2D,0,0,0,xe,ke,pe)}else n.texImage2D(t.TEXTURE_2D,0,ge,xe,ke,pe);g(R)&&y(J),Be.__version=le.version,R.onUpdate&&R.onUpdate(R)}O.__version=R.version}function ee(O,R,q){if(R.image.length!==6)return;const J=te(O,R),fe=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,O.__webglTexture,t.TEXTURE0+q);const le=r.get(fe);if(fe.version!==le.__version||J===!0){n.activeTexture(t.TEXTURE0+q);const Be=cr.getPrimaries(cr.workingColorSpace),Ie=R.colorSpace===fh?null:cr.getPrimaries(R.colorSpace),Ke=R.colorSpace===fh||Be===Ie?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ke);const Oe=R.isCompressedTexture||R.image[0].isCompressedTexture,pe=R.image[0]&&R.image[0].isDataTexture,xe=[];for(let Re=0;Re<6;Re++)!Oe&&!pe?xe[Re]=v(R.image[Re],!0,a.maxCubemapSize):xe[Re]=pe?R.image[Re].image:R.image[Re],xe[Re]=Ne(R,xe[Re]);const ke=xe[0],ge=s.convert(R.format,R.colorSpace),we=s.convert(R.type),qe=N(R.internalFormat,ge,we,R.colorSpace),Ee=R.isVideoTexture!==!0,tt=le.__version===void 0||J===!0,De=fe.dataReady;let We=A(R,ke);K(t.TEXTURE_CUBE_MAP,R);let Ae;if(Oe){Ee&&tt&&n.texStorage2D(t.TEXTURE_CUBE_MAP,We,qe,ke.width,ke.height);for(let Re=0;Re<6;Re++){Ae=xe[Re].mipmaps;for(let $e=0;$e<Ae.length;$e++){const ht=Ae[$e];R.format!==ql?ge!==null?Ee?De&&n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,0,0,ht.width,ht.height,ge,ht.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,qe,ht.width,ht.height,0,ht.data):vn("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Ee?De&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,0,0,ht.width,ht.height,ge,we,ht.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,qe,ht.width,ht.height,0,ge,we,ht.data)}}}else{if(Ae=R.mipmaps,Ee&&tt){Ae.length>0&&We++;const Re=be(xe[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,We,qe,Re.width,Re.height)}for(let Re=0;Re<6;Re++)if(pe){Ee?De&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,0,0,xe[Re].width,xe[Re].height,ge,we,xe[Re].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,qe,xe[Re].width,xe[Re].height,0,ge,we,xe[Re].data);for(let $e=0;$e<Ae.length;$e++){const At=Ae[$e].image[Re].image;Ee?De&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,0,0,At.width,At.height,ge,we,At.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,qe,At.width,At.height,0,ge,we,At.data)}}else{Ee?De&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,0,0,ge,we,xe[Re]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,qe,ge,we,xe[Re]);for(let $e=0;$e<Ae.length;$e++){const ht=Ae[$e];Ee?De&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,0,0,ge,we,ht.image[Re]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,qe,ge,we,ht.image[Re])}}}g(R)&&y(t.TEXTURE_CUBE_MAP),le.__version=fe.version,R.onUpdate&&R.onUpdate(R)}O.__version=R.version}function je(O,R,q,J,fe,le){const Be=s.convert(q.format,q.colorSpace),Ie=s.convert(q.type),Ke=N(q.internalFormat,Be,Ie,q.colorSpace),Oe=r.get(R),pe=r.get(q);if(pe.__renderTarget=R,!Oe.__hasExternalTextures){const xe=Math.max(1,R.width>>le),ke=Math.max(1,R.height>>le);fe===t.TEXTURE_3D||fe===t.TEXTURE_2D_ARRAY?n.texImage3D(fe,le,Ke,xe,ke,R.depth,0,Be,Ie,null):n.texImage2D(fe,le,Ke,xe,ke,0,Be,Ie,null)}n.bindFramebuffer(t.FRAMEBUFFER,O),de(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,J,fe,pe.__webglTexture,0,se(R)):(fe===t.TEXTURE_2D||fe>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&fe<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,J,fe,pe.__webglTexture,le),n.bindFramebuffer(t.FRAMEBUFFER,null)}function he(O,R,q){if(t.bindRenderbuffer(t.RENDERBUFFER,O),R.depthBuffer){const J=R.depthTexture,fe=J&&J.isDepthTexture?J.type:null,le=k(R.stencilBuffer,fe),Be=R.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Ie=se(R);de(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Ie,le,R.width,R.height):q?t.renderbufferStorageMultisample(t.RENDERBUFFER,Ie,le,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,le,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,Be,t.RENDERBUFFER,O)}else{const J=R.textures;for(let fe=0;fe<J.length;fe++){const le=J[fe],Be=s.convert(le.format,le.colorSpace),Ie=s.convert(le.type),Ke=N(le.internalFormat,Be,Ie,le.colorSpace),Oe=se(R);q&&de(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Oe,Ke,R.width,R.height):de(R)?l.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Oe,Ke,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Ke,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function oe(O,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,O),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const J=r.get(R.depthTexture);J.__renderTarget=R,(!J.__webglTexture||R.depthTexture.image.width!==R.width||R.depthTexture.image.height!==R.height)&&(R.depthTexture.image.width=R.width,R.depthTexture.image.height=R.height,R.depthTexture.needsUpdate=!0),$(R.depthTexture,0);const fe=J.__webglTexture,le=se(R);if(R.depthTexture.format===Sv)de(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,fe,0,le):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,fe,0);else if(R.depthTexture.format===_v)de(R)?l.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,fe,0,le):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,fe,0);else throw new Error("Unknown depthTexture format")}function _e(O){const R=r.get(O),q=O.isWebGLCubeRenderTarget===!0;if(R.__boundDepthTexture!==O.depthTexture){const J=O.depthTexture;if(R.__depthDisposeCallback&&R.__depthDisposeCallback(),J){const fe=()=>{delete R.__boundDepthTexture,delete R.__depthDisposeCallback,J.removeEventListener("dispose",fe)};J.addEventListener("dispose",fe),R.__depthDisposeCallback=fe}R.__boundDepthTexture=J}if(O.depthTexture&&!R.__autoAllocateDepthBuffer){if(q)throw new Error("target.depthTexture not supported in Cube render targets");const J=O.texture.mipmaps;J&&J.length>0?oe(R.__webglFramebuffer[0],O):oe(R.__webglFramebuffer,O)}else if(q){R.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[J]),R.__webglDepthbuffer[J]===void 0)R.__webglDepthbuffer[J]=t.createRenderbuffer(),he(R.__webglDepthbuffer[J],O,!1);else{const fe=O.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,le=R.__webglDepthbuffer[J];t.bindRenderbuffer(t.RENDERBUFFER,le),t.framebufferRenderbuffer(t.FRAMEBUFFER,fe,t.RENDERBUFFER,le)}}else{const J=O.texture.mipmaps;if(J&&J.length>0?n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[0]):n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer===void 0)R.__webglDepthbuffer=t.createRenderbuffer(),he(R.__webglDepthbuffer,O,!1);else{const fe=O.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,le=R.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,le),t.framebufferRenderbuffer(t.FRAMEBUFFER,fe,t.RENDERBUFFER,le)}}n.bindFramebuffer(t.FRAMEBUFFER,null)}function ie(O,R,q){const J=r.get(O);R!==void 0&&je(J.__webglFramebuffer,O,O.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),q!==void 0&&_e(O)}function ze(O){const R=O.texture,q=r.get(O),J=r.get(R);O.addEventListener("dispose",C);const fe=O.textures,le=O.isWebGLCubeRenderTarget===!0,Be=fe.length>1;if(Be||(J.__webglTexture===void 0&&(J.__webglTexture=t.createTexture()),J.__version=R.version,o.memory.textures++),le){q.__webglFramebuffer=[];for(let Ie=0;Ie<6;Ie++)if(R.mipmaps&&R.mipmaps.length>0){q.__webglFramebuffer[Ie]=[];for(let Ke=0;Ke<R.mipmaps.length;Ke++)q.__webglFramebuffer[Ie][Ke]=t.createFramebuffer()}else q.__webglFramebuffer[Ie]=t.createFramebuffer()}else{if(R.mipmaps&&R.mipmaps.length>0){q.__webglFramebuffer=[];for(let Ie=0;Ie<R.mipmaps.length;Ie++)q.__webglFramebuffer[Ie]=t.createFramebuffer()}else q.__webglFramebuffer=t.createFramebuffer();if(Be)for(let Ie=0,Ke=fe.length;Ie<Ke;Ie++){const Oe=r.get(fe[Ie]);Oe.__webglTexture===void 0&&(Oe.__webglTexture=t.createTexture(),o.memory.textures++)}if(O.samples>0&&de(O)===!1){q.__webglMultisampledFramebuffer=t.createFramebuffer(),q.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,q.__webglMultisampledFramebuffer);for(let Ie=0;Ie<fe.length;Ie++){const Ke=fe[Ie];q.__webglColorRenderbuffer[Ie]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,q.__webglColorRenderbuffer[Ie]);const Oe=s.convert(Ke.format,Ke.colorSpace),pe=s.convert(Ke.type),xe=N(Ke.internalFormat,Oe,pe,Ke.colorSpace,O.isXRRenderTarget===!0),ke=se(O);t.renderbufferStorageMultisample(t.RENDERBUFFER,ke,xe,O.width,O.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Ie,t.RENDERBUFFER,q.__webglColorRenderbuffer[Ie])}t.bindRenderbuffer(t.RENDERBUFFER,null),O.depthBuffer&&(q.__webglDepthRenderbuffer=t.createRenderbuffer(),he(q.__webglDepthRenderbuffer,O,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(le){n.bindTexture(t.TEXTURE_CUBE_MAP,J.__webglTexture),K(t.TEXTURE_CUBE_MAP,R);for(let Ie=0;Ie<6;Ie++)if(R.mipmaps&&R.mipmaps.length>0)for(let Ke=0;Ke<R.mipmaps.length;Ke++)je(q.__webglFramebuffer[Ie][Ke],O,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,Ke);else je(q.__webglFramebuffer[Ie],O,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0);g(R)&&y(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(Be){for(let Ie=0,Ke=fe.length;Ie<Ke;Ie++){const Oe=fe[Ie],pe=r.get(Oe);let xe=t.TEXTURE_2D;(O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(xe=O.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(xe,pe.__webglTexture),K(xe,Oe),je(q.__webglFramebuffer,O,Oe,t.COLOR_ATTACHMENT0+Ie,xe,0),g(Oe)&&y(xe)}n.unbindTexture()}else{let Ie=t.TEXTURE_2D;if((O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(Ie=O.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY),n.bindTexture(Ie,J.__webglTexture),K(Ie,R),R.mipmaps&&R.mipmaps.length>0)for(let Ke=0;Ke<R.mipmaps.length;Ke++)je(q.__webglFramebuffer[Ke],O,R,t.COLOR_ATTACHMENT0,Ie,Ke);else je(q.__webglFramebuffer,O,R,t.COLOR_ATTACHMENT0,Ie,0);g(R)&&y(Ie),n.unbindTexture()}O.depthBuffer&&_e(O)}function V(O){const R=O.textures;for(let q=0,J=R.length;q<J;q++){const fe=R[q];if(g(fe)){const le=_(O),Be=r.get(fe).__webglTexture;n.bindTexture(le,Be),y(le),n.unbindTexture()}}}const Y=[],me=[];function Q(O){if(O.samples>0){if(de(O)===!1){const R=O.textures,q=O.width,J=O.height;let fe=t.COLOR_BUFFER_BIT;const le=O.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Be=r.get(O),Ie=R.length>1;if(Ie)for(let Oe=0;Oe<R.length;Oe++)n.bindFramebuffer(t.FRAMEBUFFER,Be.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,Be.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,Be.__webglMultisampledFramebuffer);const Ke=O.texture.mipmaps;Ke&&Ke.length>0?n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Be.__webglFramebuffer[0]):n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Be.__webglFramebuffer);for(let Oe=0;Oe<R.length;Oe++){if(O.resolveDepthBuffer&&(O.depthBuffer&&(fe|=t.DEPTH_BUFFER_BIT),O.stencilBuffer&&O.resolveStencilBuffer&&(fe|=t.STENCIL_BUFFER_BIT)),Ie){t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,Be.__webglColorRenderbuffer[Oe]);const pe=r.get(R[Oe]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,pe,0)}t.blitFramebuffer(0,0,q,J,0,0,q,J,fe,t.NEAREST),c===!0&&(Y.length=0,me.length=0,Y.push(t.COLOR_ATTACHMENT0+Oe),O.depthBuffer&&O.resolveDepthBuffer===!1&&(Y.push(le),me.push(le),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,me)),t.invalidateFramebuffer(t.READ_FRAMEBUFFER,Y))}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),Ie)for(let Oe=0;Oe<R.length;Oe++){n.bindFramebuffer(t.FRAMEBUFFER,Be.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.RENDERBUFFER,Be.__webglColorRenderbuffer[Oe]);const pe=r.get(R[Oe]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,Be.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.TEXTURE_2D,pe,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Be.__webglMultisampledFramebuffer)}else if(O.depthBuffer&&O.resolveDepthBuffer===!1&&c){const R=O.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[R])}}}function se(O){return Math.min(a.maxSamples,O.samples)}function de(O){const R=r.get(O);return O.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function Le(O){const R=o.render.frame;d.get(O)!==R&&(d.set(O,R),O.update())}function Ne(O,R){const q=O.colorSpace,J=O.format,fe=O.type;return O.isCompressedTexture===!0||O.isVideoTexture===!0||q!==bb&&q!==fh&&(cr.getTransfer(q)===Dr?(J!==ql||fe!==Lc)&&vn("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ua("WebGLTextures: Unsupported texture color space:",q)),R}function be(O){return typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement?(u.width=O.naturalWidth||O.width,u.height=O.naturalHeight||O.height):typeof VideoFrame<"u"&&O instanceof VideoFrame?(u.width=O.displayWidth,u.height=O.displayHeight):(u.width=O.width,u.height=O.height),u}this.allocateTextureUnit=B,this.resetTextureUnits=L,this.setTexture2D=$,this.setTexture2DArray=G,this.setTexture3D=z,this.setTextureCube=W,this.rebindTextures=ie,this.setupRenderTarget=ze,this.updateRenderTargetMipmap=V,this.updateMultisampleRenderTarget=Q,this.setupDepthRenderbuffer=_e,this.setupFrameBufferTexture=je,this.useMultisampledRTT=de}function Hwe(t,e){function n(r,a=fh){let s;const o=cr.getTransfer(a);if(r===Lc)return t.UNSIGNED_BYTE;if(r===OF)return t.UNSIGNED_SHORT_4_4_4_4;if(r===IF)return t.UNSIGNED_SHORT_5_5_5_1;if(r===LX)return t.UNSIGNED_INT_5_9_9_9_REV;if(r===OX)return t.UNSIGNED_INT_10F_11F_11F_REV;if(r===RX)return t.BYTE;if(r===FX)return t.SHORT;if(r===vv)return t.UNSIGNED_SHORT;if(r===LF)return t.INT;if(r===Ff)return t.UNSIGNED_INT;if(r===Iu)return t.FLOAT;if(r===Gb)return t.HALF_FLOAT;if(r===IX)return t.ALPHA;if(r===zX)return t.RGB;if(r===ql)return t.RGBA;if(r===Sv)return t.DEPTH_COMPONENT;if(r===_v)return t.DEPTH_STENCIL;if(r===UX)return t.RED;if(r===zF)return t.RED_INTEGER;if(r===UF)return t.RG;if(r===BF)return t.RG_INTEGER;if(r===HF)return t.RGBA_INTEGER;if(r===V_||r===q_||r===G_||r===W_)if(o===Dr)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(r===V_)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(r===q_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(r===G_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(r===W_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(r===V_)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(r===q_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(r===G_)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(r===W_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(r===C3||r===k3||r===A3||r===T3)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(r===C3)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(r===k3)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(r===A3)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(r===T3)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(r===M3||r===P3||r===E3)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(r===M3||r===P3)return o===Dr?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(r===E3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(r===j3||r===D3||r===R3||r===F3||r===L3||r===O3||r===I3||r===z3||r===U3||r===B3||r===H3||r===$3||r===V3||r===q3)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(r===j3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(r===D3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(r===R3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(r===F3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(r===L3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(r===O3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(r===I3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(r===z3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(r===U3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(r===B3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(r===H3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(r===$3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(r===V3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(r===q3)return o===Dr?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(r===G3||r===W3||r===K3)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(r===G3)return o===Dr?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(r===W3)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(r===K3)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(r===X3||r===Y3||r===Q3||r===Z3)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(r===X3)return s.COMPRESSED_RED_RGTC1_EXT;if(r===Y3)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(r===Q3)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(r===Z3)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return r===wv?t.UNSIGNED_INT_24_8:t[r]!==void 0?t[r]:null}return{convert:n}}const $we=`
  3825. void main() {
  3826. gl_Position = vec4( position, 1.0 );
  3827. }`,Vwe=`
  3828. uniform sampler2DArray depthColor;
  3829. uniform float depthWidth;
  3830. uniform float depthHeight;
  3831. void main() {
  3832. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  3833. if ( coord.x >= 1.0 ) {
  3834. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  3835. } else {
  3836. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  3837. }
  3838. }`;class qwe{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,n){if(this.texture===null){const r=new oY(e.texture);(e.depthNear!==n.depthNear||e.depthFar!==n.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=r}}getMesh(e){if(this.texture!==null&&this.mesh===null){const n=e.cameras[0].viewport,r=new ad({vertexShader:$we,fragmentShader:Vwe,uniforms:{depthColor:{value:this.texture},depthWidth:{value:n.z},depthHeight:{value:n.w}}});this.mesh=new Sl(new KF(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}let Gwe=class extends np{constructor(e,n){super();const r=this;let a=null,s=1,o=null,l="local-floor",c=1,u=null,d=null,h=null,f=null,p=null,x=null;const v=typeof XRWebGLBinding<"u",g=new qwe,y={},_=n.getContextAttributes();let N=null,k=null;const A=[],M=[],C=new Un;let j=null;const P=new sl;P.viewport=new Za;const E=new sl;E.viewport=new Za;const U=[P,E],L=new cxe;let B=null,D=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ce){let ee=A[ce];return ee===void 0&&(ee=new uP,A[ce]=ee),ee.getTargetRaySpace()},this.getControllerGrip=function(ce){let ee=A[ce];return ee===void 0&&(ee=new uP,A[ce]=ee),ee.getGripSpace()},this.getHand=function(ce){let ee=A[ce];return ee===void 0&&(ee=new uP,A[ce]=ee),ee.getHandSpace()};function $(ce){const ee=M.indexOf(ce.inputSource);if(ee===-1)return;const je=A[ee];je!==void 0&&(je.update(ce.inputSource,ce.frame,u||o),je.dispatchEvent({type:ce.type,data:ce.inputSource}))}function G(){a.removeEventListener("select",$),a.removeEventListener("selectstart",$),a.removeEventListener("selectend",$),a.removeEventListener("squeeze",$),a.removeEventListener("squeezestart",$),a.removeEventListener("squeezeend",$),a.removeEventListener("end",G),a.removeEventListener("inputsourceschange",z);for(let ce=0;ce<A.length;ce++){const ee=M[ce];ee!==null&&(M[ce]=null,A[ce].disconnect(ee))}B=null,D=null,g.reset();for(const ce in y)delete y[ce];e.setRenderTarget(N),p=null,f=null,h=null,a=null,k=null,ve.stop(),r.isPresenting=!1,e.setPixelRatio(j),e.setSize(C.width,C.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(ce){s=ce,r.isPresenting===!0&&vn("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ce){l=ce,r.isPresenting===!0&&vn("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return u||o},this.setReferenceSpace=function(ce){u=ce},this.getBaseLayer=function(){return f!==null?f:p},this.getBinding=function(){return h===null&&v&&(h=new XRWebGLBinding(a,n)),h},this.getFrame=function(){return x},this.getSession=function(){return a},this.setSession=async function(ce){if(a=ce,a!==null){if(N=e.getRenderTarget(),a.addEventListener("select",$),a.addEventListener("selectstart",$),a.addEventListener("selectend",$),a.addEventListener("squeeze",$),a.addEventListener("squeezestart",$),a.addEventListener("squeezeend",$),a.addEventListener("end",G),a.addEventListener("inputsourceschange",z),_.xrCompatible!==!0&&await n.makeXRCompatible(),j=e.getPixelRatio(),e.getSize(C),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let je=null,he=null,oe=null;_.depth&&(oe=_.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,je=_.stencil?_v:Sv,he=_.stencil?wv:Ff);const _e={colorFormat:n.RGBA8,depthFormat:oe,scaleFactor:s};h=this.getBinding(),f=h.createProjectionLayer(_e),a.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),k=new Of(f.textureWidth,f.textureHeight,{format:ql,type:Lc,depthTexture:new sY(f.textureWidth,f.textureHeight,he,void 0,void 0,void 0,void 0,void 0,void 0,je),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}else{const je={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(a,n,je),a.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),k=new Of(p.framebufferWidth,p.framebufferHeight,{format:ql,type:Lc,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}k.isXRRenderTarget=!0,this.setFoveation(c),u=null,o=await a.requestReferenceSpace(l),ve.setContext(a),ve.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function z(ce){for(let ee=0;ee<ce.removed.length;ee++){const je=ce.removed[ee],he=M.indexOf(je);he>=0&&(M[he]=null,A[he].disconnect(je))}for(let ee=0;ee<ce.added.length;ee++){const je=ce.added[ee];let he=M.indexOf(je);if(he===-1){for(let _e=0;_e<A.length;_e++)if(_e>=M.length){M.push(je),he=_e;break}else if(M[_e]===null){M[_e]=je,he=_e;break}if(he===-1)break}const oe=A[he];oe&&oe.connect(je)}}const W=new ft,X=new ft;function ae(ce,ee,je){W.setFromMatrixPosition(ee.matrixWorld),X.setFromMatrixPosition(je.matrixWorld);const he=W.distanceTo(X),oe=ee.projectionMatrix.elements,_e=je.projectionMatrix.elements,ie=oe[14]/(oe[10]-1),ze=oe[14]/(oe[10]+1),V=(oe[9]+1)/oe[5],Y=(oe[9]-1)/oe[5],me=(oe[8]-1)/oe[0],Q=(_e[8]+1)/_e[0],se=ie*me,de=ie*Q,Le=he/(-me+Q),Ne=Le*-me;if(ee.matrixWorld.decompose(ce.position,ce.quaternion,ce.scale),ce.translateX(Ne),ce.translateZ(Le),ce.matrixWorld.compose(ce.position,ce.quaternion,ce.scale),ce.matrixWorldInverse.copy(ce.matrixWorld).invert(),oe[10]===-1)ce.projectionMatrix.copy(ee.projectionMatrix),ce.projectionMatrixInverse.copy(ee.projectionMatrixInverse);else{const be=ie+Le,O=ze+Le,R=se-Ne,q=de+(he-Ne),J=V*ze/O*be,fe=Y*ze/O*be;ce.projectionMatrix.makePerspective(R,q,J,fe,be,O),ce.projectionMatrixInverse.copy(ce.projectionMatrix).invert()}}function H(ce,ee){ee===null?ce.matrixWorld.copy(ce.matrix):ce.matrixWorld.multiplyMatrices(ee.matrixWorld,ce.matrix),ce.matrixWorldInverse.copy(ce.matrixWorld).invert()}this.updateCamera=function(ce){if(a===null)return;let ee=ce.near,je=ce.far;g.texture!==null&&(g.depthNear>0&&(ee=g.depthNear),g.depthFar>0&&(je=g.depthFar)),L.near=E.near=P.near=ee,L.far=E.far=P.far=je,(B!==L.near||D!==L.far)&&(a.updateRenderState({depthNear:L.near,depthFar:L.far}),B=L.near,D=L.far),L.layers.mask=ce.layers.mask|6,P.layers.mask=L.layers.mask&3,E.layers.mask=L.layers.mask&5;const he=ce.parent,oe=L.cameras;H(L,he);for(let _e=0;_e<oe.length;_e++)H(oe[_e],he);oe.length===2?ae(L,P,E):L.projectionMatrix.copy(P.projectionMatrix),K(ce,L,he)};function K(ce,ee,je){je===null?ce.matrix.copy(ee.matrixWorld):(ce.matrix.copy(je.matrixWorld),ce.matrix.invert(),ce.matrix.multiply(ee.matrixWorld)),ce.matrix.decompose(ce.position,ce.quaternion,ce.scale),ce.updateMatrixWorld(!0),ce.projectionMatrix.copy(ee.projectionMatrix),ce.projectionMatrixInverse.copy(ee.projectionMatrixInverse),ce.isPerspectiveCamera&&(ce.fov=J3*2*Math.atan(1/ce.projectionMatrix.elements[5]),ce.zoom=1)}this.getCamera=function(){return L},this.getFoveation=function(){if(!(f===null&&p===null))return c},this.setFoveation=function(ce){c=ce,f!==null&&(f.fixedFoveation=ce),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=ce)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(L)},this.getCameraTexture=function(ce){return y[ce]};let te=null;function Z(ce,ee){if(d=ee.getViewerPose(u||o),x=ee,d!==null){const je=d.views;p!==null&&(e.setRenderTargetFramebuffer(k,p.framebuffer),e.setRenderTarget(k));let he=!1;je.length!==L.cameras.length&&(L.cameras.length=0,he=!0);for(let ze=0;ze<je.length;ze++){const V=je[ze];let Y=null;if(p!==null)Y=p.getViewport(V);else{const Q=h.getViewSubImage(f,V);Y=Q.viewport,ze===0&&(e.setRenderTargetTextures(k,Q.colorTexture,Q.depthStencilTexture),e.setRenderTarget(k))}let me=U[ze];me===void 0&&(me=new sl,me.layers.enable(ze),me.viewport=new Za,U[ze]=me),me.matrix.fromArray(V.transform.matrix),me.matrix.decompose(me.position,me.quaternion,me.scale),me.projectionMatrix.fromArray(V.projectionMatrix),me.projectionMatrixInverse.copy(me.projectionMatrix).invert(),me.viewport.set(Y.x,Y.y,Y.width,Y.height),ze===0&&(L.matrix.copy(me.matrix),L.matrix.decompose(L.position,L.quaternion,L.scale)),he===!0&&L.cameras.push(me)}const oe=a.enabledFeatures;if(oe&&oe.includes("depth-sensing")&&a.depthUsage=="gpu-optimized"&&v){h=r.getBinding();const ze=h.getDepthInformation(je[0]);ze&&ze.isValid&&ze.texture&&g.init(ze,a.renderState)}if(oe&&oe.includes("camera-access")&&v){e.state.unbindTexture(),h=r.getBinding();for(let ze=0;ze<je.length;ze++){const V=je[ze].camera;if(V){let Y=y[V];Y||(Y=new oY,y[V]=Y);const me=h.getCameraImage(V);Y.sourceTexture=me}}}}for(let je=0;je<A.length;je++){const he=M[je],oe=A[je];he!==null&&oe!==void 0&&oe.update(he,ee,u||o)}te&&te(ce,ee),ee.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:ee}),x=null}const ve=new hY;ve.setAnimationLoop(Z),this.setAnimationLoop=function(ce){te=ce},this.dispose=function(){}}};const Em=new Gh,Wwe=new ri;function Kwe(t,e){function n(g,y){g.matrixAutoUpdate===!0&&g.updateMatrix(),y.value.copy(g.matrix)}function r(g,y){y.color.getRGB(g.fogColor.value,nY(t)),y.isFog?(g.fogNear.value=y.near,g.fogFar.value=y.far):y.isFogExp2&&(g.fogDensity.value=y.density)}function a(g,y,_,N,k){y.isMeshBasicMaterial||y.isMeshLambertMaterial?s(g,y):y.isMeshToonMaterial?(s(g,y),h(g,y)):y.isMeshPhongMaterial?(s(g,y),d(g,y)):y.isMeshStandardMaterial?(s(g,y),f(g,y),y.isMeshPhysicalMaterial&&p(g,y,k)):y.isMeshMatcapMaterial?(s(g,y),x(g,y)):y.isMeshDepthMaterial?s(g,y):y.isMeshDistanceMaterial?(s(g,y),v(g,y)):y.isMeshNormalMaterial?s(g,y):y.isLineBasicMaterial?(o(g,y),y.isLineDashedMaterial&&l(g,y)):y.isPointsMaterial?c(g,y,_,N):y.isSpriteMaterial?u(g,y):y.isShadowMaterial?(g.color.value.copy(y.color),g.opacity.value=y.opacity):y.isShaderMaterial&&(y.uniformsNeedUpdate=!1)}function s(g,y){g.opacity.value=y.opacity,y.color&&g.diffuse.value.copy(y.color),y.emissive&&g.emissive.value.copy(y.emissive).multiplyScalar(y.emissiveIntensity),y.map&&(g.map.value=y.map,n(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.bumpMap&&(g.bumpMap.value=y.bumpMap,n(y.bumpMap,g.bumpMapTransform),g.bumpScale.value=y.bumpScale,y.side===to&&(g.bumpScale.value*=-1)),y.normalMap&&(g.normalMap.value=y.normalMap,n(y.normalMap,g.normalMapTransform),g.normalScale.value.copy(y.normalScale),y.side===to&&g.normalScale.value.negate()),y.displacementMap&&(g.displacementMap.value=y.displacementMap,n(y.displacementMap,g.displacementMapTransform),g.displacementScale.value=y.displacementScale,g.displacementBias.value=y.displacementBias),y.emissiveMap&&(g.emissiveMap.value=y.emissiveMap,n(y.emissiveMap,g.emissiveMapTransform)),y.specularMap&&(g.specularMap.value=y.specularMap,n(y.specularMap,g.specularMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest);const _=e.get(y),N=_.envMap,k=_.envMapRotation;N&&(g.envMap.value=N,Em.copy(k),Em.x*=-1,Em.y*=-1,Em.z*=-1,N.isCubeTexture&&N.isRenderTargetTexture===!1&&(Em.y*=-1,Em.z*=-1),g.envMapRotation.value.setFromMatrix4(Wwe.makeRotationFromEuler(Em)),g.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=y.reflectivity,g.ior.value=y.ior,g.refractionRatio.value=y.refractionRatio),y.lightMap&&(g.lightMap.value=y.lightMap,g.lightMapIntensity.value=y.lightMapIntensity,n(y.lightMap,g.lightMapTransform)),y.aoMap&&(g.aoMap.value=y.aoMap,g.aoMapIntensity.value=y.aoMapIntensity,n(y.aoMap,g.aoMapTransform))}function o(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,y.map&&(g.map.value=y.map,n(y.map,g.mapTransform))}function l(g,y){g.dashSize.value=y.dashSize,g.totalSize.value=y.dashSize+y.gapSize,g.scale.value=y.scale}function c(g,y,_,N){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.size.value=y.size*_,g.scale.value=N*.5,y.map&&(g.map.value=y.map,n(y.map,g.uvTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function u(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.rotation.value=y.rotation,y.map&&(g.map.value=y.map,n(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function d(g,y){g.specular.value.copy(y.specular),g.shininess.value=Math.max(y.shininess,1e-4)}function h(g,y){y.gradientMap&&(g.gradientMap.value=y.gradientMap)}function f(g,y){g.metalness.value=y.metalness,y.metalnessMap&&(g.metalnessMap.value=y.metalnessMap,n(y.metalnessMap,g.metalnessMapTransform)),g.roughness.value=y.roughness,y.roughnessMap&&(g.roughnessMap.value=y.roughnessMap,n(y.roughnessMap,g.roughnessMapTransform)),y.envMap&&(g.envMapIntensity.value=y.envMapIntensity)}function p(g,y,_){g.ior.value=y.ior,y.sheen>0&&(g.sheenColor.value.copy(y.sheenColor).multiplyScalar(y.sheen),g.sheenRoughness.value=y.sheenRoughness,y.sheenColorMap&&(g.sheenColorMap.value=y.sheenColorMap,n(y.sheenColorMap,g.sheenColorMapTransform)),y.sheenRoughnessMap&&(g.sheenRoughnessMap.value=y.sheenRoughnessMap,n(y.sheenRoughnessMap,g.sheenRoughnessMapTransform))),y.clearcoat>0&&(g.clearcoat.value=y.clearcoat,g.clearcoatRoughness.value=y.clearcoatRoughness,y.clearcoatMap&&(g.clearcoatMap.value=y.clearcoatMap,n(y.clearcoatMap,g.clearcoatMapTransform)),y.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=y.clearcoatRoughnessMap,n(y.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),y.clearcoatNormalMap&&(g.clearcoatNormalMap.value=y.clearcoatNormalMap,n(y.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(y.clearcoatNormalScale),y.side===to&&g.clearcoatNormalScale.value.negate())),y.dispersion>0&&(g.dispersion.value=y.dispersion),y.iridescence>0&&(g.iridescence.value=y.iridescence,g.iridescenceIOR.value=y.iridescenceIOR,g.iridescenceThicknessMinimum.value=y.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=y.iridescenceThicknessRange[1],y.iridescenceMap&&(g.iridescenceMap.value=y.iridescenceMap,n(y.iridescenceMap,g.iridescenceMapTransform)),y.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=y.iridescenceThicknessMap,n(y.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),y.transmission>0&&(g.transmission.value=y.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),y.transmissionMap&&(g.transmissionMap.value=y.transmissionMap,n(y.transmissionMap,g.transmissionMapTransform)),g.thickness.value=y.thickness,y.thicknessMap&&(g.thicknessMap.value=y.thicknessMap,n(y.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=y.attenuationDistance,g.attenuationColor.value.copy(y.attenuationColor)),y.anisotropy>0&&(g.anisotropyVector.value.set(y.anisotropy*Math.cos(y.anisotropyRotation),y.anisotropy*Math.sin(y.anisotropyRotation)),y.anisotropyMap&&(g.anisotropyMap.value=y.anisotropyMap,n(y.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=y.specularIntensity,g.specularColor.value.copy(y.specularColor),y.specularColorMap&&(g.specularColorMap.value=y.specularColorMap,n(y.specularColorMap,g.specularColorMapTransform)),y.specularIntensityMap&&(g.specularIntensityMap.value=y.specularIntensityMap,n(y.specularIntensityMap,g.specularIntensityMapTransform))}function x(g,y){y.matcap&&(g.matcap.value=y.matcap)}function v(g,y){const _=e.get(y).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:a}}function Xwe(t,e,n,r){let a={},s={},o=[];const l=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function c(_,N){const k=N.program;r.uniformBlockBinding(_,k)}function u(_,N){let k=a[_.id];k===void 0&&(x(_),k=d(_),a[_.id]=k,_.addEventListener("dispose",g));const A=N.program;r.updateUBOMapping(_,A);const M=e.render.frame;s[_.id]!==M&&(f(_),s[_.id]=M)}function d(_){const N=h();_.__bindingPointIndex=N;const k=t.createBuffer(),A=_.__size,M=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,k),t.bufferData(t.UNIFORM_BUFFER,A,M),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,N,k),k}function h(){for(let _=0;_<l;_++)if(o.indexOf(_)===-1)return o.push(_),_;return Ua("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(_){const N=a[_.id],k=_.uniforms,A=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,N);for(let M=0,C=k.length;M<C;M++){const j=Array.isArray(k[M])?k[M]:[k[M]];for(let P=0,E=j.length;P<E;P++){const U=j[P];if(p(U,M,P,A)===!0){const L=U.__offset,B=Array.isArray(U.value)?U.value:[U.value];let D=0;for(let $=0;$<B.length;$++){const G=B[$],z=v(G);typeof G=="number"||typeof G=="boolean"?(U.__data[0]=G,t.bufferSubData(t.UNIFORM_BUFFER,L+D,U.__data)):G.isMatrix3?(U.__data[0]=G.elements[0],U.__data[1]=G.elements[1],U.__data[2]=G.elements[2],U.__data[3]=0,U.__data[4]=G.elements[3],U.__data[5]=G.elements[4],U.__data[6]=G.elements[5],U.__data[7]=0,U.__data[8]=G.elements[6],U.__data[9]=G.elements[7],U.__data[10]=G.elements[8],U.__data[11]=0):(G.toArray(U.__data,D),D+=z.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,L,U.__data)}}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function p(_,N,k,A){const M=_.value,C=N+"_"+k;if(A[C]===void 0)return typeof M=="number"||typeof M=="boolean"?A[C]=M:A[C]=M.clone(),!0;{const j=A[C];if(typeof M=="number"||typeof M=="boolean"){if(j!==M)return A[C]=M,!0}else if(j.equals(M)===!1)return j.copy(M),!0}return!1}function x(_){const N=_.uniforms;let k=0;const A=16;for(let C=0,j=N.length;C<j;C++){const P=Array.isArray(N[C])?N[C]:[N[C]];for(let E=0,U=P.length;E<U;E++){const L=P[E],B=Array.isArray(L.value)?L.value:[L.value];for(let D=0,$=B.length;D<$;D++){const G=B[D],z=v(G),W=k%A,X=W%z.boundary,ae=W+X;k+=X,ae!==0&&A-ae<z.storage&&(k+=A-ae),L.__data=new Float32Array(z.storage/Float32Array.BYTES_PER_ELEMENT),L.__offset=k,k+=z.storage}}}const M=k%A;return M>0&&(k+=A-M),_.__size=k,_.__cache={},this}function v(_){const N={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(N.boundary=4,N.storage=4):_.isVector2?(N.boundary=8,N.storage=8):_.isVector3||_.isColor?(N.boundary=16,N.storage=12):_.isVector4?(N.boundary=16,N.storage=16):_.isMatrix3?(N.boundary=48,N.storage=48):_.isMatrix4?(N.boundary=64,N.storage=64):_.isTexture?vn("WebGLRenderer: Texture samplers can not be part of an uniforms group."):vn("WebGLRenderer: Unsupported uniform value type.",_),N}function g(_){const N=_.target;N.removeEventListener("dispose",g);const k=o.indexOf(N.__bindingPointIndex);o.splice(k,1),t.deleteBuffer(a[N.id]),delete a[N.id],delete s[N.id]}function y(){for(const _ in a)t.deleteBuffer(a[_]);o=[],a={},s={}}return{bind:c,update:u,dispose:y}}const Ywe=new Uint16Array([11481,15204,11534,15171,11808,15015,12385,14843,12894,14716,13396,14600,13693,14483,13976,14366,14237,14171,14405,13961,14511,13770,14605,13598,14687,13444,14760,13305,14822,13066,14876,12857,14923,12675,14963,12517,14997,12379,15025,12230,15049,12023,15070,11843,15086,11687,15100,11551,15111,11433,15120,11330,15127,11217,15132,11060,15135,10922,15138,10801,15139,10695,15139,10600,13012,14923,13020,14917,13064,14886,13176,14800,13349,14666,13513,14526,13724,14398,13960,14230,14200,14020,14383,13827,14488,13651,14583,13491,14667,13348,14740,13132,14803,12908,14856,12713,14901,12542,14938,12394,14968,12241,14992,12017,15010,11822,15024,11654,15034,11507,15041,11380,15044,11269,15044,11081,15042,10913,15037,10764,15031,10635,15023,10520,15014,10419,15003,10330,13657,14676,13658,14673,13670,14660,13698,14622,13750,14547,13834,14442,13956,14317,14112,14093,14291,13889,14407,13704,14499,13538,14586,13389,14664,13201,14733,12966,14792,12758,14842,12577,14882,12418,14915,12272,14940,12033,14959,11826,14972,11646,14980,11490,14983,11355,14983,11212,14979,11008,14971,10830,14961,10675,14950,10540,14936,10420,14923,10315,14909,10204,14894,10041,14089,14460,14090,14459,14096,14452,14112,14431,14141,14388,14186,14305,14252,14130,14341,13941,14399,13756,14467,13585,14539,13430,14610,13272,14677,13026,14737,12808,14790,12617,14833,12449,14869,12303,14896,12065,14916,11845,14929,11655,14937,11490,14939,11347,14936,11184,14930,10970,14921,10783,14912,10621,14900,10480,14885,10356,14867,10247,14848,10062,14827,9894,14805,9745,14400,14208,14400,14206,14402,14198,14406,14174,14415,14122,14427,14035,14444,13913,14469,13767,14504,13613,14548,13463,14598,13324,14651,13082,14704,12858,14752,12658,14795,12483,14831,12330,14860,12106,14881,11875,14895,11675,14903,11501,14905,11351,14903,11178,14900,10953,14892,10757,14880,10589,14865,10442,14847,10313,14827,10162,14805,9965,14782,9792,14757,9642,14731,9507,14562,13883,14562,13883,14563,13877,14566,13862,14570,13830,14576,13773,14584,13689,14595,13582,14613,13461,14637,13336,14668,13120,14704,12897,14741,12695,14776,12516,14808,12358,14835,12150,14856,11910,14870,11701,14878,11519,14882,11361,14884,11187,14880,10951,14871,10748,14858,10572,14842,10418,14823,10286,14801,10099,14777,9897,14751,9722,14725,9567,14696,9430,14666,9309,14702,13604,14702,13604,14702,13600,14703,13591,14705,13570,14707,13533,14709,13477,14712,13400,14718,13305,14727,13106,14743,12907,14762,12716,14784,12539,14807,12380,14827,12190,14844,11943,14855,11727,14863,11539,14870,11376,14871,11204,14868,10960,14858,10748,14845,10565,14829,10406,14809,10269,14786,10058,14761,9852,14734,9671,14705,9512,14674,9374,14641,9253,14608,9076,14821,13366,14821,13365,14821,13364,14821,13358,14821,13344,14821,13320,14819,13252,14817,13145,14815,13011,14814,12858,14817,12698,14823,12539,14832,12389,14841,12214,14850,11968,14856,11750,14861,11558,14866,11390,14867,11226,14862,10972,14853,10754,14840,10565,14823,10401,14803,10259,14780,10032,14754,9820,14725,9635,14694,9473,14661,9333,14627,9203,14593,8988,14557,8798,14923,13014,14922,13014,14922,13012,14922,13004,14920,12987,14919,12957,14915,12907,14909,12834,14902,12738,14894,12623,14888,12498,14883,12370,14880,12203,14878,11970,14875,11759,14873,11569,14874,11401,14872,11243,14865,10986,14855,10762,14842,10568,14825,10401,14804,10255,14781,10017,14754,9799,14725,9611,14692,9445,14658,9301,14623,9139,14587,8920,14548,8729,14509,8562,15008,12672,15008,12672,15008,12671,15007,12667,15005,12656,15001,12637,14997,12605,14989,12556,14978,12490,14966,12407,14953,12313,14940,12136,14927,11934,14914,11742,14903,11563,14896,11401,14889,11247,14879,10992,14866,10767,14851,10570,14833,10400,14812,10252,14789,10007,14761,9784,14731,9592,14698,9424,14663,9279,14627,9088,14588,8868,14548,8676,14508,8508,14467,8360,15080,12386,15080,12386,15079,12385,15078,12383,15076,12378,15072,12367,15066,12347,15057,12315,15045,12253,15030,12138,15012,11998,14993,11845,14972,11685,14951,11530,14935,11383,14920,11228,14904,10981,14887,10762,14870,10567,14850,10397,14827,10248,14803,9997,14774,9771,14743,9578,14710,9407,14674,9259,14637,9048,14596,8826,14555,8632,14514,8464,14471,8317,14427,8182,15139,12008,15139,12008,15138,12008,15137,12007,15135,12003,15130,11990,15124,11969,15115,11929,15102,11872,15086,11794,15064,11693,15041,11581,15013,11459,14987,11336,14966,11170,14944,10944,14921,10738,14898,10552,14875,10387,14850,10239,14824,9983,14794,9758,14762,9563,14728,9392,14692,9244,14653,9014,14611,8791,14569,8597,14526,8427,14481,8281,14436,8110,14391,7885,15188,11617,15188,11617,15187,11617,15186,11618,15183,11617,15179,11612,15173,11601,15163,11581,15150,11546,15133,11495,15110,11427,15083,11346,15051,11246,15024,11057,14996,10868,14967,10687,14938,10517,14911,10362,14882,10206,14853,9956,14821,9737,14787,9543,14752,9375,14715,9228,14675,8980,14632,8760,14589,8565,14544,8395,14498,8248,14451,8049,14404,7824,14357,7630,15228,11298,15228,11298,15227,11299,15226,11301,15223,11303,15219,11302,15213,11299,15204,11290,15191,11271,15174,11217,15150,11129,15119,11015,15087,10886,15057,10744,15024,10599,14990,10455,14957,10318,14924,10143,14891,9911,14856,9701,14820,9516,14782,9352,14744,9200,14703,8946,14659,8725,14615,8533,14568,8366,14521,8220,14472,7992,14423,7770,14374,7578,14315,7408,15260,10819,15260,10819,15259,10822,15258,10826,15256,10832,15251,10836,15246,10841,15237,10838,15225,10821,15207,10788,15183,10734,15151,10660,15120,10571,15087,10469,15049,10359,15012,10249,14974,10041,14937,9837,14900,9647,14860,9475,14820,9320,14779,9147,14736,8902,14691,8688,14646,8499,14598,8335,14549,8189,14499,7940,14448,7720,14397,7529,14347,7363,14256,7218,15285,10410,15285,10411,15285,10413,15284,10418,15282,10425,15278,10434,15272,10442,15264,10449,15252,10445,15235,10433,15210,10403,15179,10358,15149,10301,15113,10218,15073,10059,15033,9894,14991,9726,14951,9565,14909,9413,14865,9273,14822,9073,14777,8845,14730,8641,14682,8459,14633,8300,14583,8129,14531,7883,14479,7670,14426,7482,14373,7321,14305,7176,14201,6939,15305,9939,15305,9940,15305,9945,15304,9955,15302,9967,15298,9989,15293,10010,15286,10033,15274,10044,15258,10045,15233,10022,15205,9975,15174,9903,15136,9808,15095,9697,15053,9578,15009,9451,14965,9327,14918,9198,14871,8973,14825,8766,14775,8579,14725,8408,14675,8259,14622,8058,14569,7821,14515,7615,14460,7435,14405,7276,14350,7108,14256,6866,14149,6653,15321,9444,15321,9445,15321,9448,15320,9458,15317,9470,15314,9490,15310,9515,15302,9540,15292,9562,15276,9579,15251,9577,15226,9559,15195,9519,15156,9463,15116,9389,15071,9304,15025,9208,14978,9023,14927,8838,14878,8661,14827,8496,14774,8344,14722,8206,14667,7973,14612,7749,14556,7555,14499,7382,14443,7229,14385,7025,14322,6791,14210,6588,14100,6409,15333,8920,15333,8921,15332,8927,15332,8943,15329,8965,15326,9002,15322,9048,15316,9106,15307,9162,15291,9204,15267,9221,15244,9221,15212,9196,15175,9134,15133,9043,15088,8930,15040,8801,14990,8665,14938,8526,14886,8391,14830,8261,14775,8087,14719,7866,14661,7664,14603,7482,14544,7322,14485,7178,14426,6936,14367,6713,14281,6517,14166,6348,14054,6198,15341,8360,15341,8361,15341,8366,15341,8379,15339,8399,15336,8431,15332,8473,15326,8527,15318,8585,15302,8632,15281,8670,15258,8690,15227,8690,15191,8664,15149,8612,15104,8543,15055,8456,15001,8360,14948,8259,14892,8122,14834,7923,14776,7734,14716,7558,14656,7397,14595,7250,14534,7070,14472,6835,14410,6628,14350,6443,14243,6283,14125,6135,14010,5889,15348,7715,15348,7717,15348,7725,15347,7745,15345,7780,15343,7836,15339,7905,15334,8e3,15326,8103,15310,8193,15293,8239,15270,8270,15240,8287,15204,8283,15163,8260,15118,8223,15067,8143,15014,8014,14958,7873,14899,7723,14839,7573,14778,7430,14715,7293,14652,7164,14588,6931,14524,6720,14460,6531,14396,6362,14330,6210,14207,6015,14086,5781,13969,5576,15352,7114,15352,7116,15352,7128,15352,7159,15350,7195,15348,7237,15345,7299,15340,7374,15332,7457,15317,7544,15301,7633,15280,7703,15251,7754,15216,7775,15176,7767,15131,7733,15079,7670,15026,7588,14967,7492,14906,7387,14844,7278,14779,7171,14714,6965,14648,6770,14581,6587,14515,6420,14448,6269,14382,6123,14299,5881,14172,5665,14049,5477,13929,5310,15355,6329,15355,6330,15355,6339,15355,6362,15353,6410,15351,6472,15349,6572,15344,6688,15337,6835,15323,6985,15309,7142,15287,7220,15260,7277,15226,7310,15188,7326,15142,7318,15090,7285,15036,7239,14976,7177,14914,7045,14849,6892,14782,6736,14714,6581,14645,6433,14576,6293,14506,6164,14438,5946,14369,5733,14270,5540,14140,5369,14014,5216,13892,5043,15357,5483,15357,5484,15357,5496,15357,5528,15356,5597,15354,5692,15351,5835,15347,6011,15339,6195,15328,6317,15314,6446,15293,6566,15268,6668,15235,6746,15197,6796,15152,6811,15101,6790,15046,6748,14985,6673,14921,6583,14854,6479,14785,6371,14714,6259,14643,6149,14571,5946,14499,5750,14428,5567,14358,5401,14242,5250,14109,5111,13980,4870,13856,4657,15359,4555,15359,4557,15358,4573,15358,4633,15357,4715,15355,4841,15353,5061,15349,5216,15342,5391,15331,5577,15318,5770,15299,5967,15274,6150,15243,6223,15206,6280,15161,6310,15111,6317,15055,6300,14994,6262,14928,6208,14860,6141,14788,5994,14715,5838,14641,5684,14566,5529,14492,5384,14418,5247,14346,5121,14216,4892,14079,4682,13948,4496,13822,4330,15359,3498,15359,3501,15359,3520,15359,3598,15358,3719,15356,3860,15355,4137,15351,4305,15344,4563,15334,4809,15321,5116,15303,5273,15280,5418,15250,5547,15214,5653,15170,5722,15120,5761,15064,5763,15002,5733,14935,5673,14865,5597,14792,5504,14716,5400,14640,5294,14563,5185,14486,5041,14410,4841,14335,4655,14191,4482,14051,4325,13918,4183,13790,4012,15360,2282,15360,2285,15360,2306,15360,2401,15359,2547,15357,2748,15355,3103,15352,3349,15345,3675,15336,4020,15324,4272,15307,4496,15285,4716,15255,4908,15220,5086,15178,5170,15128,5214,15072,5234,15010,5231,14943,5206,14871,5166,14796,5102,14718,4971,14639,4833,14559,4687,14480,4541,14402,4401,14315,4268,14167,4142,14025,3958,13888,3747,13759,3556,15360,923,15360,925,15360,946,15360,1052,15359,1214,15357,1494,15356,1892,15352,2274,15346,2663,15338,3099,15326,3393,15309,3679,15288,3980,15260,4183,15226,4325,15185,4437,15136,4517,15080,4570,15018,4591,14950,4581,14877,4545,14800,4485,14720,4411,14638,4325,14556,4231,14475,4136,14395,3988,14297,3803,14145,3628,13999,3465,13861,3314,13729,3177,15360,263,15360,264,15360,272,15360,325,15359,407,15358,548,15356,780,15352,1144,15347,1580,15339,2099,15328,2425,15312,2795,15292,3133,15264,3329,15232,3517,15191,3689,15143,3819,15088,3923,15025,3978,14956,3999,14882,3979,14804,3931,14722,3855,14639,3756,14554,3645,14470,3529,14388,3409,14279,3289,14124,3173,13975,3055,13834,2848,13701,2658,15360,49,15360,49,15360,52,15360,75,15359,111,15358,201,15356,283,15353,519,15348,726,15340,1045,15329,1415,15314,1795,15295,2173,15269,2410,15237,2649,15197,2866,15150,3054,15095,3140,15032,3196,14963,3228,14888,3236,14808,3224,14725,3191,14639,3146,14553,3088,14466,2976,14382,2836,14262,2692,14103,2549,13952,2409,13808,2278,13674,2154,15360,4,15360,4,15360,4,15360,13,15359,33,15358,59,15357,112,15353,199,15348,302,15341,456,15331,628,15316,827,15297,1082,15272,1332,15241,1601,15202,1851,15156,2069,15101,2172,15039,2256,14970,2314,14894,2348,14813,2358,14728,2344,14640,2311,14551,2263,14463,2203,14376,2133,14247,2059,14084,1915,13930,1761,13784,1609,13648,1464,15360,0,15360,0,15360,0,15360,3,15359,18,15358,26,15357,53,15354,80,15348,97,15341,165,15332,238,15318,326,15299,427,15275,529,15245,654,15207,771,15161,885,15108,994,15046,1089,14976,1170,14900,1229,14817,1266,14731,1284,14641,1282,14550,1260,14460,1223,14370,1174,14232,1116,14066,1050,13909,981,13761,910,13623,839]);let xu=null;function Qwe(){return xu===null&&(xu=new Kbe(Ywe,32,32,UF,Gb),xu.minFilter=hl,xu.magFilter=hl,xu.wrapS=Ou,xu.wrapT=Ou,xu.generateMipmaps=!1,xu.needsUpdate=!0),xu}let Zwe=class{constructor(e={}){const{canvas:n=ybe(),context:r=null,depth:a=!0,stencil:s=!1,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:u=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:f=!1}=e;this.isWebGLRenderer=!0;let p;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=r.getContextAttributes().alpha}else p=o;const x=new Set([HF,BF,zF]),v=new Set([Lc,Ff,vv,wv,OF,IF]),g=new Uint32Array(4),y=new Int32Array(4);let _=null,N=null;const k=[],A=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Dh,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const M=this;let C=!1;this._outputColorSpace=ko;let j=0,P=0,E=null,U=-1,L=null;const B=new Za,D=new Za;let $=null;const G=new $n(0);let z=0,W=n.width,X=n.height,ae=1,H=null,K=null;const te=new Za(0,0,W,X),Z=new Za(0,0,W,X);let ve=!1;const ce=new WF;let ee=!1,je=!1;const he=new ri,oe=new ft,_e=new Za,ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ze=!1;function V(){return E===null?ae:1}let Y=r;function me(ye,He){return n.getContext(ye,He)}try{const ye={alpha:!0,depth:a,stencil:s,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:u,powerPreference:d,failIfMajorPerformanceCaveat:h};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${RF}`),n.addEventListener("webglcontextlost",Ae,!1),n.addEventListener("webglcontextrestored",Re,!1),n.addEventListener("webglcontextcreationerror",$e,!1),Y===null){const He="webgl2";if(Y=me(He,ye),Y===null)throw me(He)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(ye){throw ye("WebGLRenderer: "+ye.message),ye}let Q,se,de,Le,Ne,be,O,R,q,J,fe,le,Be,Ie,Ke,Oe,pe,xe,ke,ge,we,qe,Ee,tt;function De(){Q=new s0e(Y),Q.init(),qe=new Hwe(Y,Q),se=new Qve(Y,Q,e,qe),de=new Uwe(Y,Q),se.reversedDepthBuffer&&f&&de.buffers.depth.setReversed(!0),Le=new c0e(Y),Ne=new Awe,be=new Bwe(Y,Q,de,Ne,se,qe,Le),O=new Jve(M),R=new i0e(M),q=new mxe(Y),Ee=new Xve(Y,q),J=new o0e(Y,q,Le,Ee),fe=new d0e(Y,J,q,Le),ke=new u0e(Y,se,be),Oe=new Zve(Ne),le=new kwe(M,O,R,Q,se,Ee,Oe),Be=new Kwe(M,Ne),Ie=new Mwe,Ke=new Fwe(Q),xe=new Kve(M,O,R,de,fe,p,c),pe=new Iwe(M,fe,se),tt=new Xwe(Y,Le,se,de),ge=new Yve(Y,Q,Le),we=new l0e(Y,Q,Le),Le.programs=le.programs,M.capabilities=se,M.extensions=Q,M.properties=Ne,M.renderLists=Ie,M.shadowMap=pe,M.state=de,M.info=Le}De();const We=new Gwe(M,Y);this.xr=We,this.getContext=function(){return Y},this.getContextAttributes=function(){return Y.getContextAttributes()},this.forceContextLoss=function(){const ye=Q.get("WEBGL_lose_context");ye&&ye.loseContext()},this.forceContextRestore=function(){const ye=Q.get("WEBGL_lose_context");ye&&ye.restoreContext()},this.getPixelRatio=function(){return ae},this.setPixelRatio=function(ye){ye!==void 0&&(ae=ye,this.setSize(W,X,!1))},this.getSize=function(ye){return ye.set(W,X)},this.setSize=function(ye,He,Ye=!0){if(We.isPresenting){vn("WebGLRenderer: Can't change size while VR device is presenting.");return}W=ye,X=He,n.width=Math.floor(ye*ae),n.height=Math.floor(He*ae),Ye===!0&&(n.style.width=ye+"px",n.style.height=He+"px"),this.setViewport(0,0,ye,He)},this.getDrawingBufferSize=function(ye){return ye.set(W*ae,X*ae).floor()},this.setDrawingBufferSize=function(ye,He,Ye){W=ye,X=He,ae=Ye,n.width=Math.floor(ye*Ye),n.height=Math.floor(He*Ye),this.setViewport(0,0,ye,He)},this.getCurrentViewport=function(ye){return ye.copy(B)},this.getViewport=function(ye){return ye.copy(te)},this.setViewport=function(ye,He,Ye,Xe){ye.isVector4?te.set(ye.x,ye.y,ye.z,ye.w):te.set(ye,He,Ye,Xe),de.viewport(B.copy(te).multiplyScalar(ae).round())},this.getScissor=function(ye){return ye.copy(Z)},this.setScissor=function(ye,He,Ye,Xe){ye.isVector4?Z.set(ye.x,ye.y,ye.z,ye.w):Z.set(ye,He,Ye,Xe),de.scissor(D.copy(Z).multiplyScalar(ae).round())},this.getScissorTest=function(){return ve},this.setScissorTest=function(ye){de.setScissorTest(ve=ye)},this.setOpaqueSort=function(ye){H=ye},this.setTransparentSort=function(ye){K=ye},this.getClearColor=function(ye){return ye.copy(xe.getClearColor())},this.setClearColor=function(){xe.setClearColor(...arguments)},this.getClearAlpha=function(){return xe.getClearAlpha()},this.setClearAlpha=function(){xe.setClearAlpha(...arguments)},this.clear=function(ye=!0,He=!0,Ye=!0){let Xe=0;if(ye){let Te=!1;if(E!==null){const lt=E.texture.format;Te=x.has(lt)}if(Te){const lt=E.texture.type,pt=v.has(lt),at=xe.getClearColor(),Tt=xe.getClearAlpha(),$t=at.r,Rt=at.g,Pt=at.b;pt?(g[0]=$t,g[1]=Rt,g[2]=Pt,g[3]=Tt,Y.clearBufferuiv(Y.COLOR,0,g)):(y[0]=$t,y[1]=Rt,y[2]=Pt,y[3]=Tt,Y.clearBufferiv(Y.COLOR,0,y))}else Xe|=Y.COLOR_BUFFER_BIT}He&&(Xe|=Y.DEPTH_BUFFER_BIT),Ye&&(Xe|=Y.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Y.clear(Xe)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",Ae,!1),n.removeEventListener("webglcontextrestored",Re,!1),n.removeEventListener("webglcontextcreationerror",$e,!1),xe.dispose(),Ie.dispose(),Ke.dispose(),Ne.dispose(),O.dispose(),R.dispose(),fe.dispose(),Ee.dispose(),tt.dispose(),le.dispose(),We.dispose(),We.removeEventListener("sessionstart",bt),We.removeEventListener("sessionend",yt),Gt.stop()};function Ae(ye){ye.preventDefault(),ZB("WebGLRenderer: Context Lost."),C=!0}function Re(){ZB("WebGLRenderer: Context Restored."),C=!1;const ye=Le.autoReset,He=pe.enabled,Ye=pe.autoUpdate,Xe=pe.needsUpdate,Te=pe.type;De(),Le.autoReset=ye,pe.enabled=He,pe.autoUpdate=Ye,pe.needsUpdate=Xe,pe.type=Te}function $e(ye){Ua("WebGLRenderer: A WebGL context could not be created. Reason: ",ye.statusMessage)}function ht(ye){const He=ye.target;He.removeEventListener("dispose",ht),At(He)}function At(ye){Dt(ye),Ne.remove(ye)}function Dt(ye){const He=Ne.get(ye).programs;He!==void 0&&(He.forEach(function(Ye){le.releaseProgram(Ye)}),ye.isShaderMaterial&&le.releaseShaderCache(ye))}this.renderBufferDirect=function(ye,He,Ye,Xe,Te,lt){He===null&&(He=ie);const pt=Te.isMesh&&Te.matrixWorld.determinant()<0,at=Fe(ye,He,Ye,Xe,Te);de.setMaterial(Xe,pt);let Tt=Ye.index,$t=1;if(Xe.wireframe===!0){if(Tt=J.getWireframeAttribute(Ye),Tt===void 0)return;$t=2}const Rt=Ye.drawRange,Pt=Ye.attributes.position;let sn=Rt.start*$t,Zt=(Rt.start+Rt.count)*$t;lt!==null&&(sn=Math.max(sn,lt.start*$t),Zt=Math.min(Zt,(lt.start+lt.count)*$t)),Tt!==null?(sn=Math.max(sn,0),Zt=Math.min(Zt,Tt.count)):Pt!=null&&(sn=Math.max(sn,0),Zt=Math.min(Zt,Pt.count));const un=Zt-sn;if(un<0||un===1/0)return;Ee.setup(Te,Xe,at,Ye,Tt);let kn,Dn=ge;if(Tt!==null&&(kn=q.get(Tt),Dn=we,Dn.setIndex(kn)),Te.isMesh)Xe.wireframe===!0?(de.setLineWidth(Xe.wireframeLinewidth*V()),Dn.setMode(Y.LINES)):Dn.setMode(Y.TRIANGLES);else if(Te.isLine){let Xt=Xe.linewidth;Xt===void 0&&(Xt=1),de.setLineWidth(Xt*V()),Te.isLineSegments?Dn.setMode(Y.LINES):Te.isLineLoop?Dn.setMode(Y.LINE_LOOP):Dn.setMode(Y.LINE_STRIP)}else Te.isPoints?Dn.setMode(Y.POINTS):Te.isSprite&&Dn.setMode(Y.TRIANGLES);if(Te.isBatchedMesh)if(Te._multiDrawInstances!==null)Nv("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),Dn.renderMultiDrawInstances(Te._multiDrawStarts,Te._multiDrawCounts,Te._multiDrawCount,Te._multiDrawInstances);else if(Q.get("WEBGL_multi_draw"))Dn.renderMultiDraw(Te._multiDrawStarts,Te._multiDrawCounts,Te._multiDrawCount);else{const Xt=Te._multiDrawStarts,mn=Te._multiDrawCounts,fn=Te._multiDrawCount,Gr=Tt?q.get(Tt).bytesPerElement:1,pn=Ne.get(Xe).currentProgram.getUniforms();for(let Rn=0;Rn<fn;Rn++)pn.setValue(Y,"_gl_DrawID",Rn),Dn.render(Xt[Rn]/Gr,mn[Rn])}else if(Te.isInstancedMesh)Dn.renderInstances(sn,un,Te.count);else if(Ye.isInstancedBufferGeometry){const Xt=Ye._maxInstanceCount!==void 0?Ye._maxInstanceCount:1/0,mn=Math.min(Ye.instanceCount,Xt);Dn.renderInstances(sn,un,mn)}else Dn.render(sn,un)};function It(ye,He,Ye){ye.transparent===!0&&ye.side===_c&&ye.forceSinglePass===!1?(ye.side=to,ye.needsUpdate=!0,dr(ye,He,Ye),ye.side=qh,ye.needsUpdate=!0,dr(ye,He,Ye),ye.side=_c):dr(ye,He,Ye)}this.compile=function(ye,He,Ye=null){Ye===null&&(Ye=ye),N=Ke.get(Ye),N.init(He),A.push(N),Ye.traverseVisible(function(Te){Te.isLight&&Te.layers.test(He.layers)&&(N.pushLight(Te),Te.castShadow&&N.pushShadow(Te))}),ye!==Ye&&ye.traverseVisible(function(Te){Te.isLight&&Te.layers.test(He.layers)&&(N.pushLight(Te),Te.castShadow&&N.pushShadow(Te))}),N.setupLights();const Xe=new Set;return ye.traverse(function(Te){if(!(Te.isMesh||Te.isPoints||Te.isLine||Te.isSprite))return;const lt=Te.material;if(lt)if(Array.isArray(lt))for(let pt=0;pt<lt.length;pt++){const at=lt[pt];It(at,Ye,Te),Xe.add(at)}else It(lt,Ye,Te),Xe.add(lt)}),N=A.pop(),Xe},this.compileAsync=function(ye,He,Ye=null){const Xe=this.compile(ye,He,Ye);return new Promise(Te=>{function lt(){if(Xe.forEach(function(pt){Ne.get(pt).currentProgram.isReady()&&Xe.delete(pt)}),Xe.size===0){Te(ye);return}setTimeout(lt,10)}Q.get("KHR_parallel_shader_compile")!==null?lt():setTimeout(lt,10)})};let kt=null;function Ue(ye){kt&&kt(ye)}function bt(){Gt.stop()}function yt(){Gt.start()}const Gt=new hY;Gt.setAnimationLoop(Ue),typeof self<"u"&&Gt.setContext(self),this.setAnimationLoop=function(ye){kt=ye,We.setAnimationLoop(ye),ye===null?Gt.stop():Gt.start()},We.addEventListener("sessionstart",bt),We.addEventListener("sessionend",yt),this.render=function(ye,He){if(He!==void 0&&He.isCamera!==!0){Ua("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;if(ye.matrixWorldAutoUpdate===!0&&ye.updateMatrixWorld(),He.parent===null&&He.matrixWorldAutoUpdate===!0&&He.updateMatrixWorld(),We.enabled===!0&&We.isPresenting===!0&&(We.cameraAutoUpdate===!0&&We.updateCamera(He),He=We.getCamera()),ye.isScene===!0&&ye.onBeforeRender(M,ye,He,E),N=Ke.get(ye,A.length),N.init(He),A.push(N),he.multiplyMatrices(He.projectionMatrix,He.matrixWorldInverse),ce.setFromProjectionMatrix(he,kc,He.reversedDepth),je=this.localClippingEnabled,ee=Oe.init(this.clippingPlanes,je),_=Ie.get(ye,k.length),_.init(),k.push(_),We.enabled===!0&&We.isPresenting===!0){const lt=M.xr.getDepthSensingMesh();lt!==null&&Cn(lt,He,-1/0,M.sortObjects)}Cn(ye,He,0,M.sortObjects),_.finish(),M.sortObjects===!0&&_.sort(H,K),ze=We.enabled===!1||We.isPresenting===!1||We.hasDepthSensing()===!1,ze&&xe.addToRenderList(_,ye),this.info.render.frame++,ee===!0&&Oe.beginShadows();const Ye=N.state.shadowsArray;pe.render(Ye,ye,He),ee===!0&&Oe.endShadows(),this.info.autoReset===!0&&this.info.reset();const Xe=_.opaque,Te=_.transmissive;if(N.setupLights(),He.isArrayCamera){const lt=He.cameras;if(Te.length>0)for(let pt=0,at=lt.length;pt<at;pt++){const Tt=lt[pt];Qn(Xe,Te,ye,Tt)}ze&&xe.render(ye);for(let pt=0,at=lt.length;pt<at;pt++){const Tt=lt[pt];vr(_,ye,Tt,Tt.viewport)}}else Te.length>0&&Qn(Xe,Te,ye,He),ze&&xe.render(ye),vr(_,ye,He);E!==null&&P===0&&(be.updateMultisampleRenderTarget(E),be.updateRenderTargetMipmap(E)),ye.isScene===!0&&ye.onAfterRender(M,ye,He),Ee.resetDefaultState(),U=-1,L=null,A.pop(),A.length>0?(N=A[A.length-1],ee===!0&&Oe.setGlobalState(M.clippingPlanes,N.state.camera)):N=null,k.pop(),k.length>0?_=k[k.length-1]:_=null};function Cn(ye,He,Ye,Xe){if(ye.visible===!1)return;if(ye.layers.test(He.layers)){if(ye.isGroup)Ye=ye.renderOrder;else if(ye.isLOD)ye.autoUpdate===!0&&ye.update(He);else if(ye.isLight)N.pushLight(ye),ye.castShadow&&N.pushShadow(ye);else if(ye.isSprite){if(!ye.frustumCulled||ce.intersectsSprite(ye)){Xe&&_e.setFromMatrixPosition(ye.matrixWorld).applyMatrix4(he);const pt=fe.update(ye),at=ye.material;at.visible&&_.push(ye,pt,at,Ye,_e.z,null)}}else if((ye.isMesh||ye.isLine||ye.isPoints)&&(!ye.frustumCulled||ce.intersectsObject(ye))){const pt=fe.update(ye),at=ye.material;if(Xe&&(ye.boundingSphere!==void 0?(ye.boundingSphere===null&&ye.computeBoundingSphere(),_e.copy(ye.boundingSphere.center)):(pt.boundingSphere===null&&pt.computeBoundingSphere(),_e.copy(pt.boundingSphere.center)),_e.applyMatrix4(ye.matrixWorld).applyMatrix4(he)),Array.isArray(at)){const Tt=pt.groups;for(let $t=0,Rt=Tt.length;$t<Rt;$t++){const Pt=Tt[$t],sn=at[Pt.materialIndex];sn&&sn.visible&&_.push(ye,pt,sn,Ye,_e.z,Pt)}}else at.visible&&_.push(ye,pt,at,Ye,_e.z,null)}}const lt=ye.children;for(let pt=0,at=lt.length;pt<at;pt++)Cn(lt[pt],He,Ye,Xe)}function vr(ye,He,Ye,Xe){const{opaque:Te,transmissive:lt,transparent:pt}=ye;N.setupLightsView(Ye),ee===!0&&Oe.setGlobalState(M.clippingPlanes,Ye),Xe&&de.viewport(B.copy(Xe)),Te.length>0&&tr(Te,He,Ye),lt.length>0&&tr(lt,He,Ye),pt.length>0&&tr(pt,He,Ye),de.buffers.depth.setTest(!0),de.buffers.depth.setMask(!0),de.buffers.color.setMask(!0),de.setPolygonOffset(!1)}function Qn(ye,He,Ye,Xe){if((Ye.isScene===!0?Ye.overrideMaterial:null)!==null)return;N.state.transmissionRenderTarget[Xe.id]===void 0&&(N.state.transmissionRenderTarget[Xe.id]=new Of(1,1,{generateMipmaps:!0,type:Q.has("EXT_color_buffer_half_float")||Q.has("EXT_color_buffer_float")?Gb:Lc,minFilter:tf,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:cr.workingColorSpace}));const lt=N.state.transmissionRenderTarget[Xe.id],pt=Xe.viewport||B;lt.setSize(pt.z*M.transmissionResolutionScale,pt.w*M.transmissionResolutionScale);const at=M.getRenderTarget(),Tt=M.getActiveCubeFace(),$t=M.getActiveMipmapLevel();M.setRenderTarget(lt),M.getClearColor(G),z=M.getClearAlpha(),z<1&&M.setClearColor(16777215,.5),M.clear(),ze&&xe.render(Ye);const Rt=M.toneMapping;M.toneMapping=Dh;const Pt=Xe.viewport;if(Xe.viewport!==void 0&&(Xe.viewport=void 0),N.setupLightsView(Xe),ee===!0&&Oe.setGlobalState(M.clippingPlanes,Xe),tr(ye,Ye,Xe),be.updateMultisampleRenderTarget(lt),be.updateRenderTargetMipmap(lt),Q.has("WEBGL_multisampled_render_to_texture")===!1){let sn=!1;for(let Zt=0,un=He.length;Zt<un;Zt++){const kn=He[Zt],{object:Dn,geometry:Xt,material:mn,group:fn}=kn;if(mn.side===_c&&Dn.layers.test(Xe.layers)){const Gr=mn.side;mn.side=to,mn.needsUpdate=!0,En(Dn,Ye,Xe,Xt,mn,fn),mn.side=Gr,mn.needsUpdate=!0,sn=!0}}sn===!0&&(be.updateMultisampleRenderTarget(lt),be.updateRenderTargetMipmap(lt))}M.setRenderTarget(at,Tt,$t),M.setClearColor(G,z),Pt!==void 0&&(Xe.viewport=Pt),M.toneMapping=Rt}function tr(ye,He,Ye){const Xe=He.isScene===!0?He.overrideMaterial:null;for(let Te=0,lt=ye.length;Te<lt;Te++){const pt=ye[Te],{object:at,geometry:Tt,group:$t}=pt;let Rt=pt.material;Rt.allowOverride===!0&&Xe!==null&&(Rt=Xe),at.layers.test(Ye.layers)&&En(at,He,Ye,Tt,Rt,$t)}}function En(ye,He,Ye,Xe,Te,lt){ye.onBeforeRender(M,He,Ye,Xe,Te,lt),ye.modelViewMatrix.multiplyMatrices(Ye.matrixWorldInverse,ye.matrixWorld),ye.normalMatrix.getNormalMatrix(ye.modelViewMatrix),Te.onBeforeRender(M,He,Ye,Xe,ye,lt),Te.transparent===!0&&Te.side===_c&&Te.forceSinglePass===!1?(Te.side=to,Te.needsUpdate=!0,M.renderBufferDirect(Ye,He,Xe,Te,ye,lt),Te.side=qh,Te.needsUpdate=!0,M.renderBufferDirect(Ye,He,Xe,Te,ye,lt),Te.side=_c):M.renderBufferDirect(Ye,He,Xe,Te,ye,lt),ye.onAfterRender(M,He,Ye,Xe,Te,lt)}function dr(ye,He,Ye){He.isScene!==!0&&(He=ie);const Xe=Ne.get(ye),Te=N.state.lights,lt=N.state.shadowsArray,pt=Te.state.version,at=le.getParameters(ye,Te.state,lt,He,Ye),Tt=le.getProgramCacheKey(at);let $t=Xe.programs;Xe.environment=ye.isMeshStandardMaterial?He.environment:null,Xe.fog=He.fog,Xe.envMap=(ye.isMeshStandardMaterial?R:O).get(ye.envMap||Xe.environment),Xe.envMapRotation=Xe.environment!==null&&ye.envMap===null?He.environmentRotation:ye.envMapRotation,$t===void 0&&(ye.addEventListener("dispose",ht),$t=new Map,Xe.programs=$t);let Rt=$t.get(Tt);if(Rt!==void 0){if(Xe.currentProgram===Rt&&Xe.lightsStateVersion===pt)return si(ye,at),Rt}else at.uniforms=le.getUniforms(ye),ye.onBeforeCompile(at,M),Rt=le.acquireProgram(at,Tt),$t.set(Tt,Rt),Xe.uniforms=at.uniforms;const Pt=Xe.uniforms;return(!ye.isShaderMaterial&&!ye.isRawShaderMaterial||ye.clipping===!0)&&(Pt.clippingPlanes=Oe.uniform),si(ye,at),Xe.needsLights=nt(ye),Xe.lightsStateVersion=pt,Xe.needsLights&&(Pt.ambientLightColor.value=Te.state.ambient,Pt.lightProbe.value=Te.state.probe,Pt.directionalLights.value=Te.state.directional,Pt.directionalLightShadows.value=Te.state.directionalShadow,Pt.spotLights.value=Te.state.spot,Pt.spotLightShadows.value=Te.state.spotShadow,Pt.rectAreaLights.value=Te.state.rectArea,Pt.ltc_1.value=Te.state.rectAreaLTC1,Pt.ltc_2.value=Te.state.rectAreaLTC2,Pt.pointLights.value=Te.state.point,Pt.pointLightShadows.value=Te.state.pointShadow,Pt.hemisphereLights.value=Te.state.hemi,Pt.directionalShadowMap.value=Te.state.directionalShadowMap,Pt.directionalShadowMatrix.value=Te.state.directionalShadowMatrix,Pt.spotShadowMap.value=Te.state.spotShadowMap,Pt.spotLightMatrix.value=Te.state.spotLightMatrix,Pt.spotLightMap.value=Te.state.spotLightMap,Pt.pointShadowMap.value=Te.state.pointShadowMap,Pt.pointShadowMatrix.value=Te.state.pointShadowMatrix),Xe.currentProgram=Rt,Xe.uniformsList=null,Rt}function Tr(ye){if(ye.uniformsList===null){const He=ye.currentProgram.getUniforms();ye.uniformsList=Q_.seqWithValue(He.seq,ye.uniforms)}return ye.uniformsList}function si(ye,He){const Ye=Ne.get(ye);Ye.outputColorSpace=He.outputColorSpace,Ye.batching=He.batching,Ye.batchingColor=He.batchingColor,Ye.instancing=He.instancing,Ye.instancingColor=He.instancingColor,Ye.instancingMorph=He.instancingMorph,Ye.skinning=He.skinning,Ye.morphTargets=He.morphTargets,Ye.morphNormals=He.morphNormals,Ye.morphColors=He.morphColors,Ye.morphTargetsCount=He.morphTargetsCount,Ye.numClippingPlanes=He.numClippingPlanes,Ye.numIntersection=He.numClipIntersection,Ye.vertexAlphas=He.vertexAlphas,Ye.vertexTangents=He.vertexTangents,Ye.toneMapping=He.toneMapping}function Fe(ye,He,Ye,Xe,Te){He.isScene!==!0&&(He=ie),be.resetTextureUnits();const lt=He.fog,pt=Xe.isMeshStandardMaterial?He.environment:null,at=E===null?M.outputColorSpace:E.isXRRenderTarget===!0?E.texture.colorSpace:bb,Tt=(Xe.isMeshStandardMaterial?R:O).get(Xe.envMap||pt),$t=Xe.vertexColors===!0&&!!Ye.attributes.color&&Ye.attributes.color.itemSize===4,Rt=!!Ye.attributes.tangent&&(!!Xe.normalMap||Xe.anisotropy>0),Pt=!!Ye.morphAttributes.position,sn=!!Ye.morphAttributes.normal,Zt=!!Ye.morphAttributes.color;let un=Dh;Xe.toneMapped&&(E===null||E.isXRRenderTarget===!0)&&(un=M.toneMapping);const kn=Ye.morphAttributes.position||Ye.morphAttributes.normal||Ye.morphAttributes.color,Dn=kn!==void 0?kn.length:0,Xt=Ne.get(Xe),mn=N.state.lights;if(ee===!0&&(je===!0||ye!==L)){const ma=ye===L&&Xe.id===U;Oe.setState(Xe,ye,ma)}let fn=!1;Xe.version===Xt.__version?(Xt.needsLights&&Xt.lightsStateVersion!==mn.state.version||Xt.outputColorSpace!==at||Te.isBatchedMesh&&Xt.batching===!1||!Te.isBatchedMesh&&Xt.batching===!0||Te.isBatchedMesh&&Xt.batchingColor===!0&&Te.colorTexture===null||Te.isBatchedMesh&&Xt.batchingColor===!1&&Te.colorTexture!==null||Te.isInstancedMesh&&Xt.instancing===!1||!Te.isInstancedMesh&&Xt.instancing===!0||Te.isSkinnedMesh&&Xt.skinning===!1||!Te.isSkinnedMesh&&Xt.skinning===!0||Te.isInstancedMesh&&Xt.instancingColor===!0&&Te.instanceColor===null||Te.isInstancedMesh&&Xt.instancingColor===!1&&Te.instanceColor!==null||Te.isInstancedMesh&&Xt.instancingMorph===!0&&Te.morphTexture===null||Te.isInstancedMesh&&Xt.instancingMorph===!1&&Te.morphTexture!==null||Xt.envMap!==Tt||Xe.fog===!0&&Xt.fog!==lt||Xt.numClippingPlanes!==void 0&&(Xt.numClippingPlanes!==Oe.numPlanes||Xt.numIntersection!==Oe.numIntersection)||Xt.vertexAlphas!==$t||Xt.vertexTangents!==Rt||Xt.morphTargets!==Pt||Xt.morphNormals!==sn||Xt.morphColors!==Zt||Xt.toneMapping!==un||Xt.morphTargetsCount!==Dn)&&(fn=!0):(fn=!0,Xt.__version=Xe.version);let Gr=Xt.currentProgram;fn===!0&&(Gr=dr(Xe,He,Te));let pn=!1,Rn=!1,ia=!1;const Sn=Gr.getUniforms(),va=Xt.uniforms;if(de.useProgram(Gr.program)&&(pn=!0,Rn=!0,ia=!0),Xe.id!==U&&(U=Xe.id,Rn=!0),pn||L!==ye){de.buffers.depth.getReversed()&&ye.reversedDepth!==!0&&(ye._reversedDepth=!0,ye.updateProjectionMatrix()),Sn.setValue(Y,"projectionMatrix",ye.projectionMatrix),Sn.setValue(Y,"viewMatrix",ye.matrixWorldInverse);const xt=Sn.map.cameraPosition;xt!==void 0&&xt.setValue(Y,oe.setFromMatrixPosition(ye.matrixWorld)),se.logarithmicDepthBuffer&&Sn.setValue(Y,"logDepthBufFC",2/(Math.log(ye.far+1)/Math.LN2)),(Xe.isMeshPhongMaterial||Xe.isMeshToonMaterial||Xe.isMeshLambertMaterial||Xe.isMeshBasicMaterial||Xe.isMeshStandardMaterial||Xe.isShaderMaterial)&&Sn.setValue(Y,"isOrthographic",ye.isOrthographicCamera===!0),L!==ye&&(L=ye,Rn=!0,ia=!0)}if(Te.isSkinnedMesh){Sn.setOptional(Y,Te,"bindMatrix"),Sn.setOptional(Y,Te,"bindMatrixInverse");const ma=Te.skeleton;ma&&(ma.boneTexture===null&&ma.computeBoneTexture(),Sn.setValue(Y,"boneTexture",ma.boneTexture,be))}Te.isBatchedMesh&&(Sn.setOptional(Y,Te,"batchingTexture"),Sn.setValue(Y,"batchingTexture",Te._matricesTexture,be),Sn.setOptional(Y,Te,"batchingIdTexture"),Sn.setValue(Y,"batchingIdTexture",Te._indirectTexture,be),Sn.setOptional(Y,Te,"batchingColorTexture"),Te._colorsTexture!==null&&Sn.setValue(Y,"batchingColorTexture",Te._colorsTexture,be));const sr=Ye.morphAttributes;if((sr.position!==void 0||sr.normal!==void 0||sr.color!==void 0)&&ke.update(Te,Ye,Gr),(Rn||Xt.receiveShadow!==Te.receiveShadow)&&(Xt.receiveShadow=Te.receiveShadow,Sn.setValue(Y,"receiveShadow",Te.receiveShadow)),Xe.isMeshGouraudMaterial&&Xe.envMap!==null&&(va.envMap.value=Tt,va.flipEnvMap.value=Tt.isCubeTexture&&Tt.isRenderTargetTexture===!1?-1:1),Xe.isMeshStandardMaterial&&Xe.envMap===null&&He.environment!==null&&(va.envMapIntensity.value=He.environmentIntensity),va.dfgLUT!==void 0&&(va.dfgLUT.value=Qwe()),Rn&&(Sn.setValue(Y,"toneMappingExposure",M.toneMappingExposure),Xt.needsLights&&Se(va,ia),lt&&Xe.fog===!0&&Be.refreshFogUniforms(va,lt),Be.refreshMaterialUniforms(va,Xe,ae,X,N.state.transmissionRenderTarget[ye.id]),Q_.upload(Y,Tr(Xt),va,be)),Xe.isShaderMaterial&&Xe.uniformsNeedUpdate===!0&&(Q_.upload(Y,Tr(Xt),va,be),Xe.uniformsNeedUpdate=!1),Xe.isSpriteMaterial&&Sn.setValue(Y,"center",Te.center),Sn.setValue(Y,"modelViewMatrix",Te.modelViewMatrix),Sn.setValue(Y,"normalMatrix",Te.normalMatrix),Sn.setValue(Y,"modelMatrix",Te.matrixWorld),Xe.isShaderMaterial||Xe.isRawShaderMaterial){const ma=Xe.uniformsGroups;for(let xt=0,Ft=ma.length;xt<Ft;xt++){const bn=ma[xt];tt.update(bn,Gr),tt.bind(bn,Gr)}}return Gr}function Se(ye,He){ye.ambientLightColor.needsUpdate=He,ye.lightProbe.needsUpdate=He,ye.directionalLights.needsUpdate=He,ye.directionalLightShadows.needsUpdate=He,ye.pointLights.needsUpdate=He,ye.pointLightShadows.needsUpdate=He,ye.spotLights.needsUpdate=He,ye.spotLightShadows.needsUpdate=He,ye.rectAreaLights.needsUpdate=He,ye.hemisphereLights.needsUpdate=He}function nt(ye){return ye.isMeshLambertMaterial||ye.isMeshToonMaterial||ye.isMeshPhongMaterial||ye.isMeshStandardMaterial||ye.isShadowMaterial||ye.isShaderMaterial&&ye.lights===!0}this.getActiveCubeFace=function(){return j},this.getActiveMipmapLevel=function(){return P},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(ye,He,Ye){const Xe=Ne.get(ye);Xe.__autoAllocateDepthBuffer=ye.resolveDepthBuffer===!1,Xe.__autoAllocateDepthBuffer===!1&&(Xe.__useRenderToTexture=!1),Ne.get(ye.texture).__webglTexture=He,Ne.get(ye.depthTexture).__webglTexture=Xe.__autoAllocateDepthBuffer?void 0:Ye,Xe.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(ye,He){const Ye=Ne.get(ye);Ye.__webglFramebuffer=He,Ye.__useDefaultFramebuffer=He===void 0};const ot=Y.createFramebuffer();this.setRenderTarget=function(ye,He=0,Ye=0){E=ye,j=He,P=Ye;let Xe=!0,Te=null,lt=!1,pt=!1;if(ye){const Tt=Ne.get(ye);if(Tt.__useDefaultFramebuffer!==void 0)de.bindFramebuffer(Y.FRAMEBUFFER,null),Xe=!1;else if(Tt.__webglFramebuffer===void 0)be.setupRenderTarget(ye);else if(Tt.__hasExternalTextures)be.rebindTextures(ye,Ne.get(ye.texture).__webglTexture,Ne.get(ye.depthTexture).__webglTexture);else if(ye.depthBuffer){const Pt=ye.depthTexture;if(Tt.__boundDepthTexture!==Pt){if(Pt!==null&&Ne.has(Pt)&&(ye.width!==Pt.image.width||ye.height!==Pt.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");be.setupDepthRenderbuffer(ye)}}const $t=ye.texture;($t.isData3DTexture||$t.isDataArrayTexture||$t.isCompressedArrayTexture)&&(pt=!0);const Rt=Ne.get(ye).__webglFramebuffer;ye.isWebGLCubeRenderTarget?(Array.isArray(Rt[He])?Te=Rt[He][Ye]:Te=Rt[He],lt=!0):ye.samples>0&&be.useMultisampledRTT(ye)===!1?Te=Ne.get(ye).__webglMultisampledFramebuffer:Array.isArray(Rt)?Te=Rt[Ye]:Te=Rt,B.copy(ye.viewport),D.copy(ye.scissor),$=ye.scissorTest}else B.copy(te).multiplyScalar(ae).floor(),D.copy(Z).multiplyScalar(ae).floor(),$=ve;if(Ye!==0&&(Te=ot),de.bindFramebuffer(Y.FRAMEBUFFER,Te)&&Xe&&de.drawBuffers(ye,Te),de.viewport(B),de.scissor(D),de.setScissorTest($),lt){const Tt=Ne.get(ye.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_CUBE_MAP_POSITIVE_X+He,Tt.__webglTexture,Ye)}else if(pt){const Tt=He;for(let $t=0;$t<ye.textures.length;$t++){const Rt=Ne.get(ye.textures[$t]);Y.framebufferTextureLayer(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0+$t,Rt.__webglTexture,Ye,Tt)}}else if(ye!==null&&Ye!==0){const Tt=Ne.get(ye.texture);Y.framebufferTexture2D(Y.FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,Tt.__webglTexture,Ye)}U=-1},this.readRenderTargetPixels=function(ye,He,Ye,Xe,Te,lt,pt,at=0){if(!(ye&&ye.isWebGLRenderTarget)){Ua("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Tt=Ne.get(ye).__webglFramebuffer;if(ye.isWebGLCubeRenderTarget&&pt!==void 0&&(Tt=Tt[pt]),Tt){de.bindFramebuffer(Y.FRAMEBUFFER,Tt);try{const $t=ye.textures[at],Rt=$t.format,Pt=$t.type;if(!se.textureFormatReadable(Rt)){Ua("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!se.textureTypeReadable(Pt)){Ua("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}He>=0&&He<=ye.width-Xe&&Ye>=0&&Ye<=ye.height-Te&&(ye.textures.length>1&&Y.readBuffer(Y.COLOR_ATTACHMENT0+at),Y.readPixels(He,Ye,Xe,Te,qe.convert(Rt),qe.convert(Pt),lt))}finally{const $t=E!==null?Ne.get(E).__webglFramebuffer:null;de.bindFramebuffer(Y.FRAMEBUFFER,$t)}}},this.readRenderTargetPixelsAsync=async function(ye,He,Ye,Xe,Te,lt,pt,at=0){if(!(ye&&ye.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Tt=Ne.get(ye).__webglFramebuffer;if(ye.isWebGLCubeRenderTarget&&pt!==void 0&&(Tt=Tt[pt]),Tt)if(He>=0&&He<=ye.width-Xe&&Ye>=0&&Ye<=ye.height-Te){de.bindFramebuffer(Y.FRAMEBUFFER,Tt);const $t=ye.textures[at],Rt=$t.format,Pt=$t.type;if(!se.textureFormatReadable(Rt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!se.textureTypeReadable(Pt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const sn=Y.createBuffer();Y.bindBuffer(Y.PIXEL_PACK_BUFFER,sn),Y.bufferData(Y.PIXEL_PACK_BUFFER,lt.byteLength,Y.STREAM_READ),ye.textures.length>1&&Y.readBuffer(Y.COLOR_ATTACHMENT0+at),Y.readPixels(He,Ye,Xe,Te,qe.convert(Rt),qe.convert(Pt),0);const Zt=E!==null?Ne.get(E).__webglFramebuffer:null;de.bindFramebuffer(Y.FRAMEBUFFER,Zt);const un=Y.fenceSync(Y.SYNC_GPU_COMMANDS_COMPLETE,0);return Y.flush(),await vbe(Y,un,4),Y.bindBuffer(Y.PIXEL_PACK_BUFFER,sn),Y.getBufferSubData(Y.PIXEL_PACK_BUFFER,0,lt),Y.deleteBuffer(sn),Y.deleteSync(un),lt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(ye,He=null,Ye=0){const Xe=Math.pow(2,-Ye),Te=Math.floor(ye.image.width*Xe),lt=Math.floor(ye.image.height*Xe),pt=He!==null?He.x:0,at=He!==null?He.y:0;be.setTexture2D(ye,0),Y.copyTexSubImage2D(Y.TEXTURE_2D,Ye,0,0,pt,at,Te,lt),de.unbindTexture()};const Ge=Y.createFramebuffer(),zt=Y.createFramebuffer();this.copyTextureToTexture=function(ye,He,Ye=null,Xe=null,Te=0,lt=null){lt===null&&(Te!==0?(Nv("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),lt=Te,Te=0):lt=0);let pt,at,Tt,$t,Rt,Pt,sn,Zt,un;const kn=ye.isCompressedTexture?ye.mipmaps[lt]:ye.image;if(Ye!==null)pt=Ye.max.x-Ye.min.x,at=Ye.max.y-Ye.min.y,Tt=Ye.isBox3?Ye.max.z-Ye.min.z:1,$t=Ye.min.x,Rt=Ye.min.y,Pt=Ye.isBox3?Ye.min.z:0;else{const sr=Math.pow(2,-Te);pt=Math.floor(kn.width*sr),at=Math.floor(kn.height*sr),ye.isDataArrayTexture?Tt=kn.depth:ye.isData3DTexture?Tt=Math.floor(kn.depth*sr):Tt=1,$t=0,Rt=0,Pt=0}Xe!==null?(sn=Xe.x,Zt=Xe.y,un=Xe.z):(sn=0,Zt=0,un=0);const Dn=qe.convert(He.format),Xt=qe.convert(He.type);let mn;He.isData3DTexture?(be.setTexture3D(He,0),mn=Y.TEXTURE_3D):He.isDataArrayTexture||He.isCompressedArrayTexture?(be.setTexture2DArray(He,0),mn=Y.TEXTURE_2D_ARRAY):(be.setTexture2D(He,0),mn=Y.TEXTURE_2D),Y.pixelStorei(Y.UNPACK_FLIP_Y_WEBGL,He.flipY),Y.pixelStorei(Y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,He.premultiplyAlpha),Y.pixelStorei(Y.UNPACK_ALIGNMENT,He.unpackAlignment);const fn=Y.getParameter(Y.UNPACK_ROW_LENGTH),Gr=Y.getParameter(Y.UNPACK_IMAGE_HEIGHT),pn=Y.getParameter(Y.UNPACK_SKIP_PIXELS),Rn=Y.getParameter(Y.UNPACK_SKIP_ROWS),ia=Y.getParameter(Y.UNPACK_SKIP_IMAGES);Y.pixelStorei(Y.UNPACK_ROW_LENGTH,kn.width),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,kn.height),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,$t),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,Rt),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,Pt);const Sn=ye.isDataArrayTexture||ye.isData3DTexture,va=He.isDataArrayTexture||He.isData3DTexture;if(ye.isDepthTexture){const sr=Ne.get(ye),ma=Ne.get(He),xt=Ne.get(sr.__renderTarget),Ft=Ne.get(ma.__renderTarget);de.bindFramebuffer(Y.READ_FRAMEBUFFER,xt.__webglFramebuffer),de.bindFramebuffer(Y.DRAW_FRAMEBUFFER,Ft.__webglFramebuffer);for(let bn=0;bn<Tt;bn++)Sn&&(Y.framebufferTextureLayer(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Ne.get(ye).__webglTexture,Te,Pt+bn),Y.framebufferTextureLayer(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Ne.get(He).__webglTexture,lt,un+bn)),Y.blitFramebuffer($t,Rt,pt,at,sn,Zt,pt,at,Y.DEPTH_BUFFER_BIT,Y.NEAREST);de.bindFramebuffer(Y.READ_FRAMEBUFFER,null),de.bindFramebuffer(Y.DRAW_FRAMEBUFFER,null)}else if(Te!==0||ye.isRenderTargetTexture||Ne.has(ye)){const sr=Ne.get(ye),ma=Ne.get(He);de.bindFramebuffer(Y.READ_FRAMEBUFFER,Ge),de.bindFramebuffer(Y.DRAW_FRAMEBUFFER,zt);for(let xt=0;xt<Tt;xt++)Sn?Y.framebufferTextureLayer(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,sr.__webglTexture,Te,Pt+xt):Y.framebufferTexture2D(Y.READ_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,sr.__webglTexture,Te),va?Y.framebufferTextureLayer(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,ma.__webglTexture,lt,un+xt):Y.framebufferTexture2D(Y.DRAW_FRAMEBUFFER,Y.COLOR_ATTACHMENT0,Y.TEXTURE_2D,ma.__webglTexture,lt),Te!==0?Y.blitFramebuffer($t,Rt,pt,at,sn,Zt,pt,at,Y.COLOR_BUFFER_BIT,Y.NEAREST):va?Y.copyTexSubImage3D(mn,lt,sn,Zt,un+xt,$t,Rt,pt,at):Y.copyTexSubImage2D(mn,lt,sn,Zt,$t,Rt,pt,at);de.bindFramebuffer(Y.READ_FRAMEBUFFER,null),de.bindFramebuffer(Y.DRAW_FRAMEBUFFER,null)}else va?ye.isDataTexture||ye.isData3DTexture?Y.texSubImage3D(mn,lt,sn,Zt,un,pt,at,Tt,Dn,Xt,kn.data):He.isCompressedArrayTexture?Y.compressedTexSubImage3D(mn,lt,sn,Zt,un,pt,at,Tt,Dn,kn.data):Y.texSubImage3D(mn,lt,sn,Zt,un,pt,at,Tt,Dn,Xt,kn):ye.isDataTexture?Y.texSubImage2D(Y.TEXTURE_2D,lt,sn,Zt,pt,at,Dn,Xt,kn.data):ye.isCompressedTexture?Y.compressedTexSubImage2D(Y.TEXTURE_2D,lt,sn,Zt,kn.width,kn.height,Dn,kn.data):Y.texSubImage2D(Y.TEXTURE_2D,lt,sn,Zt,pt,at,Dn,Xt,kn);Y.pixelStorei(Y.UNPACK_ROW_LENGTH,fn),Y.pixelStorei(Y.UNPACK_IMAGE_HEIGHT,Gr),Y.pixelStorei(Y.UNPACK_SKIP_PIXELS,pn),Y.pixelStorei(Y.UNPACK_SKIP_ROWS,Rn),Y.pixelStorei(Y.UNPACK_SKIP_IMAGES,ia),lt===0&&He.generateMipmaps&&Y.generateMipmap(mn),de.unbindTexture()},this.initRenderTarget=function(ye){Ne.get(ye).__webglFramebuffer===void 0&&be.setupRenderTarget(ye)},this.initTexture=function(ye){ye.isCubeTexture?be.setTextureCube(ye,0):ye.isData3DTexture?be.setTexture3D(ye,0):ye.isDataArrayTexture||ye.isCompressedArrayTexture?be.setTexture2DArray(ye,0):be.setTexture2D(ye,0),de.unbindTexture()},this.resetState=function(){j=0,P=0,E=null,de.reset(),Ee.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return kc}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=cr._getDrawingBufferColorSpace(e),n.unpackColorSpace=cr._getUnpackColorSpace()}};const K8={type:"change"},YF={type:"start"},bY={type:"end"},AS=new VF,X8=new ih,Jwe=Math.cos(70*Sbe.DEG2RAD),ci=new ft,Ws=2*Math.PI,Lr={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},yP=1e-6;class eSe extends dxe{constructor(e,n=null){super(e,n),this.state=Lr.NONE,this.target=new ft,this.cursor=new ft,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Xg.ROTATE,MIDDLE:Xg.DOLLY,RIGHT:Xg.PAN},this.touches={ONE:Ig.ROTATE,TWO:Ig.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new ft,this._lastQuaternion=new Lf,this._lastTargetPosition=new ft,this._quat=new Lf().setFromUnitVectors(e.up,new ft(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new _8,this._sphericalDelta=new _8,this._scale=1,this._panOffset=new ft,this._rotateStart=new Un,this._rotateEnd=new Un,this._rotateDelta=new Un,this._panStart=new Un,this._panEnd=new Un,this._panDelta=new Un,this._dollyStart=new Un,this._dollyEnd=new Un,this._dollyDelta=new Un,this._dollyDirection=new ft,this._mouse=new Un,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=nSe.bind(this),this._onPointerDown=tSe.bind(this),this._onPointerUp=rSe.bind(this),this._onContextMenu=uSe.bind(this),this._onMouseWheel=sSe.bind(this),this._onKeyDown=oSe.bind(this),this._onTouchStart=lSe.bind(this),this._onTouchMove=cSe.bind(this),this._onMouseDown=aSe.bind(this),this._onMouseMove=iSe.bind(this),this._interceptControlDown=dSe.bind(this),this._interceptControlUp=hSe.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(K8),this.update(),this.state=Lr.NONE}update(e=null){const n=this.object.position;ci.copy(n).sub(this.target),ci.applyQuaternion(this._quat),this._spherical.setFromVector3(ci),this.autoRotate&&this.state===Lr.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let r=this.minAzimuthAngle,a=this.maxAzimuthAngle;isFinite(r)&&isFinite(a)&&(r<-Math.PI?r+=Ws:r>Math.PI&&(r-=Ws),a<-Math.PI?a+=Ws:a>Math.PI&&(a-=Ws),r<=a?this._spherical.theta=Math.max(r,Math.min(a,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+a)/2?Math.max(r,this._spherical.theta):Math.min(a,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(ci.setFromSpherical(this._spherical),ci.applyQuaternion(this._quatInverse),n.copy(this.target).add(ci),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){const l=ci.length();o=this._clampDistance(l*this._scale);const c=l-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),s=!!c}else if(this.object.isOrthographicCamera){const l=new ft(this._mouse.x,this._mouse.y,0);l.unproject(this.object);const c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=c!==this.object.zoom;const u=new ft(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(l),this.object.updateMatrixWorld(),o=ci.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(AS.origin.copy(this.object.position),AS.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(AS.direction))<Jwe?this.object.lookAt(this.target):(X8.setFromNormalAndCoplanarPoint(this.object.up,this.target),AS.intersectPlane(X8,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>yP||8*(1-this._lastQuaternion.dot(this.object.quaternion))>yP||this._lastTargetPosition.distanceToSquared(this.target)>yP?(this.dispatchEvent(K8),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Ws/60*this.autoRotateSpeed*e:Ws/60/60*this.autoRotateSpeed}_getZoomScale(e){const n=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*n)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,n){ci.setFromMatrixColumn(n,0),ci.multiplyScalar(-e),this._panOffset.add(ci)}_panUp(e,n){this.screenSpacePanning===!0?ci.setFromMatrixColumn(n,1):(ci.setFromMatrixColumn(n,0),ci.crossVectors(this.object.up,ci)),ci.multiplyScalar(e),this._panOffset.add(ci)}_pan(e,n){const r=this.domElement;if(this.object.isPerspectiveCamera){const a=this.object.position;ci.copy(a).sub(this.target);let s=ci.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/r.clientHeight,this.object.matrix),this._panUp(2*n*s/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(n*(this.object.top-this.object.bottom)/this.object.zoom/r.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,n){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const r=this.domElement.getBoundingClientRect(),a=e-r.left,s=n-r.top,o=r.width,l=r.height;this._mouse.x=a/o*2-1,this._mouse.y=-(s/l)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ws*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ws*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let n=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(Ws*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),n=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-Ws*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),n=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(Ws*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),n=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-Ws*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),a=.5*(e.pageY+n.y);this._rotateStart.set(r,a)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),a=.5*(e.pageY+n.y);this._panStart.set(r,a)}}_handleTouchStartDolly(e){const n=this._getSecondPointerPosition(e),r=e.pageX-n.x,a=e.pageY-n.y,s=Math.sqrt(r*r+a*a);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const r=this._getSecondPointerPosition(e),a=.5*(e.pageX+r.x),s=.5*(e.pageY+r.y);this._rotateEnd.set(a,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const n=this.domElement;this._rotateLeft(Ws*this._rotateDelta.x/n.clientHeight),this._rotateUp(Ws*this._rotateDelta.y/n.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),r=.5*(e.pageX+n.x),a=.5*(e.pageY+n.y);this._panEnd.set(r,a)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const n=this._getSecondPointerPosition(e),r=e.pageX-n.x,a=e.pageY-n.y,s=Math.sqrt(r*r+a*a);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+n.x)*.5,l=(e.pageY+n.y)*.5;this._updateZoomParameters(o,l)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId){this._pointers.splice(n,1);return}}_isTrackingPointer(e){for(let n=0;n<this._pointers.length;n++)if(this._pointers[n]==e.pointerId)return!0;return!1}_trackPointer(e){let n=this._pointerPositions[e.pointerId];n===void 0&&(n=new Un,this._pointerPositions[e.pointerId]=n),n.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const n=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[n]}_customWheelEvent(e){const n=e.deltaMode,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(n){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}}function tSe(t){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(t)&&(this._addPointer(t),t.pointerType==="touch"?this._onTouchStart(t):this._onMouseDown(t)))}function nSe(t){this.enabled!==!1&&(t.pointerType==="touch"?this._onTouchMove(t):this._onMouseMove(t))}function rSe(t){switch(this._removePointer(t),this._pointers.length){case 0:this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(bY),this.state=Lr.NONE;break;case 1:const e=this._pointers[0],n=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:n.x,pageY:n.y});break}}function aSe(t){let e;switch(t.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Xg.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(t),this.state=Lr.DOLLY;break;case Xg.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Lr.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Lr.ROTATE}break;case Xg.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(t),this.state=Lr.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(t),this.state=Lr.PAN}break;default:this.state=Lr.NONE}this.state!==Lr.NONE&&this.dispatchEvent(YF)}function iSe(t){switch(this.state){case Lr.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(t);break;case Lr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(t);break;case Lr.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(t);break}}function sSe(t){this.enabled===!1||this.enableZoom===!1||this.state!==Lr.NONE||(t.preventDefault(),this.dispatchEvent(YF),this._handleMouseWheel(this._customWheelEvent(t)),this.dispatchEvent(bY))}function oSe(t){this.enabled!==!1&&this._handleKeyDown(t)}function lSe(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case Ig.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(t),this.state=Lr.TOUCH_ROTATE;break;case Ig.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(t),this.state=Lr.TOUCH_PAN;break;default:this.state=Lr.NONE}break;case 2:switch(this.touches.TWO){case Ig.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(t),this.state=Lr.TOUCH_DOLLY_PAN;break;case Ig.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(t),this.state=Lr.TOUCH_DOLLY_ROTATE;break;default:this.state=Lr.NONE}break;default:this.state=Lr.NONE}this.state!==Lr.NONE&&this.dispatchEvent(YF)}function cSe(t){switch(this._trackPointer(t),this.state){case Lr.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(t),this.update();break;case Lr.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(t),this.update();break;case Lr.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(t),this.update();break;case Lr.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(t),this.update();break;default:this.state=Lr.NONE}}function uSe(t){this.enabled!==!1&&t.preventDefault()}function dSe(t){t.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hSe(t){t.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function mSe(t,e=!1){const n=t[0].index!==null,r=new Set(Object.keys(t[0].attributes)),a=new Set(Object.keys(t[0].morphAttributes)),s={},o={},l=t[0].morphTargetsRelative,c=new wl;let u=0;for(let d=0;d<t.length;++d){const h=t[d];let f=0;if(n!==(h.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in h.attributes){if(!r.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;s[p]===void 0&&(s[p]=[]),s[p].push(h.attributes[p]),f++}if(f!==r.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+". Make sure all geometries have the same number of attributes."),null;if(l!==h.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in h.morphAttributes){if(!a.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+". .morphAttributes must be consistent throughout all geometries."),null;o[p]===void 0&&(o[p]=[]),o[p].push(h.morphAttributes[p])}if(e){let p;if(n)p=h.index.count;else if(h.attributes.position!==void 0)p=h.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+d+". The geometry must have either an index or a position attribute"),null;c.addGroup(u,p,d),u+=p}}if(n){let d=0;const h=[];for(let f=0;f<t.length;++f){const p=t[f].index;for(let x=0;x<p.count;++x)h.push(p.getX(x)+d);d+=t[f].attributes.position.count}c.setIndex(h)}for(const d in s){const h=Y8(s[d]);if(!h)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+d+" attribute."),null;c.setAttribute(d,h)}for(const d in o){const h=o[d][0].length;if(h===0)break;c.morphAttributes=c.morphAttributes||{},c.morphAttributes[d]=[];for(let f=0;f<h;++f){const p=[];for(let v=0;v<o[d].length;++v)p.push(o[d][v][f]);const x=Y8(p);if(!x)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+d+" morphAttribute."),null;c.morphAttributes[d].push(x)}}return c}function Y8(t){let e,n,r,a=-1,s=0;for(let u=0;u<t.length;++u){const d=t[u];if(e===void 0&&(e=d.array.constructor),e!==d.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(n===void 0&&(n=d.itemSize),n!==d.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(r===void 0&&(r=d.normalized),r!==d.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(a===-1&&(a=d.gpuType),a!==d.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=d.count*n}const o=new e(s),l=new Ds(o,n,r);let c=0;for(let u=0;u<t.length;++u){const d=t[u];if(d.isInterleavedBufferAttribute){const h=c/n;for(let f=0,p=d.count;f<p;f++)for(let x=0;x<n;x++){const v=d.getComponent(f,x);l.setComponent(f+h,x,v)}}else o.set(d.array,c);c+=d.count*n}return a!==void 0&&(l.gpuType=a),l}class fSe extends XF{constructor(e){super(e)}load(e,n,r,a){const s=this,o=new ixe(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{n(s.parse(l))}catch(c){a?a(c):console.error(c),s.manager.itemError(e)}},r,a)}parse(e){function n(u){const d=new DataView(u),h=32/8*3+32/8*3*3+16/8,f=d.getUint32(80,!0);if(80+32/8+f*h===d.byteLength)return!0;const x=[115,111,108,105,100];for(let v=0;v<5;v++)if(r(x,d,v))return!1;return!0}function r(u,d,h){for(let f=0,p=u.length;f<p;f++)if(u[f]!==d.getUint8(h+f))return!1;return!0}function a(u){const d=new DataView(u),h=d.getUint32(80,!0);let f,p,x,v=!1,g,y,_,N,k;for(let U=0;U<70;U++)d.getUint32(U,!1)==1129270351&&d.getUint8(U+4)==82&&d.getUint8(U+5)==61&&(v=!0,g=new Float32Array(h*3*3),y=d.getUint8(U+6)/255,_=d.getUint8(U+7)/255,N=d.getUint8(U+8)/255,k=d.getUint8(U+9)/255);const A=84,M=50,C=new wl,j=new Float32Array(h*3*3),P=new Float32Array(h*3*3),E=new $n;for(let U=0;U<h;U++){const L=A+U*M,B=d.getFloat32(L,!0),D=d.getFloat32(L+4,!0),$=d.getFloat32(L+8,!0);if(v){const G=d.getUint16(L+48,!0);(G&32768)===0?(f=(G&31)/31,p=(G>>5&31)/31,x=(G>>10&31)/31):(f=y,p=_,x=N)}for(let G=1;G<=3;G++){const z=L+G*12,W=U*3*3+(G-1)*3;j[W]=d.getFloat32(z,!0),j[W+1]=d.getFloat32(z+4,!0),j[W+2]=d.getFloat32(z+8,!0),P[W]=B,P[W+1]=D,P[W+2]=$,v&&(E.setRGB(f,p,x,ko),g[W]=E.r,g[W+1]=E.g,g[W+2]=E.b)}}return C.setAttribute("position",new Ds(j,3)),C.setAttribute("normal",new Ds(P,3)),v&&(C.setAttribute("color",new Ds(g,3)),C.hasColors=!0,C.alpha=k),C}function s(u){const d=new wl,h=/solid([\s\S]*?)endsolid/g,f=/facet([\s\S]*?)endfacet/g,p=/solid\s(.+)/;let x=0;const v=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,g=new RegExp("vertex"+v+v+v,"g"),y=new RegExp("normal"+v+v+v,"g"),_=[],N=[],k=[],A=new ft;let M,C=0,j=0,P=0;for(;(M=h.exec(u))!==null;){j=P;const E=M[0],U=(M=p.exec(E))!==null?M[1]:"";for(k.push(U);(M=f.exec(E))!==null;){let D=0,$=0;const G=M[0];for(;(M=y.exec(G))!==null;)A.x=parseFloat(M[1]),A.y=parseFloat(M[2]),A.z=parseFloat(M[3]),$++;for(;(M=g.exec(G))!==null;)_.push(parseFloat(M[1]),parseFloat(M[2]),parseFloat(M[3])),N.push(A.x,A.y,A.z),D++,P++;$!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+x),D!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+x),x++}const L=j,B=P-j;d.userData.groupNames=k,d.addGroup(L,B,C),C++}return d.setAttribute("position",new jo(_,3)),d.setAttribute("normal",new jo(N,3)),d}function o(u){return typeof u!="string"?new TextDecoder().decode(u):u}function l(u){if(typeof u=="string"){const d=new Uint8Array(u.length);for(let h=0;h<u.length;h++)d[h]=u.charCodeAt(h)&255;return d.buffer||d}else return u}const c=l(e);return n(c)?a(c):s(o(e))}}function TS(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var vP={exports:{}};var Q8;function pSe(){return Q8||(Q8=1,(function(t,e){(function(n){t.exports=n()})(function(){return(function n(r,a,s){function o(u,d){if(!a[u]){if(!r[u]){var h=typeof TS=="function"&&TS;if(!d&&h)return h(u,!0);if(l)return l(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var p=a[u]={exports:{}};r[u][0].call(p.exports,function(x){var v=r[u][1][x];return o(v||x)},p,p.exports,n,r,a,s)}return a[u].exports}for(var l=typeof TS=="function"&&TS,c=0;c<s.length;c++)o(s[c]);return o})({1:[function(n,r,a){var s=n("./utils"),o=n("./support"),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a.encode=function(c){for(var u,d,h,f,p,x,v,g=[],y=0,_=c.length,N=_,k=s.getTypeOf(c)!=="string";y<c.length;)N=_-y,h=k?(u=c[y++],d=y<_?c[y++]:0,y<_?c[y++]:0):(u=c.charCodeAt(y++),d=y<_?c.charCodeAt(y++):0,y<_?c.charCodeAt(y++):0),f=u>>2,p=(3&u)<<4|d>>4,x=1<N?(15&d)<<2|h>>6:64,v=2<N?63&h:64,g.push(l.charAt(f)+l.charAt(p)+l.charAt(x)+l.charAt(v));return g.join("")},a.decode=function(c){var u,d,h,f,p,x,v=0,g=0,y="data:";if(c.substr(0,y.length)===y)throw new Error("Invalid base64 input, it looks like a data url.");var _,N=3*(c=c.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(c.charAt(c.length-1)===l.charAt(64)&&N--,c.charAt(c.length-2)===l.charAt(64)&&N--,N%1!=0)throw new Error("Invalid base64 input, bad content length.");for(_=o.uint8array?new Uint8Array(0|N):new Array(0|N);v<c.length;)u=l.indexOf(c.charAt(v++))<<2|(f=l.indexOf(c.charAt(v++)))>>4,d=(15&f)<<4|(p=l.indexOf(c.charAt(v++)))>>2,h=(3&p)<<6|(x=l.indexOf(c.charAt(v++))),_[g++]=u,p!==64&&(_[g++]=d),x!==64&&(_[g++]=h);return _}},{"./support":30,"./utils":32}],2:[function(n,r,a){var s=n("./external"),o=n("./stream/DataWorker"),l=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function u(d,h,f,p,x){this.compressedSize=d,this.uncompressedSize=h,this.crc32=f,this.compression=p,this.compressedContent=x}u.prototype={getContentWorker:function(){var d=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return d.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),d},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},u.createWorkerFrom=function(d,h,f){return d.pipe(new l).pipe(new c("uncompressedSize")).pipe(h.compressWorker(f)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=u},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var s=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var s=n("./utils"),o=(function(){for(var l,c=[],u=0;u<256;u++){l=u;for(var d=0;d<8;d++)l=1&l?3988292384^l>>>1:l>>>1;c[u]=l}return c})();r.exports=function(l,c){return l!==void 0&&l.length?s.getTypeOf(l)!=="string"?(function(u,d,h,f){var p=o,x=f+h;u^=-1;for(var v=f;v<x;v++)u=u>>>8^p[255&(u^d[v])];return-1^u})(0|c,l,l.length,0):(function(u,d,h,f){var p=o,x=f+h;u^=-1;for(var v=f;v<x;v++)u=u>>>8^p[255&(u^d.charCodeAt(v))];return-1^u})(0|c,l,l.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,a){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),l=n("./utils"),c=n("./stream/GenericWorker"),u=s?"uint8array":"array";function d(h,f){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=f,this.meta={}}a.magic="\b\0",l.inherits(d,c),d.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(l.transformTo(u,h.data),!1)},d.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},d.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},d.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(f){h.push({data:f,meta:h.meta})}},a.compressWorker=function(h){return new d("Deflate",h)},a.uncompressWorker=function(){return new d("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function s(p,x){var v,g="";for(v=0;v<x;v++)g+=String.fromCharCode(255&p),p>>>=8;return g}function o(p,x,v,g,y,_){var N,k,A=p.file,M=p.compression,C=_!==u.utf8encode,j=l.transformTo("string",_(A.name)),P=l.transformTo("string",u.utf8encode(A.name)),E=A.comment,U=l.transformTo("string",_(E)),L=l.transformTo("string",u.utf8encode(E)),B=P.length!==A.name.length,D=L.length!==E.length,$="",G="",z="",W=A.dir,X=A.date,ae={crc32:0,compressedSize:0,uncompressedSize:0};x&&!v||(ae.crc32=p.crc32,ae.compressedSize=p.compressedSize,ae.uncompressedSize=p.uncompressedSize);var H=0;x&&(H|=8),C||!B&&!D||(H|=2048);var K=0,te=0;W&&(K|=16),y==="UNIX"?(te=798,K|=(function(ve,ce){var ee=ve;return ve||(ee=ce?16893:33204),(65535&ee)<<16})(A.unixPermissions,W)):(te=20,K|=(function(ve){return 63&(ve||0)})(A.dosPermissions)),N=X.getUTCHours(),N<<=6,N|=X.getUTCMinutes(),N<<=5,N|=X.getUTCSeconds()/2,k=X.getUTCFullYear()-1980,k<<=4,k|=X.getUTCMonth()+1,k<<=5,k|=X.getUTCDate(),B&&(G=s(1,1)+s(d(j),4)+P,$+="up"+s(G.length,2)+G),D&&(z=s(1,1)+s(d(U),4)+L,$+="uc"+s(z.length,2)+z);var Z="";return Z+=`
  3839. \0`,Z+=s(H,2),Z+=M.magic,Z+=s(N,2),Z+=s(k,2),Z+=s(ae.crc32,4),Z+=s(ae.compressedSize,4),Z+=s(ae.uncompressedSize,4),Z+=s(j.length,2),Z+=s($.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Z+j+$,dirRecord:h.CENTRAL_FILE_HEADER+s(te,2)+Z+s(U.length,2)+"\0\0\0\0"+s(K,4)+s(g,4)+j+$+U}}var l=n("../utils"),c=n("../stream/GenericWorker"),u=n("../utf8"),d=n("../crc32"),h=n("../signature");function f(p,x,v,g){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=v,this.encodeFileName=g,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}l.inherits(f,c),f.prototype.push=function(p){var x=p.meta.percent||0,v=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,c.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:v?(x+100*(v-g-1))/v:100}}))},f.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var x=this.streamFiles&&!p.file.dir;if(x){var v=o(p,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:v.fileRecord,meta:{percent:0}})}else this.accumulate=!0},f.prototype.closedSource=function(p){this.accumulate=!1;var x=this.streamFiles&&!p.file.dir,v=o(p,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(v.dirRecord),x)this.push({data:(function(g){return h.DATA_DESCRIPTOR+s(g.crc32,4)+s(g.compressedSize,4)+s(g.uncompressedSize,4)})(p),meta:{percent:100}});else for(this.push({data:v.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},f.prototype.flush=function(){for(var p=this.bytesWritten,x=0;x<this.dirRecords.length;x++)this.push({data:this.dirRecords[x],meta:{percent:100}});var v=this.bytesWritten-p,g=(function(y,_,N,k,A){var M=l.transformTo("string",A(k));return h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(y,2)+s(y,2)+s(_,4)+s(N,4)+s(M.length,2)+M})(this.dirRecords.length,v,p,this.zipComment,this.encodeFileName);this.push({data:g,meta:{percent:100}})},f.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},f.prototype.registerPrevious=function(p){this._sources.push(p);var x=this;return p.on("data",function(v){x.processChunk(v)}),p.on("end",function(){x.closedSource(x.previous.streamInfo),x._sources.length?x.prepareNextSource():x.end()}),p.on("error",function(v){x.error(v)}),this},f.prototype.resume=function(){return!!c.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},f.prototype.error=function(p){var x=this._sources;if(!c.prototype.error.call(this,p))return!1;for(var v=0;v<x.length;v++)try{x[v].error(p)}catch{}return!0},f.prototype.lock=function(){c.prototype.lock.call(this);for(var p=this._sources,x=0;x<p.length;x++)p[x].lock()},r.exports=f},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,r,a){var s=n("../compressions"),o=n("./ZipFileWorker");a.generateWorker=function(l,c,u){var d=new o(c.streamFiles,u,c.platform,c.encodeFileName),h=0;try{l.forEach(function(f,p){h++;var x=(function(_,N){var k=_||N,A=s[k];if(!A)throw new Error(k+" is not a valid compression method !");return A})(p.options.compression,c.compression),v=p.options.compressionOptions||c.compressionOptions||{},g=p.dir,y=p.date;p._compressWorker(x,v).withStreamInfo("file",{name:f,dir:g,date:y,comment:p.comment||"",unixPermissions:p.unixPermissions,dosPermissions:p.dosPermissions}).pipe(d)}),d.entriesCount=h}catch(f){d.error(f)}return d}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,r,a){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var o=new s;for(var l in this)typeof this[l]!="function"&&(o[l]=this[l]);return o}}(s.prototype=n("./object")).loadAsync=n("./load"),s.support=n("./support"),s.defaults=n("./defaults"),s.version="3.10.1",s.loadAsync=function(o,l){return new s().loadAsync(o,l)},s.external=n("./external"),r.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,r,a){var s=n("./utils"),o=n("./external"),l=n("./utf8"),c=n("./zipEntries"),u=n("./stream/Crc32Probe"),d=n("./nodejsUtils");function h(f){return new o.Promise(function(p,x){var v=f.decompressed.getContentWorker().pipe(new u);v.on("error",function(g){x(g)}).on("end",function(){v.streamInfo.crc32!==f.decompressed.crc32?x(new Error("Corrupted zip : CRC32 mismatch")):p()}).resume()})}r.exports=function(f,p){var x=this;return p=s.extend(p||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:l.utf8decode}),d.isNode&&d.isStream(f)?o.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):s.prepareContent("the loaded zip file",f,!0,p.optimizedBinaryString,p.base64).then(function(v){var g=new c(p);return g.load(v),g}).then(function(v){var g=[o.Promise.resolve(v)],y=v.files;if(p.checkCRC32)for(var _=0;_<y.length;_++)g.push(h(y[_]));return o.Promise.all(g)}).then(function(v){for(var g=v.shift(),y=g.files,_=0;_<y.length;_++){var N=y[_],k=N.fileNameStr,A=s.resolve(N.fileNameStr);x.file(A,N.decompressed,{binary:!0,optimizedBinaryString:!0,date:N.date,dir:N.dir,comment:N.fileCommentStr.length?N.fileCommentStr:null,unixPermissions:N.unixPermissions,dosPermissions:N.dosPermissions,createFolders:p.createFolders}),N.dir||(x.file(A).unsafeOriginalName=k)}return g.zipComment.length&&(x.comment=g.zipComment),x})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(n,r,a){var s=n("../utils"),o=n("../stream/GenericWorker");function l(c,u){o.call(this,"Nodejs stream input adapter for "+c),this._upstreamEnded=!1,this._bindStream(u)}s.inherits(l,o),l.prototype._bindStream=function(c){var u=this;(this._stream=c).pause(),c.on("data",function(d){u.push({data:d,meta:{percent:0}})}).on("error",function(d){u.isPaused?this.generatedError=d:u.error(d)}).on("end",function(){u.isPaused?u._upstreamEnded=!0:u.end()})},l.prototype.pause=function(){return!!o.prototype.pause.call(this)&&(this._stream.pause(),!0)},l.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},r.exports=l},{"../stream/GenericWorker":28,"../utils":32}],13:[function(n,r,a){var s=n("readable-stream").Readable;function o(l,c,u){s.call(this,c),this._helper=l;var d=this;l.on("data",function(h,f){d.push(h)||d._helper.pause(),u&&u(f)}).on("error",function(h){d.emit("error",h)}).on("end",function(){d.push(null)})}n("../utils").inherits(o,s),o.prototype._read=function(){this._helper.resume()},r.exports=o},{"../utils":32,"readable-stream":16}],14:[function(n,r,a){r.exports={isNode:typeof Buffer<"u",newBufferFrom:function(s,o){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(s,o);if(typeof s=="number")throw new Error('The "data" argument must not be a number');return new Buffer(s,o)},allocBuffer:function(s){if(Buffer.alloc)return Buffer.alloc(s);var o=new Buffer(s);return o.fill(0),o},isBuffer:function(s){return Buffer.isBuffer(s)},isStream:function(s){return s&&typeof s.on=="function"&&typeof s.pause=="function"&&typeof s.resume=="function"}}},{}],15:[function(n,r,a){function s(A,M,C){var j,P=l.getTypeOf(M),E=l.extend(C||{},d);E.date=E.date||new Date,E.compression!==null&&(E.compression=E.compression.toUpperCase()),typeof E.unixPermissions=="string"&&(E.unixPermissions=parseInt(E.unixPermissions,8)),E.unixPermissions&&16384&E.unixPermissions&&(E.dir=!0),E.dosPermissions&&16&E.dosPermissions&&(E.dir=!0),E.dir&&(A=y(A)),E.createFolders&&(j=g(A))&&_.call(this,j,!0);var U=P==="string"&&E.binary===!1&&E.base64===!1;C&&C.binary!==void 0||(E.binary=!U),(M instanceof h&&M.uncompressedSize===0||E.dir||!M||M.length===0)&&(E.base64=!1,E.binary=!0,M="",E.compression="STORE",P="string");var L=null;L=M instanceof h||M instanceof c?M:x.isNode&&x.isStream(M)?new v(A,M):l.prepareContent(A,M,E.binary,E.optimizedBinaryString,E.base64);var B=new f(A,L,E);this.files[A]=B}var o=n("./utf8"),l=n("./utils"),c=n("./stream/GenericWorker"),u=n("./stream/StreamHelper"),d=n("./defaults"),h=n("./compressedObject"),f=n("./zipObject"),p=n("./generate"),x=n("./nodejsUtils"),v=n("./nodejs/NodejsStreamInputAdapter"),g=function(A){A.slice(-1)==="/"&&(A=A.substring(0,A.length-1));var M=A.lastIndexOf("/");return 0<M?A.substring(0,M):""},y=function(A){return A.slice(-1)!=="/"&&(A+="/"),A},_=function(A,M){return M=M!==void 0?M:d.createFolders,A=y(A),this.files[A]||s.call(this,A,null,{dir:!0,createFolders:M}),this.files[A]};function N(A){return Object.prototype.toString.call(A)==="[object RegExp]"}var k={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(A){var M,C,j;for(M in this.files)j=this.files[M],(C=M.slice(this.root.length,M.length))&&M.slice(0,this.root.length)===this.root&&A(C,j)},filter:function(A){var M=[];return this.forEach(function(C,j){A(C,j)&&M.push(j)}),M},file:function(A,M,C){if(arguments.length!==1)return A=this.root+A,s.call(this,A,M,C),this;if(N(A)){var j=A;return this.filter(function(E,U){return!U.dir&&j.test(E)})}var P=this.files[this.root+A];return P&&!P.dir?P:null},folder:function(A){if(!A)return this;if(N(A))return this.filter(function(P,E){return E.dir&&A.test(P)});var M=this.root+A,C=_.call(this,M),j=this.clone();return j.root=C.name,j},remove:function(A){A=this.root+A;var M=this.files[A];if(M||(A.slice(-1)!=="/"&&(A+="/"),M=this.files[A]),M&&!M.dir)delete this.files[A];else for(var C=this.filter(function(P,E){return E.name.slice(0,A.length)===A}),j=0;j<C.length;j++)delete this.files[C[j].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(A){var M,C={};try{if((C=l.extend(A||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:o.utf8encode})).type=C.type.toLowerCase(),C.compression=C.compression.toUpperCase(),C.type==="binarystring"&&(C.type="string"),!C.type)throw new Error("No output type specified.");l.checkSupport(C.type),C.platform!=="darwin"&&C.platform!=="freebsd"&&C.platform!=="linux"&&C.platform!=="sunos"||(C.platform="UNIX"),C.platform==="win32"&&(C.platform="DOS");var j=C.comment||this.comment||"";M=p.generateWorker(this,C,j)}catch(P){(M=new c("error")).error(P)}return new u(M,C.type||"string",C.mimeType)},generateAsync:function(A,M){return this.generateInternalStream(A).accumulate(M)},generateNodeStream:function(A,M){return(A=A||{}).type||(A.type="nodebuffer"),this.generateInternalStream(A).toNodejsStream(M)}};r.exports=k},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(n,r,a){r.exports=n("stream")},{stream:void 0}],17:[function(n,r,a){var s=n("./DataReader");function o(l){s.call(this,l);for(var c=0;c<this.data.length;c++)l[c]=255&l[c]}n("../utils").inherits(o,s),o.prototype.byteAt=function(l){return this.data[this.zero+l]},o.prototype.lastIndexOfSignature=function(l){for(var c=l.charCodeAt(0),u=l.charCodeAt(1),d=l.charCodeAt(2),h=l.charCodeAt(3),f=this.length-4;0<=f;--f)if(this.data[f]===c&&this.data[f+1]===u&&this.data[f+2]===d&&this.data[f+3]===h)return f-this.zero;return-1},o.prototype.readAndCheckSignature=function(l){var c=l.charCodeAt(0),u=l.charCodeAt(1),d=l.charCodeAt(2),h=l.charCodeAt(3),f=this.readData(4);return c===f[0]&&u===f[1]&&d===f[2]&&h===f[3]},o.prototype.readData=function(l){if(this.checkOffset(l),l===0)return[];var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./DataReader":18}],18:[function(n,r,a){var s=n("../utils");function o(l){this.data=l,this.length=l.length,this.index=0,this.zero=0}o.prototype={checkOffset:function(l){this.checkIndex(this.index+l)},checkIndex:function(l){if(this.length<this.zero+l||l<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+l+"). Corrupted zip ?")},setIndex:function(l){this.checkIndex(l),this.index=l},skip:function(l){this.setIndex(this.index+l)},byteAt:function(){},readInt:function(l){var c,u=0;for(this.checkOffset(l),c=this.index+l-1;c>=this.index;c--)u=(u<<8)+this.byteAt(c);return this.index+=l,u},readString:function(l){return s.transformTo("string",this.readData(l))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var l=this.readInt(4);return new Date(Date.UTC(1980+(l>>25&127),(l>>21&15)-1,l>>16&31,l>>11&31,l>>5&63,(31&l)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,a){var s=n("./Uint8ArrayReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var s=n("./DataReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.byteAt=function(l){return this.data.charCodeAt(this.zero+l)},o.prototype.lastIndexOfSignature=function(l){return this.data.lastIndexOf(l)-this.zero},o.prototype.readAndCheckSignature=function(l){return l===this.readData(4)},o.prototype.readData=function(l){this.checkOffset(l);var c=this.data.slice(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var s=n("./ArrayReader");function o(l){s.call(this,l)}n("../utils").inherits(o,s),o.prototype.readData=function(l){if(this.checkOffset(l),l===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+l);return this.index+=l,c},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var s=n("../utils"),o=n("../support"),l=n("./ArrayReader"),c=n("./StringReader"),u=n("./NodeBufferReader"),d=n("./Uint8ArrayReader");r.exports=function(h){var f=s.getTypeOf(h);return s.checkSupport(f),f!=="string"||o.uint8array?f==="nodebuffer"?new u(h):o.uint8array?new d(s.transformTo("uint8array",h)):new l(s.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var s=n("./GenericWorker"),o=n("../utils");function l(c){s.call(this,"ConvertWorker to "+c),this.destType=c}o.inherits(l,s),l.prototype.processChunk=function(c){this.push({data:o.transformTo(this.destType,c.data),meta:c.meta})},r.exports=l},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var s=n("./GenericWorker"),o=n("../crc32");function l(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(l,s),l.prototype.processChunk=function(c){this.streamInfo.crc32=o(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=l},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var s=n("../utils"),o=n("./GenericWorker");function l(c){o.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}s.inherits(l,o),l.prototype.processChunk=function(c){if(c){var u=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=u+c.data.length}o.prototype.processChunk.call(this,c)},r.exports=l},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var s=n("../utils"),o=n("./GenericWorker");function l(c){o.call(this,"DataWorker");var u=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(d){u.dataIsReady=!0,u.data=d,u.max=d&&d.length||0,u.type=s.getTypeOf(d),u.isPaused||u._tickAndRepeat()},function(d){u.error(d)})}s.inherits(l,o),l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},l.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},l.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},l.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,u=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,u);break;case"uint8array":c=this.data.subarray(this.index,u);break;case"array":case"nodebuffer":c=this.data.slice(this.index,u)}return this.index=u,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=l},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,l){return this._listeners[o].push(l),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,l){if(this._listeners[o])for(var c=0;c<this._listeners[o].length;c++)this._listeners[o][c].call(this,l)},pipe:function(o){return o.registerPrevious(this)},registerPrevious:function(o){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=o.streamInfo,this.mergeStreamInfo(),this.previous=o;var l=this;return o.on("data",function(c){l.processChunk(c)}),o.on("end",function(){l.end()}),o.on("error",function(c){l.error(c)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var o=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),o=!0),this.previous&&this.previous.resume(),!o},flush:function(){},processChunk:function(o){this.push(o)},withStreamInfo:function(o,l){return this.extraStreamInfo[o]=l,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var o in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,o)&&(this.streamInfo[o]=this.extraStreamInfo[o])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var o="Worker "+this.name;return this.previous?this.previous+" -> "+o:o}},r.exports=s},{}],29:[function(n,r,a){var s=n("../utils"),o=n("./ConvertWorker"),l=n("./GenericWorker"),c=n("../base64"),u=n("../support"),d=n("../external"),h=null;if(u.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function f(x,v){return new d.Promise(function(g,y){var _=[],N=x._internalType,k=x._outputType,A=x._mimeType;x.on("data",function(M,C){_.push(M),v&&v(C)}).on("error",function(M){_=[],y(M)}).on("end",function(){try{var M=(function(C,j,P){switch(C){case"blob":return s.newBlob(s.transformTo("arraybuffer",j),P);case"base64":return c.encode(j);default:return s.transformTo(C,j)}})(k,(function(C,j){var P,E=0,U=null,L=0;for(P=0;P<j.length;P++)L+=j[P].length;switch(C){case"string":return j.join("");case"array":return Array.prototype.concat.apply([],j);case"uint8array":for(U=new Uint8Array(L),P=0;P<j.length;P++)U.set(j[P],E),E+=j[P].length;return U;case"nodebuffer":return Buffer.concat(j);default:throw new Error("concat : unsupported type '"+C+"'")}})(N,_),A);g(M)}catch(C){y(C)}_=[]}).resume()})}function p(x,v,g){var y=v;switch(v){case"blob":case"arraybuffer":y="uint8array";break;case"base64":y="string"}try{this._internalType=y,this._outputType=v,this._mimeType=g,s.checkSupport(y),this._worker=x.pipe(new o(y)),x.lock()}catch(_){this._worker=new l("error"),this._worker.error(_)}}p.prototype={accumulate:function(x){return f(this,x)},on:function(x,v){var g=this;return x==="data"?this._worker.on(x,function(y){v.call(g,y.data,y.meta)}):this._worker.on(x,function(){s.delay(v,arguments,g)}),this},resume:function(){return s.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(x){if(s.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:this._outputType!=="nodebuffer"},x)}},r.exports=p},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(n,r,a){if(a.base64=!0,a.array=!0,a.string=!0,a.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",a.nodebuffer=typeof Buffer<"u",a.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")a.blob=!1;else{var s=new ArrayBuffer(0);try{a.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),a.blob=o.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var s=n("./utils"),o=n("./support"),l=n("./nodejsUtils"),c=n("./stream/GenericWorker"),u=new Array(256),d=0;d<256;d++)u[d]=252<=d?6:248<=d?5:240<=d?4:224<=d?3:192<=d?2:1;u[254]=u[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function f(){c.call(this,"utf-8 encode")}a.utf8encode=function(p){return o.nodebuffer?l.newBufferFrom(p,"utf-8"):(function(x){var v,g,y,_,N,k=x.length,A=0;for(_=0;_<k;_++)(64512&(g=x.charCodeAt(_)))==55296&&_+1<k&&(64512&(y=x.charCodeAt(_+1)))==56320&&(g=65536+(g-55296<<10)+(y-56320),_++),A+=g<128?1:g<2048?2:g<65536?3:4;for(v=o.uint8array?new Uint8Array(A):new Array(A),_=N=0;N<A;_++)(64512&(g=x.charCodeAt(_)))==55296&&_+1<k&&(64512&(y=x.charCodeAt(_+1)))==56320&&(g=65536+(g-55296<<10)+(y-56320),_++),g<128?v[N++]=g:(g<2048?v[N++]=192|g>>>6:(g<65536?v[N++]=224|g>>>12:(v[N++]=240|g>>>18,v[N++]=128|g>>>12&63),v[N++]=128|g>>>6&63),v[N++]=128|63&g);return v})(p)},a.utf8decode=function(p){return o.nodebuffer?s.transformTo("nodebuffer",p).toString("utf-8"):(function(x){var v,g,y,_,N=x.length,k=new Array(2*N);for(v=g=0;v<N;)if((y=x[v++])<128)k[g++]=y;else if(4<(_=u[y]))k[g++]=65533,v+=_-1;else{for(y&=_===2?31:_===3?15:7;1<_&&v<N;)y=y<<6|63&x[v++],_--;1<_?k[g++]=65533:y<65536?k[g++]=y:(y-=65536,k[g++]=55296|y>>10&1023,k[g++]=56320|1023&y)}return k.length!==g&&(k.subarray?k=k.subarray(0,g):k.length=g),s.applyFromCharCode(k)})(p=s.transformTo(o.uint8array?"uint8array":"array",p))},s.inherits(h,c),h.prototype.processChunk=function(p){var x=s.transformTo(o.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var v=x;(x=new Uint8Array(v.length+this.leftOver.length)).set(this.leftOver,0),x.set(v,this.leftOver.length)}else x=this.leftOver.concat(x);this.leftOver=null}var g=(function(_,N){var k;for((N=N||_.length)>_.length&&(N=_.length),k=N-1;0<=k&&(192&_[k])==128;)k--;return k<0||k===0?N:k+u[_[k]]>N?k:N})(x),y=x;g!==x.length&&(o.uint8array?(y=x.subarray(0,g),this.leftOver=x.subarray(g,x.length)):(y=x.slice(0,g),this.leftOver=x.slice(g,x.length))),this.push({data:a.utf8decode(y),meta:p.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,s.inherits(f,c),f.prototype.processChunk=function(p){this.push({data:a.utf8encode(p.data),meta:p.meta})},a.Utf8EncodeWorker=f},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var s=n("./support"),o=n("./base64"),l=n("./nodejsUtils"),c=n("./external");function u(v){return v}function d(v,g){for(var y=0;y<v.length;++y)g[y]=255&v.charCodeAt(y);return g}n("setimmediate"),a.newBlob=function(v,g){a.checkSupport("blob");try{return new Blob([v],{type:g})}catch{try{var y=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return y.append(v),y.getBlob(g)}catch{throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(v,g,y){var _=[],N=0,k=v.length;if(k<=y)return String.fromCharCode.apply(null,v);for(;N<k;)g==="array"||g==="nodebuffer"?_.push(String.fromCharCode.apply(null,v.slice(N,Math.min(N+y,k)))):_.push(String.fromCharCode.apply(null,v.subarray(N,Math.min(N+y,k)))),N+=y;return _.join("")},stringifyByChar:function(v){for(var g="",y=0;y<v.length;y++)g+=String.fromCharCode(v[y]);return g},applyCanBeUsed:{uint8array:(function(){try{return s.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return s.nodebuffer&&String.fromCharCode.apply(null,l.allocBuffer(1)).length===1}catch{return!1}})()}};function f(v){var g=65536,y=a.getTypeOf(v),_=!0;if(y==="uint8array"?_=h.applyCanBeUsed.uint8array:y==="nodebuffer"&&(_=h.applyCanBeUsed.nodebuffer),_)for(;1<g;)try{return h.stringifyByChunk(v,y,g)}catch{g=Math.floor(g/2)}return h.stringifyByChar(v)}function p(v,g){for(var y=0;y<v.length;y++)g[y]=v[y];return g}a.applyFromCharCode=f;var x={};x.string={string:u,array:function(v){return d(v,new Array(v.length))},arraybuffer:function(v){return x.string.uint8array(v).buffer},uint8array:function(v){return d(v,new Uint8Array(v.length))},nodebuffer:function(v){return d(v,l.allocBuffer(v.length))}},x.array={string:f,array:u,arraybuffer:function(v){return new Uint8Array(v).buffer},uint8array:function(v){return new Uint8Array(v)},nodebuffer:function(v){return l.newBufferFrom(v)}},x.arraybuffer={string:function(v){return f(new Uint8Array(v))},array:function(v){return p(new Uint8Array(v),new Array(v.byteLength))},arraybuffer:u,uint8array:function(v){return new Uint8Array(v)},nodebuffer:function(v){return l.newBufferFrom(new Uint8Array(v))}},x.uint8array={string:f,array:function(v){return p(v,new Array(v.length))},arraybuffer:function(v){return v.buffer},uint8array:u,nodebuffer:function(v){return l.newBufferFrom(v)}},x.nodebuffer={string:f,array:function(v){return p(v,new Array(v.length))},arraybuffer:function(v){return x.nodebuffer.uint8array(v).buffer},uint8array:function(v){return p(v,new Uint8Array(v.length))},nodebuffer:u},a.transformTo=function(v,g){if(g=g||"",!v)return g;a.checkSupport(v);var y=a.getTypeOf(g);return x[y][v](g)},a.resolve=function(v){for(var g=v.split("/"),y=[],_=0;_<g.length;_++){var N=g[_];N==="."||N===""&&_!==0&&_!==g.length-1||(N===".."?y.pop():y.push(N))}return y.join("/")},a.getTypeOf=function(v){return typeof v=="string"?"string":Object.prototype.toString.call(v)==="[object Array]"?"array":s.nodebuffer&&l.isBuffer(v)?"nodebuffer":s.uint8array&&v instanceof Uint8Array?"uint8array":s.arraybuffer&&v instanceof ArrayBuffer?"arraybuffer":void 0},a.checkSupport=function(v){if(!s[v.toLowerCase()])throw new Error(v+" is not supported by this platform")},a.MAX_VALUE_16BITS=65535,a.MAX_VALUE_32BITS=-1,a.pretty=function(v){var g,y,_="";for(y=0;y<(v||"").length;y++)_+="\\x"+((g=v.charCodeAt(y))<16?"0":"")+g.toString(16).toUpperCase();return _},a.delay=function(v,g,y){setImmediate(function(){v.apply(y||null,g||[])})},a.inherits=function(v,g){function y(){}y.prototype=g.prototype,v.prototype=new y},a.extend=function(){var v,g,y={};for(v=0;v<arguments.length;v++)for(g in arguments[v])Object.prototype.hasOwnProperty.call(arguments[v],g)&&y[g]===void 0&&(y[g]=arguments[v][g]);return y},a.prepareContent=function(v,g,y,_,N){return c.Promise.resolve(g).then(function(k){return s.blob&&(k instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(k))!==-1)&&typeof FileReader<"u"?new c.Promise(function(A,M){var C=new FileReader;C.onload=function(j){A(j.target.result)},C.onerror=function(j){M(j.target.error)},C.readAsArrayBuffer(k)}):k}).then(function(k){var A=a.getTypeOf(k);return A?(A==="arraybuffer"?k=a.transformTo("uint8array",k):A==="string"&&(N?k=o.decode(k):y&&_!==!0&&(k=(function(M){return d(M,s.uint8array?new Uint8Array(M.length):new Array(M.length))})(k))),k):c.Promise.reject(new Error("Can't read the data of '"+v+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(n,r,a){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./signature"),c=n("./zipEntry"),u=n("./support");function d(h){this.files=[],this.loadOptions=h}d.prototype={checkSignature:function(h){if(!this.reader.readAndCheckSignature(h)){this.reader.index-=4;var f=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+o.pretty(f)+", expected "+o.pretty(h)+")")}},isSignature:function(h,f){var p=this.reader.index;this.reader.setIndex(h);var x=this.reader.readString(4)===f;return this.reader.setIndex(p),x},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var h=this.reader.readData(this.zipCommentLength),f=u.uint8array?"uint8array":"array",p=o.transformTo(f,h);this.zipComment=this.loadOptions.decodeFileName(p)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var h,f,p,x=this.zip64EndOfCentralSize-44;0<x;)h=this.reader.readInt(2),f=this.reader.readInt(4),p=this.reader.readData(f),this.zip64ExtensibleData[h]={id:h,length:f,value:p}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var h,f;for(h=0;h<this.files.length;h++)f=this.files[h],this.reader.setIndex(f.localHeaderOffset),this.checkSignature(l.LOCAL_FILE_HEADER),f.readLocalPart(this.reader),f.handleUTF8(),f.processAttributes()},readCentralDir:function(){var h;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(l.CENTRAL_FILE_HEADER);)(h=new c({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(h);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var h=this.reader.lastIndexOfSignature(l.CENTRAL_DIRECTORY_END);if(h<0)throw this.isSignature(0,l.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(h);var f=h;if(this.checkSignature(l.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===o.MAX_VALUE_16BITS||this.diskWithCentralDirStart===o.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===o.MAX_VALUE_16BITS||this.centralDirRecords===o.MAX_VALUE_16BITS||this.centralDirSize===o.MAX_VALUE_32BITS||this.centralDirOffset===o.MAX_VALUE_32BITS){if(this.zip64=!0,(h=this.reader.lastIndexOfSignature(l.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(h),this.checkSignature(l.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,l.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(l.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(l.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var p=this.centralDirOffset+this.centralDirSize;this.zip64&&(p+=20,p+=12+this.zip64EndOfCentralSize);var x=f-p;if(0<x)this.isSignature(f,l.CENTRAL_FILE_HEADER)||(this.reader.zero=x);else if(x<0)throw new Error("Corrupted zip: missing "+Math.abs(x)+" bytes.")},prepareReader:function(h){this.reader=s(h)},load:function(h){this.prepareReader(h),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},r.exports=d},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(n,r,a){var s=n("./reader/readerFor"),o=n("./utils"),l=n("./compressedObject"),c=n("./crc32"),u=n("./utf8"),d=n("./compressions"),h=n("./support");function f(p,x){this.options=p,this.loadOptions=x}f.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(p){var x,v;if(p.skip(22),this.fileNameLength=p.readInt(2),v=p.readInt(2),this.fileName=p.readData(this.fileNameLength),p.skip(v),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((x=(function(g){for(var y in d)if(Object.prototype.hasOwnProperty.call(d,y)&&d[y].magic===g)return d[y];return null})(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+o.pretty(this.compressionMethod)+" unknown (inner file : "+o.transformTo("string",this.fileName)+")");this.decompressed=new l(this.compressedSize,this.uncompressedSize,this.crc32,x,p.readData(this.compressedSize))},readCentralPart:function(p){this.versionMadeBy=p.readInt(2),p.skip(2),this.bitFlag=p.readInt(2),this.compressionMethod=p.readString(2),this.date=p.readDate(),this.crc32=p.readInt(4),this.compressedSize=p.readInt(4),this.uncompressedSize=p.readInt(4);var x=p.readInt(2);if(this.extraFieldsLength=p.readInt(2),this.fileCommentLength=p.readInt(2),this.diskNumberStart=p.readInt(2),this.internalFileAttributes=p.readInt(2),this.externalFileAttributes=p.readInt(4),this.localHeaderOffset=p.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");p.skip(x),this.readExtraFields(p),this.parseZIP64ExtraField(p),this.fileComment=p.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var p=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var x,v,g,y=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4<y;)x=p.readInt(2),v=p.readInt(2),g=p.readData(v),this.extraFields[x]={id:x,length:v,value:g};p.setIndex(y)},handleUTF8:function(){var p=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=u.utf8decode(this.fileName),this.fileCommentStr=u.utf8decode(this.fileComment);else{var x=this.findExtraFieldUnicodePath();if(x!==null)this.fileNameStr=x;else{var v=o.transformTo(p,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(v)}var g=this.findExtraFieldUnicodeComment();if(g!==null)this.fileCommentStr=g;else{var y=o.transformTo(p,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(y)}}},findExtraFieldUnicodePath:function(){var p=this.extraFields[28789];if(p){var x=s(p.value);return x.readInt(1)!==1||c(this.fileName)!==x.readInt(4)?null:u.utf8decode(x.readData(p.length-5))}return null},findExtraFieldUnicodeComment:function(){var p=this.extraFields[25461];if(p){var x=s(p.value);return x.readInt(1)!==1||c(this.fileComment)!==x.readInt(4)?null:u.utf8decode(x.readData(p.length-5))}return null}},r.exports=f},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(n,r,a){function s(x,v,g){this.name=x,this.dir=g.dir,this.date=g.date,this.comment=g.comment,this.unixPermissions=g.unixPermissions,this.dosPermissions=g.dosPermissions,this._data=v,this._dataBinary=g.binary,this.options={compression:g.compression,compressionOptions:g.compressionOptions}}var o=n("./stream/StreamHelper"),l=n("./stream/DataWorker"),c=n("./utf8"),u=n("./compressedObject"),d=n("./stream/GenericWorker");s.prototype={internalStream:function(x){var v=null,g="string";try{if(!x)throw new Error("No output type specified.");var y=(g=x.toLowerCase())==="string"||g==="text";g!=="binarystring"&&g!=="text"||(g="string"),v=this._decompressWorker();var _=!this._dataBinary;_&&!y&&(v=v.pipe(new c.Utf8EncodeWorker)),!_&&y&&(v=v.pipe(new c.Utf8DecodeWorker))}catch(N){(v=new d("error")).error(N)}return new o(v,g,"")},async:function(x,v){return this.internalStream(x).accumulate(v)},nodeStream:function(x,v){return this.internalStream(x||"nodebuffer").toNodejsStream(v)},_compressWorker:function(x,v){if(this._data instanceof u&&this._data.compression.magic===x.magic)return this._data.getCompressedWorker();var g=this._decompressWorker();return this._dataBinary||(g=g.pipe(new c.Utf8EncodeWorker)),u.createWorkerFrom(g,x,v)},_decompressWorker:function(){return this._data instanceof u?this._data.getContentWorker():this._data instanceof d?this._data:new l(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],f=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},p=0;p<h.length;p++)s.prototype[h[p]]=f;r.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(n,r,a){(function(s){var o,l,c=s.MutationObserver||s.WebKitMutationObserver;if(c){var u=0,d=new c(x),h=s.document.createTextNode("");d.observe(h,{characterData:!0}),o=function(){h.data=u=++u%2}}else if(s.setImmediate||s.MessageChannel===void 0)o="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var v=s.document.createElement("script");v.onreadystatechange=function(){x(),v.onreadystatechange=null,v.parentNode.removeChild(v),v=null},s.document.documentElement.appendChild(v)}:function(){setTimeout(x,0)};else{var f=new s.MessageChannel;f.port1.onmessage=x,o=function(){f.port2.postMessage(0)}}var p=[];function x(){var v,g;l=!0;for(var y=p.length;y;){for(g=p,p=[],v=-1;++v<y;)g[v]();y=p.length}l=!1}r.exports=function(v){p.push(v)!==1||l||o()}}).call(this,typeof eS<"u"?eS:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(n,r,a){var s=n("immediate");function o(){}var l={},c=["REJECTED"],u=["FULFILLED"],d=["PENDING"];function h(y){if(typeof y!="function")throw new TypeError("resolver must be a function");this.state=d,this.queue=[],this.outcome=void 0,y!==o&&v(this,y)}function f(y,_,N){this.promise=y,typeof _=="function"&&(this.onFulfilled=_,this.callFulfilled=this.otherCallFulfilled),typeof N=="function"&&(this.onRejected=N,this.callRejected=this.otherCallRejected)}function p(y,_,N){s(function(){var k;try{k=_(N)}catch(A){return l.reject(y,A)}k===y?l.reject(y,new TypeError("Cannot resolve promise with itself")):l.resolve(y,k)})}function x(y){var _=y&&y.then;if(y&&(typeof y=="object"||typeof y=="function")&&typeof _=="function")return function(){_.apply(y,arguments)}}function v(y,_){var N=!1;function k(C){N||(N=!0,l.reject(y,C))}function A(C){N||(N=!0,l.resolve(y,C))}var M=g(function(){_(A,k)});M.status==="error"&&k(M.value)}function g(y,_){var N={};try{N.value=y(_),N.status="success"}catch(k){N.status="error",N.value=k}return N}(r.exports=h).prototype.finally=function(y){if(typeof y!="function")return this;var _=this.constructor;return this.then(function(N){return _.resolve(y()).then(function(){return N})},function(N){return _.resolve(y()).then(function(){throw N})})},h.prototype.catch=function(y){return this.then(null,y)},h.prototype.then=function(y,_){if(typeof y!="function"&&this.state===u||typeof _!="function"&&this.state===c)return this;var N=new this.constructor(o);return this.state!==d?p(N,this.state===u?y:_,this.outcome):this.queue.push(new f(N,y,_)),N},f.prototype.callFulfilled=function(y){l.resolve(this.promise,y)},f.prototype.otherCallFulfilled=function(y){p(this.promise,this.onFulfilled,y)},f.prototype.callRejected=function(y){l.reject(this.promise,y)},f.prototype.otherCallRejected=function(y){p(this.promise,this.onRejected,y)},l.resolve=function(y,_){var N=g(x,_);if(N.status==="error")return l.reject(y,N.value);var k=N.value;if(k)v(y,k);else{y.state=u,y.outcome=_;for(var A=-1,M=y.queue.length;++A<M;)y.queue[A].callFulfilled(_)}return y},l.reject=function(y,_){y.state=c,y.outcome=_;for(var N=-1,k=y.queue.length;++N<k;)y.queue[N].callRejected(_);return y},h.resolve=function(y){return y instanceof this?y:l.resolve(new this(o),y)},h.reject=function(y){var _=new this(o);return l.reject(_,y)},h.all=function(y){var _=this;if(Object.prototype.toString.call(y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var N=y.length,k=!1;if(!N)return this.resolve([]);for(var A=new Array(N),M=0,C=-1,j=new this(o);++C<N;)P(y[C],C);return j;function P(E,U){_.resolve(E).then(function(L){A[U]=L,++M!==N||k||(k=!0,l.resolve(j,A))},function(L){k||(k=!0,l.reject(j,L))})}},h.race=function(y){var _=this;if(Object.prototype.toString.call(y)!=="[object Array]")return this.reject(new TypeError("must be an array"));var N=y.length,k=!1;if(!N)return this.resolve([]);for(var A=-1,M=new this(o);++A<N;)C=y[A],_.resolve(C).then(function(j){k||(k=!0,l.resolve(M,j))},function(j){k||(k=!0,l.reject(M,j))});var C;return M}},{immediate:36}],38:[function(n,r,a){var s={};(0,n("./lib/utils/common").assign)(s,n("./lib/deflate"),n("./lib/inflate"),n("./lib/zlib/constants")),r.exports=s},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(n,r,a){var s=n("./zlib/deflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/messages"),u=n("./zlib/zstream"),d=Object.prototype.toString,h=0,f=-1,p=0,x=8;function v(y){if(!(this instanceof v))return new v(y);this.options=o.assign({level:f,method:x,chunkSize:16384,windowBits:15,memLevel:8,strategy:p,to:""},y||{});var _=this.options;_.raw&&0<_.windowBits?_.windowBits=-_.windowBits:_.gzip&&0<_.windowBits&&_.windowBits<16&&(_.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new u,this.strm.avail_out=0;var N=s.deflateInit2(this.strm,_.level,_.method,_.windowBits,_.memLevel,_.strategy);if(N!==h)throw new Error(c[N]);if(_.header&&s.deflateSetHeader(this.strm,_.header),_.dictionary){var k;if(k=typeof _.dictionary=="string"?l.string2buf(_.dictionary):d.call(_.dictionary)==="[object ArrayBuffer]"?new Uint8Array(_.dictionary):_.dictionary,(N=s.deflateSetDictionary(this.strm,k))!==h)throw new Error(c[N]);this._dict_set=!0}}function g(y,_){var N=new v(_);if(N.push(y,!0),N.err)throw N.msg||c[N.err];return N.result}v.prototype.push=function(y,_){var N,k,A=this.strm,M=this.options.chunkSize;if(this.ended)return!1;k=_===~~_?_:_===!0?4:0,typeof y=="string"?A.input=l.string2buf(y):d.call(y)==="[object ArrayBuffer]"?A.input=new Uint8Array(y):A.input=y,A.next_in=0,A.avail_in=A.input.length;do{if(A.avail_out===0&&(A.output=new o.Buf8(M),A.next_out=0,A.avail_out=M),(N=s.deflate(A,k))!==1&&N!==h)return this.onEnd(N),!(this.ended=!0);A.avail_out!==0&&(A.avail_in!==0||k!==4&&k!==2)||(this.options.to==="string"?this.onData(l.buf2binstring(o.shrinkBuf(A.output,A.next_out))):this.onData(o.shrinkBuf(A.output,A.next_out)))}while((0<A.avail_in||A.avail_out===0)&&N!==1);return k===4?(N=s.deflateEnd(this.strm),this.onEnd(N),this.ended=!0,N===h):k!==2||(this.onEnd(h),!(A.avail_out=0))},v.prototype.onData=function(y){this.chunks.push(y)},v.prototype.onEnd=function(y){y===h&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=y,this.msg=this.strm.msg},a.Deflate=v,a.deflate=g,a.deflateRaw=function(y,_){return(_=_||{}).raw=!0,g(y,_)},a.gzip=function(y,_){return(_=_||{}).gzip=!0,g(y,_)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(n,r,a){var s=n("./zlib/inflate"),o=n("./utils/common"),l=n("./utils/strings"),c=n("./zlib/constants"),u=n("./zlib/messages"),d=n("./zlib/zstream"),h=n("./zlib/gzheader"),f=Object.prototype.toString;function p(v){if(!(this instanceof p))return new p(v);this.options=o.assign({chunkSize:16384,windowBits:0,to:""},v||{});var g=this.options;g.raw&&0<=g.windowBits&&g.windowBits<16&&(g.windowBits=-g.windowBits,g.windowBits===0&&(g.windowBits=-15)),!(0<=g.windowBits&&g.windowBits<16)||v&&v.windowBits||(g.windowBits+=32),15<g.windowBits&&g.windowBits<48&&(15&g.windowBits)==0&&(g.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d,this.strm.avail_out=0;var y=s.inflateInit2(this.strm,g.windowBits);if(y!==c.Z_OK)throw new Error(u[y]);this.header=new h,s.inflateGetHeader(this.strm,this.header)}function x(v,g){var y=new p(g);if(y.push(v,!0),y.err)throw y.msg||u[y.err];return y.result}p.prototype.push=function(v,g){var y,_,N,k,A,M,C=this.strm,j=this.options.chunkSize,P=this.options.dictionary,E=!1;if(this.ended)return!1;_=g===~~g?g:g===!0?c.Z_FINISH:c.Z_NO_FLUSH,typeof v=="string"?C.input=l.binstring2buf(v):f.call(v)==="[object ArrayBuffer]"?C.input=new Uint8Array(v):C.input=v,C.next_in=0,C.avail_in=C.input.length;do{if(C.avail_out===0&&(C.output=new o.Buf8(j),C.next_out=0,C.avail_out=j),(y=s.inflate(C,c.Z_NO_FLUSH))===c.Z_NEED_DICT&&P&&(M=typeof P=="string"?l.string2buf(P):f.call(P)==="[object ArrayBuffer]"?new Uint8Array(P):P,y=s.inflateSetDictionary(this.strm,M)),y===c.Z_BUF_ERROR&&E===!0&&(y=c.Z_OK,E=!1),y!==c.Z_STREAM_END&&y!==c.Z_OK)return this.onEnd(y),!(this.ended=!0);C.next_out&&(C.avail_out!==0&&y!==c.Z_STREAM_END&&(C.avail_in!==0||_!==c.Z_FINISH&&_!==c.Z_SYNC_FLUSH)||(this.options.to==="string"?(N=l.utf8border(C.output,C.next_out),k=C.next_out-N,A=l.buf2string(C.output,N),C.next_out=k,C.avail_out=j-k,k&&o.arraySet(C.output,C.output,N,k,0),this.onData(A)):this.onData(o.shrinkBuf(C.output,C.next_out)))),C.avail_in===0&&C.avail_out===0&&(E=!0)}while((0<C.avail_in||C.avail_out===0)&&y!==c.Z_STREAM_END);return y===c.Z_STREAM_END&&(_=c.Z_FINISH),_===c.Z_FINISH?(y=s.inflateEnd(this.strm),this.onEnd(y),this.ended=!0,y===c.Z_OK):_!==c.Z_SYNC_FLUSH||(this.onEnd(c.Z_OK),!(C.avail_out=0))},p.prototype.onData=function(v){this.chunks.push(v)},p.prototype.onEnd=function(v){v===c.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=o.flattenChunks(this.chunks)),this.chunks=[],this.err=v,this.msg=this.strm.msg},a.Inflate=p,a.inflate=x,a.inflateRaw=function(v,g){return(g=g||{}).raw=!0,x(v,g)},a.ungzip=x},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(n,r,a){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";a.assign=function(c){for(var u=Array.prototype.slice.call(arguments,1);u.length;){var d=u.shift();if(d){if(typeof d!="object")throw new TypeError(d+"must be non-object");for(var h in d)d.hasOwnProperty(h)&&(c[h]=d[h])}}return c},a.shrinkBuf=function(c,u){return c.length===u?c:c.subarray?c.subarray(0,u):(c.length=u,c)};var o={arraySet:function(c,u,d,h,f){if(u.subarray&&c.subarray)c.set(u.subarray(d,d+h),f);else for(var p=0;p<h;p++)c[f+p]=u[d+p]},flattenChunks:function(c){var u,d,h,f,p,x;for(u=h=0,d=c.length;u<d;u++)h+=c[u].length;for(x=new Uint8Array(h),u=f=0,d=c.length;u<d;u++)p=c[u],x.set(p,f),f+=p.length;return x}},l={arraySet:function(c,u,d,h,f){for(var p=0;p<h;p++)c[f+p]=u[d+p]},flattenChunks:function(c){return[].concat.apply([],c)}};a.setTyped=function(c){c?(a.Buf8=Uint8Array,a.Buf16=Uint16Array,a.Buf32=Int32Array,a.assign(a,o)):(a.Buf8=Array,a.Buf16=Array,a.Buf32=Array,a.assign(a,l))},a.setTyped(s)},{}],42:[function(n,r,a){var s=n("./common"),o=!0,l=!0;try{String.fromCharCode.apply(null,[0])}catch{o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{l=!1}for(var c=new s.Buf8(256),u=0;u<256;u++)c[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;function d(h,f){if(f<65537&&(h.subarray&&l||!h.subarray&&o))return String.fromCharCode.apply(null,s.shrinkBuf(h,f));for(var p="",x=0;x<f;x++)p+=String.fromCharCode(h[x]);return p}c[254]=c[254]=1,a.string2buf=function(h){var f,p,x,v,g,y=h.length,_=0;for(v=0;v<y;v++)(64512&(p=h.charCodeAt(v)))==55296&&v+1<y&&(64512&(x=h.charCodeAt(v+1)))==56320&&(p=65536+(p-55296<<10)+(x-56320),v++),_+=p<128?1:p<2048?2:p<65536?3:4;for(f=new s.Buf8(_),v=g=0;g<_;v++)(64512&(p=h.charCodeAt(v)))==55296&&v+1<y&&(64512&(x=h.charCodeAt(v+1)))==56320&&(p=65536+(p-55296<<10)+(x-56320),v++),p<128?f[g++]=p:(p<2048?f[g++]=192|p>>>6:(p<65536?f[g++]=224|p>>>12:(f[g++]=240|p>>>18,f[g++]=128|p>>>12&63),f[g++]=128|p>>>6&63),f[g++]=128|63&p);return f},a.buf2binstring=function(h){return d(h,h.length)},a.binstring2buf=function(h){for(var f=new s.Buf8(h.length),p=0,x=f.length;p<x;p++)f[p]=h.charCodeAt(p);return f},a.buf2string=function(h,f){var p,x,v,g,y=f||h.length,_=new Array(2*y);for(p=x=0;p<y;)if((v=h[p++])<128)_[x++]=v;else if(4<(g=c[v]))_[x++]=65533,p+=g-1;else{for(v&=g===2?31:g===3?15:7;1<g&&p<y;)v=v<<6|63&h[p++],g--;1<g?_[x++]=65533:v<65536?_[x++]=v:(v-=65536,_[x++]=55296|v>>10&1023,_[x++]=56320|1023&v)}return d(_,x)},a.utf8border=function(h,f){var p;for((f=f||h.length)>h.length&&(f=h.length),p=f-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?f:p+c[h[p]]>f?p:f}},{"./common":41}],43:[function(n,r,a){r.exports=function(s,o,l,c){for(var u=65535&s|0,d=s>>>16&65535|0,h=0;l!==0;){for(l-=h=2e3<l?2e3:l;d=d+(u=u+o[c++]|0)|0,--h;);u%=65521,d%=65521}return u|d<<16|0}},{}],44:[function(n,r,a){r.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(n,r,a){var s=(function(){for(var o,l=[],c=0;c<256;c++){o=c;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;l[c]=o}return l})();r.exports=function(o,l,c,u){var d=s,h=u+c;o^=-1;for(var f=u;f<h;f++)o=o>>>8^d[255&(o^l[f])];return-1^o}},{}],46:[function(n,r,a){var s,o=n("../utils/common"),l=n("./trees"),c=n("./adler32"),u=n("./crc32"),d=n("./messages"),h=0,f=4,p=0,x=-2,v=-1,g=4,y=2,_=8,N=9,k=286,A=30,M=19,C=2*k+1,j=15,P=3,E=258,U=E+P+1,L=42,B=113,D=1,$=2,G=3,z=4;function W(V,Y){return V.msg=d[Y],Y}function X(V){return(V<<1)-(4<V?9:0)}function ae(V){for(var Y=V.length;0<=--Y;)V[Y]=0}function H(V){var Y=V.state,me=Y.pending;me>V.avail_out&&(me=V.avail_out),me!==0&&(o.arraySet(V.output,Y.pending_buf,Y.pending_out,me,V.next_out),V.next_out+=me,Y.pending_out+=me,V.total_out+=me,V.avail_out-=me,Y.pending-=me,Y.pending===0&&(Y.pending_out=0))}function K(V,Y){l._tr_flush_block(V,0<=V.block_start?V.block_start:-1,V.strstart-V.block_start,Y),V.block_start=V.strstart,H(V.strm)}function te(V,Y){V.pending_buf[V.pending++]=Y}function Z(V,Y){V.pending_buf[V.pending++]=Y>>>8&255,V.pending_buf[V.pending++]=255&Y}function ve(V,Y){var me,Q,se=V.max_chain_length,de=V.strstart,Le=V.prev_length,Ne=V.nice_match,be=V.strstart>V.w_size-U?V.strstart-(V.w_size-U):0,O=V.window,R=V.w_mask,q=V.prev,J=V.strstart+E,fe=O[de+Le-1],le=O[de+Le];V.prev_length>=V.good_match&&(se>>=2),Ne>V.lookahead&&(Ne=V.lookahead);do if(O[(me=Y)+Le]===le&&O[me+Le-1]===fe&&O[me]===O[de]&&O[++me]===O[de+1]){de+=2,me++;do;while(O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&O[++de]===O[++me]&&de<J);if(Q=E-(J-de),de=J-E,Le<Q){if(V.match_start=Y,Ne<=(Le=Q))break;fe=O[de+Le-1],le=O[de+Le]}}while((Y=q[Y&R])>be&&--se!=0);return Le<=V.lookahead?Le:V.lookahead}function ce(V){var Y,me,Q,se,de,Le,Ne,be,O,R,q=V.w_size;do{if(se=V.window_size-V.lookahead-V.strstart,V.strstart>=q+(q-U)){for(o.arraySet(V.window,V.window,q,q,0),V.match_start-=q,V.strstart-=q,V.block_start-=q,Y=me=V.hash_size;Q=V.head[--Y],V.head[Y]=q<=Q?Q-q:0,--me;);for(Y=me=q;Q=V.prev[--Y],V.prev[Y]=q<=Q?Q-q:0,--me;);se+=q}if(V.strm.avail_in===0)break;if(Le=V.strm,Ne=V.window,be=V.strstart+V.lookahead,O=se,R=void 0,R=Le.avail_in,O<R&&(R=O),me=R===0?0:(Le.avail_in-=R,o.arraySet(Ne,Le.input,Le.next_in,R,be),Le.state.wrap===1?Le.adler=c(Le.adler,Ne,R,be):Le.state.wrap===2&&(Le.adler=u(Le.adler,Ne,R,be)),Le.next_in+=R,Le.total_in+=R,R),V.lookahead+=me,V.lookahead+V.insert>=P)for(de=V.strstart-V.insert,V.ins_h=V.window[de],V.ins_h=(V.ins_h<<V.hash_shift^V.window[de+1])&V.hash_mask;V.insert&&(V.ins_h=(V.ins_h<<V.hash_shift^V.window[de+P-1])&V.hash_mask,V.prev[de&V.w_mask]=V.head[V.ins_h],V.head[V.ins_h]=de,de++,V.insert--,!(V.lookahead+V.insert<P)););}while(V.lookahead<U&&V.strm.avail_in!==0)}function ee(V,Y){for(var me,Q;;){if(V.lookahead<U){if(ce(V),V.lookahead<U&&Y===h)return D;if(V.lookahead===0)break}if(me=0,V.lookahead>=P&&(V.ins_h=(V.ins_h<<V.hash_shift^V.window[V.strstart+P-1])&V.hash_mask,me=V.prev[V.strstart&V.w_mask]=V.head[V.ins_h],V.head[V.ins_h]=V.strstart),me!==0&&V.strstart-me<=V.w_size-U&&(V.match_length=ve(V,me)),V.match_length>=P)if(Q=l._tr_tally(V,V.strstart-V.match_start,V.match_length-P),V.lookahead-=V.match_length,V.match_length<=V.max_lazy_match&&V.lookahead>=P){for(V.match_length--;V.strstart++,V.ins_h=(V.ins_h<<V.hash_shift^V.window[V.strstart+P-1])&V.hash_mask,me=V.prev[V.strstart&V.w_mask]=V.head[V.ins_h],V.head[V.ins_h]=V.strstart,--V.match_length!=0;);V.strstart++}else V.strstart+=V.match_length,V.match_length=0,V.ins_h=V.window[V.strstart],V.ins_h=(V.ins_h<<V.hash_shift^V.window[V.strstart+1])&V.hash_mask;else Q=l._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++;if(Q&&(K(V,!1),V.strm.avail_out===0))return D}return V.insert=V.strstart<P-1?V.strstart:P-1,Y===f?(K(V,!0),V.strm.avail_out===0?G:z):V.last_lit&&(K(V,!1),V.strm.avail_out===0)?D:$}function je(V,Y){for(var me,Q,se;;){if(V.lookahead<U){if(ce(V),V.lookahead<U&&Y===h)return D;if(V.lookahead===0)break}if(me=0,V.lookahead>=P&&(V.ins_h=(V.ins_h<<V.hash_shift^V.window[V.strstart+P-1])&V.hash_mask,me=V.prev[V.strstart&V.w_mask]=V.head[V.ins_h],V.head[V.ins_h]=V.strstart),V.prev_length=V.match_length,V.prev_match=V.match_start,V.match_length=P-1,me!==0&&V.prev_length<V.max_lazy_match&&V.strstart-me<=V.w_size-U&&(V.match_length=ve(V,me),V.match_length<=5&&(V.strategy===1||V.match_length===P&&4096<V.strstart-V.match_start)&&(V.match_length=P-1)),V.prev_length>=P&&V.match_length<=V.prev_length){for(se=V.strstart+V.lookahead-P,Q=l._tr_tally(V,V.strstart-1-V.prev_match,V.prev_length-P),V.lookahead-=V.prev_length-1,V.prev_length-=2;++V.strstart<=se&&(V.ins_h=(V.ins_h<<V.hash_shift^V.window[V.strstart+P-1])&V.hash_mask,me=V.prev[V.strstart&V.w_mask]=V.head[V.ins_h],V.head[V.ins_h]=V.strstart),--V.prev_length!=0;);if(V.match_available=0,V.match_length=P-1,V.strstart++,Q&&(K(V,!1),V.strm.avail_out===0))return D}else if(V.match_available){if((Q=l._tr_tally(V,0,V.window[V.strstart-1]))&&K(V,!1),V.strstart++,V.lookahead--,V.strm.avail_out===0)return D}else V.match_available=1,V.strstart++,V.lookahead--}return V.match_available&&(Q=l._tr_tally(V,0,V.window[V.strstart-1]),V.match_available=0),V.insert=V.strstart<P-1?V.strstart:P-1,Y===f?(K(V,!0),V.strm.avail_out===0?G:z):V.last_lit&&(K(V,!1),V.strm.avail_out===0)?D:$}function he(V,Y,me,Q,se){this.good_length=V,this.max_lazy=Y,this.nice_length=me,this.max_chain=Q,this.func=se}function oe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=_,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new o.Buf16(2*C),this.dyn_dtree=new o.Buf16(2*(2*A+1)),this.bl_tree=new o.Buf16(2*(2*M+1)),ae(this.dyn_ltree),ae(this.dyn_dtree),ae(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new o.Buf16(j+1),this.heap=new o.Buf16(2*k+1),ae(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new o.Buf16(2*k+1),ae(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function _e(V){var Y;return V&&V.state?(V.total_in=V.total_out=0,V.data_type=y,(Y=V.state).pending=0,Y.pending_out=0,Y.wrap<0&&(Y.wrap=-Y.wrap),Y.status=Y.wrap?L:B,V.adler=Y.wrap===2?0:1,Y.last_flush=h,l._tr_init(Y),p):W(V,x)}function ie(V){var Y=_e(V);return Y===p&&(function(me){me.window_size=2*me.w_size,ae(me.head),me.max_lazy_match=s[me.level].max_lazy,me.good_match=s[me.level].good_length,me.nice_match=s[me.level].nice_length,me.max_chain_length=s[me.level].max_chain,me.strstart=0,me.block_start=0,me.lookahead=0,me.insert=0,me.match_length=me.prev_length=P-1,me.match_available=0,me.ins_h=0})(V.state),Y}function ze(V,Y,me,Q,se,de){if(!V)return x;var Le=1;if(Y===v&&(Y=6),Q<0?(Le=0,Q=-Q):15<Q&&(Le=2,Q-=16),se<1||N<se||me!==_||Q<8||15<Q||Y<0||9<Y||de<0||g<de)return W(V,x);Q===8&&(Q=9);var Ne=new oe;return(V.state=Ne).strm=V,Ne.wrap=Le,Ne.gzhead=null,Ne.w_bits=Q,Ne.w_size=1<<Ne.w_bits,Ne.w_mask=Ne.w_size-1,Ne.hash_bits=se+7,Ne.hash_size=1<<Ne.hash_bits,Ne.hash_mask=Ne.hash_size-1,Ne.hash_shift=~~((Ne.hash_bits+P-1)/P),Ne.window=new o.Buf8(2*Ne.w_size),Ne.head=new o.Buf16(Ne.hash_size),Ne.prev=new o.Buf16(Ne.w_size),Ne.lit_bufsize=1<<se+6,Ne.pending_buf_size=4*Ne.lit_bufsize,Ne.pending_buf=new o.Buf8(Ne.pending_buf_size),Ne.d_buf=1*Ne.lit_bufsize,Ne.l_buf=3*Ne.lit_bufsize,Ne.level=Y,Ne.strategy=de,Ne.method=me,ie(V)}s=[new he(0,0,0,0,function(V,Y){var me=65535;for(me>V.pending_buf_size-5&&(me=V.pending_buf_size-5);;){if(V.lookahead<=1){if(ce(V),V.lookahead===0&&Y===h)return D;if(V.lookahead===0)break}V.strstart+=V.lookahead,V.lookahead=0;var Q=V.block_start+me;if((V.strstart===0||V.strstart>=Q)&&(V.lookahead=V.strstart-Q,V.strstart=Q,K(V,!1),V.strm.avail_out===0)||V.strstart-V.block_start>=V.w_size-U&&(K(V,!1),V.strm.avail_out===0))return D}return V.insert=0,Y===f?(K(V,!0),V.strm.avail_out===0?G:z):(V.strstart>V.block_start&&(K(V,!1),V.strm.avail_out),D)}),new he(4,4,8,4,ee),new he(4,5,16,8,ee),new he(4,6,32,32,ee),new he(4,4,16,16,je),new he(8,16,32,32,je),new he(8,16,128,128,je),new he(8,32,128,256,je),new he(32,128,258,1024,je),new he(32,258,258,4096,je)],a.deflateInit=function(V,Y){return ze(V,Y,_,15,8,0)},a.deflateInit2=ze,a.deflateReset=ie,a.deflateResetKeep=_e,a.deflateSetHeader=function(V,Y){return V&&V.state?V.state.wrap!==2?x:(V.state.gzhead=Y,p):x},a.deflate=function(V,Y){var me,Q,se,de;if(!V||!V.state||5<Y||Y<0)return V?W(V,x):x;if(Q=V.state,!V.output||!V.input&&V.avail_in!==0||Q.status===666&&Y!==f)return W(V,V.avail_out===0?-5:x);if(Q.strm=V,me=Q.last_flush,Q.last_flush=Y,Q.status===L)if(Q.wrap===2)V.adler=0,te(Q,31),te(Q,139),te(Q,8),Q.gzhead?(te(Q,(Q.gzhead.text?1:0)+(Q.gzhead.hcrc?2:0)+(Q.gzhead.extra?4:0)+(Q.gzhead.name?8:0)+(Q.gzhead.comment?16:0)),te(Q,255&Q.gzhead.time),te(Q,Q.gzhead.time>>8&255),te(Q,Q.gzhead.time>>16&255),te(Q,Q.gzhead.time>>24&255),te(Q,Q.level===9?2:2<=Q.strategy||Q.level<2?4:0),te(Q,255&Q.gzhead.os),Q.gzhead.extra&&Q.gzhead.extra.length&&(te(Q,255&Q.gzhead.extra.length),te(Q,Q.gzhead.extra.length>>8&255)),Q.gzhead.hcrc&&(V.adler=u(V.adler,Q.pending_buf,Q.pending,0)),Q.gzindex=0,Q.status=69):(te(Q,0),te(Q,0),te(Q,0),te(Q,0),te(Q,0),te(Q,Q.level===9?2:2<=Q.strategy||Q.level<2?4:0),te(Q,3),Q.status=B);else{var Le=_+(Q.w_bits-8<<4)<<8;Le|=(2<=Q.strategy||Q.level<2?0:Q.level<6?1:Q.level===6?2:3)<<6,Q.strstart!==0&&(Le|=32),Le+=31-Le%31,Q.status=B,Z(Q,Le),Q.strstart!==0&&(Z(Q,V.adler>>>16),Z(Q,65535&V.adler)),V.adler=1}if(Q.status===69)if(Q.gzhead.extra){for(se=Q.pending;Q.gzindex<(65535&Q.gzhead.extra.length)&&(Q.pending!==Q.pending_buf_size||(Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),H(V),se=Q.pending,Q.pending!==Q.pending_buf_size));)te(Q,255&Q.gzhead.extra[Q.gzindex]),Q.gzindex++;Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),Q.gzindex===Q.gzhead.extra.length&&(Q.gzindex=0,Q.status=73)}else Q.status=73;if(Q.status===73)if(Q.gzhead.name){se=Q.pending;do{if(Q.pending===Q.pending_buf_size&&(Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),H(V),se=Q.pending,Q.pending===Q.pending_buf_size)){de=1;break}de=Q.gzindex<Q.gzhead.name.length?255&Q.gzhead.name.charCodeAt(Q.gzindex++):0,te(Q,de)}while(de!==0);Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),de===0&&(Q.gzindex=0,Q.status=91)}else Q.status=91;if(Q.status===91)if(Q.gzhead.comment){se=Q.pending;do{if(Q.pending===Q.pending_buf_size&&(Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),H(V),se=Q.pending,Q.pending===Q.pending_buf_size)){de=1;break}de=Q.gzindex<Q.gzhead.comment.length?255&Q.gzhead.comment.charCodeAt(Q.gzindex++):0,te(Q,de)}while(de!==0);Q.gzhead.hcrc&&Q.pending>se&&(V.adler=u(V.adler,Q.pending_buf,Q.pending-se,se)),de===0&&(Q.status=103)}else Q.status=103;if(Q.status===103&&(Q.gzhead.hcrc?(Q.pending+2>Q.pending_buf_size&&H(V),Q.pending+2<=Q.pending_buf_size&&(te(Q,255&V.adler),te(Q,V.adler>>8&255),V.adler=0,Q.status=B)):Q.status=B),Q.pending!==0){if(H(V),V.avail_out===0)return Q.last_flush=-1,p}else if(V.avail_in===0&&X(Y)<=X(me)&&Y!==f)return W(V,-5);if(Q.status===666&&V.avail_in!==0)return W(V,-5);if(V.avail_in!==0||Q.lookahead!==0||Y!==h&&Q.status!==666){var Ne=Q.strategy===2?(function(be,O){for(var R;;){if(be.lookahead===0&&(ce(be),be.lookahead===0)){if(O===h)return D;break}if(be.match_length=0,R=l._tr_tally(be,0,be.window[be.strstart]),be.lookahead--,be.strstart++,R&&(K(be,!1),be.strm.avail_out===0))return D}return be.insert=0,O===f?(K(be,!0),be.strm.avail_out===0?G:z):be.last_lit&&(K(be,!1),be.strm.avail_out===0)?D:$})(Q,Y):Q.strategy===3?(function(be,O){for(var R,q,J,fe,le=be.window;;){if(be.lookahead<=E){if(ce(be),be.lookahead<=E&&O===h)return D;if(be.lookahead===0)break}if(be.match_length=0,be.lookahead>=P&&0<be.strstart&&(q=le[J=be.strstart-1])===le[++J]&&q===le[++J]&&q===le[++J]){fe=be.strstart+E;do;while(q===le[++J]&&q===le[++J]&&q===le[++J]&&q===le[++J]&&q===le[++J]&&q===le[++J]&&q===le[++J]&&q===le[++J]&&J<fe);be.match_length=E-(fe-J),be.match_length>be.lookahead&&(be.match_length=be.lookahead)}if(be.match_length>=P?(R=l._tr_tally(be,1,be.match_length-P),be.lookahead-=be.match_length,be.strstart+=be.match_length,be.match_length=0):(R=l._tr_tally(be,0,be.window[be.strstart]),be.lookahead--,be.strstart++),R&&(K(be,!1),be.strm.avail_out===0))return D}return be.insert=0,O===f?(K(be,!0),be.strm.avail_out===0?G:z):be.last_lit&&(K(be,!1),be.strm.avail_out===0)?D:$})(Q,Y):s[Q.level].func(Q,Y);if(Ne!==G&&Ne!==z||(Q.status=666),Ne===D||Ne===G)return V.avail_out===0&&(Q.last_flush=-1),p;if(Ne===$&&(Y===1?l._tr_align(Q):Y!==5&&(l._tr_stored_block(Q,0,0,!1),Y===3&&(ae(Q.head),Q.lookahead===0&&(Q.strstart=0,Q.block_start=0,Q.insert=0))),H(V),V.avail_out===0))return Q.last_flush=-1,p}return Y!==f?p:Q.wrap<=0?1:(Q.wrap===2?(te(Q,255&V.adler),te(Q,V.adler>>8&255),te(Q,V.adler>>16&255),te(Q,V.adler>>24&255),te(Q,255&V.total_in),te(Q,V.total_in>>8&255),te(Q,V.total_in>>16&255),te(Q,V.total_in>>24&255)):(Z(Q,V.adler>>>16),Z(Q,65535&V.adler)),H(V),0<Q.wrap&&(Q.wrap=-Q.wrap),Q.pending!==0?p:1)},a.deflateEnd=function(V){var Y;return V&&V.state?(Y=V.state.status)!==L&&Y!==69&&Y!==73&&Y!==91&&Y!==103&&Y!==B&&Y!==666?W(V,x):(V.state=null,Y===B?W(V,-3):p):x},a.deflateSetDictionary=function(V,Y){var me,Q,se,de,Le,Ne,be,O,R=Y.length;if(!V||!V.state||(de=(me=V.state).wrap)===2||de===1&&me.status!==L||me.lookahead)return x;for(de===1&&(V.adler=c(V.adler,Y,R,0)),me.wrap=0,R>=me.w_size&&(de===0&&(ae(me.head),me.strstart=0,me.block_start=0,me.insert=0),O=new o.Buf8(me.w_size),o.arraySet(O,Y,R-me.w_size,me.w_size,0),Y=O,R=me.w_size),Le=V.avail_in,Ne=V.next_in,be=V.input,V.avail_in=R,V.next_in=0,V.input=Y,ce(me);me.lookahead>=P;){for(Q=me.strstart,se=me.lookahead-(P-1);me.ins_h=(me.ins_h<<me.hash_shift^me.window[Q+P-1])&me.hash_mask,me.prev[Q&me.w_mask]=me.head[me.ins_h],me.head[me.ins_h]=Q,Q++,--se;);me.strstart=Q,me.lookahead=P-1,ce(me)}return me.strstart+=me.lookahead,me.block_start=me.strstart,me.insert=me.lookahead,me.lookahead=0,me.match_length=me.prev_length=P-1,me.match_available=0,V.next_in=Ne,V.input=be,V.avail_in=Le,me.wrap=de,p},a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,r,a){r.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(n,r,a){r.exports=function(s,o){var l,c,u,d,h,f,p,x,v,g,y,_,N,k,A,M,C,j,P,E,U,L,B,D,$;l=s.state,c=s.next_in,D=s.input,u=c+(s.avail_in-5),d=s.next_out,$=s.output,h=d-(o-s.avail_out),f=d+(s.avail_out-257),p=l.dmax,x=l.wsize,v=l.whave,g=l.wnext,y=l.window,_=l.hold,N=l.bits,k=l.lencode,A=l.distcode,M=(1<<l.lenbits)-1,C=(1<<l.distbits)-1;e:do{N<15&&(_+=D[c++]<<N,N+=8,_+=D[c++]<<N,N+=8),j=k[_&M];t:for(;;){if(_>>>=P=j>>>24,N-=P,(P=j>>>16&255)===0)$[d++]=65535&j;else{if(!(16&P)){if((64&P)==0){j=k[(65535&j)+(_&(1<<P)-1)];continue t}if(32&P){l.mode=12;break e}s.msg="invalid literal/length code",l.mode=30;break e}E=65535&j,(P&=15)&&(N<P&&(_+=D[c++]<<N,N+=8),E+=_&(1<<P)-1,_>>>=P,N-=P),N<15&&(_+=D[c++]<<N,N+=8,_+=D[c++]<<N,N+=8),j=A[_&C];n:for(;;){if(_>>>=P=j>>>24,N-=P,!(16&(P=j>>>16&255))){if((64&P)==0){j=A[(65535&j)+(_&(1<<P)-1)];continue n}s.msg="invalid distance code",l.mode=30;break e}if(U=65535&j,N<(P&=15)&&(_+=D[c++]<<N,(N+=8)<P&&(_+=D[c++]<<N,N+=8)),p<(U+=_&(1<<P)-1)){s.msg="invalid distance too far back",l.mode=30;break e}if(_>>>=P,N-=P,(P=d-h)<U){if(v<(P=U-P)&&l.sane){s.msg="invalid distance too far back",l.mode=30;break e}if(B=y,(L=0)===g){if(L+=x-P,P<E){for(E-=P;$[d++]=y[L++],--P;);L=d-U,B=$}}else if(g<P){if(L+=x+g-P,(P-=g)<E){for(E-=P;$[d++]=y[L++],--P;);if(L=0,g<E){for(E-=P=g;$[d++]=y[L++],--P;);L=d-U,B=$}}}else if(L+=g-P,P<E){for(E-=P;$[d++]=y[L++],--P;);L=d-U,B=$}for(;2<E;)$[d++]=B[L++],$[d++]=B[L++],$[d++]=B[L++],E-=3;E&&($[d++]=B[L++],1<E&&($[d++]=B[L++]))}else{for(L=d-U;$[d++]=$[L++],$[d++]=$[L++],$[d++]=$[L++],2<(E-=3););E&&($[d++]=$[L++],1<E&&($[d++]=$[L++]))}break}}break}}while(c<u&&d<f);c-=E=N>>3,_&=(1<<(N-=E<<3))-1,s.next_in=c,s.next_out=d,s.avail_in=c<u?u-c+5:5-(c-u),s.avail_out=d<f?f-d+257:257-(d-f),l.hold=_,l.bits=N}},{}],49:[function(n,r,a){var s=n("../utils/common"),o=n("./adler32"),l=n("./crc32"),c=n("./inffast"),u=n("./inftrees"),d=1,h=2,f=0,p=-2,x=1,v=852,g=592;function y(L){return(L>>>24&255)+(L>>>8&65280)+((65280&L)<<8)+((255&L)<<24)}function _(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function N(L){var B;return L&&L.state?(B=L.state,L.total_in=L.total_out=B.total=0,L.msg="",B.wrap&&(L.adler=1&B.wrap),B.mode=x,B.last=0,B.havedict=0,B.dmax=32768,B.head=null,B.hold=0,B.bits=0,B.lencode=B.lendyn=new s.Buf32(v),B.distcode=B.distdyn=new s.Buf32(g),B.sane=1,B.back=-1,f):p}function k(L){var B;return L&&L.state?((B=L.state).wsize=0,B.whave=0,B.wnext=0,N(L)):p}function A(L,B){var D,$;return L&&L.state?($=L.state,B<0?(D=0,B=-B):(D=1+(B>>4),B<48&&(B&=15)),B&&(B<8||15<B)?p:($.window!==null&&$.wbits!==B&&($.window=null),$.wrap=D,$.wbits=B,k(L))):p}function M(L,B){var D,$;return L?($=new _,(L.state=$).window=null,(D=A(L,B))!==f&&(L.state=null),D):p}var C,j,P=!0;function E(L){if(P){var B;for(C=new s.Buf32(512),j=new s.Buf32(32),B=0;B<144;)L.lens[B++]=8;for(;B<256;)L.lens[B++]=9;for(;B<280;)L.lens[B++]=7;for(;B<288;)L.lens[B++]=8;for(u(d,L.lens,0,288,C,0,L.work,{bits:9}),B=0;B<32;)L.lens[B++]=5;u(h,L.lens,0,32,j,0,L.work,{bits:5}),P=!1}L.lencode=C,L.lenbits=9,L.distcode=j,L.distbits=5}function U(L,B,D,$){var G,z=L.state;return z.window===null&&(z.wsize=1<<z.wbits,z.wnext=0,z.whave=0,z.window=new s.Buf8(z.wsize)),$>=z.wsize?(s.arraySet(z.window,B,D-z.wsize,z.wsize,0),z.wnext=0,z.whave=z.wsize):($<(G=z.wsize-z.wnext)&&(G=$),s.arraySet(z.window,B,D-$,G,z.wnext),($-=G)?(s.arraySet(z.window,B,D-$,$,0),z.wnext=$,z.whave=z.wsize):(z.wnext+=G,z.wnext===z.wsize&&(z.wnext=0),z.whave<z.wsize&&(z.whave+=G))),0}a.inflateReset=k,a.inflateReset2=A,a.inflateResetKeep=N,a.inflateInit=function(L){return M(L,15)},a.inflateInit2=M,a.inflate=function(L,B){var D,$,G,z,W,X,ae,H,K,te,Z,ve,ce,ee,je,he,oe,_e,ie,ze,V,Y,me,Q,se=0,de=new s.Buf8(4),Le=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!L||!L.state||!L.output||!L.input&&L.avail_in!==0)return p;(D=L.state).mode===12&&(D.mode=13),W=L.next_out,G=L.output,ae=L.avail_out,z=L.next_in,$=L.input,X=L.avail_in,H=D.hold,K=D.bits,te=X,Z=ae,Y=f;e:for(;;)switch(D.mode){case x:if(D.wrap===0){D.mode=13;break}for(;K<16;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(2&D.wrap&&H===35615){de[D.check=0]=255&H,de[1]=H>>>8&255,D.check=l(D.check,de,2,0),K=H=0,D.mode=2;break}if(D.flags=0,D.head&&(D.head.done=!1),!(1&D.wrap)||(((255&H)<<8)+(H>>8))%31){L.msg="incorrect header check",D.mode=30;break}if((15&H)!=8){L.msg="unknown compression method",D.mode=30;break}if(K-=4,V=8+(15&(H>>>=4)),D.wbits===0)D.wbits=V;else if(V>D.wbits){L.msg="invalid window size",D.mode=30;break}D.dmax=1<<V,L.adler=D.check=1,D.mode=512&H?10:12,K=H=0;break;case 2:for(;K<16;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(D.flags=H,(255&D.flags)!=8){L.msg="unknown compression method",D.mode=30;break}if(57344&D.flags){L.msg="unknown header flags set",D.mode=30;break}D.head&&(D.head.text=H>>8&1),512&D.flags&&(de[0]=255&H,de[1]=H>>>8&255,D.check=l(D.check,de,2,0)),K=H=0,D.mode=3;case 3:for(;K<32;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.head&&(D.head.time=H),512&D.flags&&(de[0]=255&H,de[1]=H>>>8&255,de[2]=H>>>16&255,de[3]=H>>>24&255,D.check=l(D.check,de,4,0)),K=H=0,D.mode=4;case 4:for(;K<16;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.head&&(D.head.xflags=255&H,D.head.os=H>>8),512&D.flags&&(de[0]=255&H,de[1]=H>>>8&255,D.check=l(D.check,de,2,0)),K=H=0,D.mode=5;case 5:if(1024&D.flags){for(;K<16;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.length=H,D.head&&(D.head.extra_len=H),512&D.flags&&(de[0]=255&H,de[1]=H>>>8&255,D.check=l(D.check,de,2,0)),K=H=0}else D.head&&(D.head.extra=null);D.mode=6;case 6:if(1024&D.flags&&(X<(ve=D.length)&&(ve=X),ve&&(D.head&&(V=D.head.extra_len-D.length,D.head.extra||(D.head.extra=new Array(D.head.extra_len)),s.arraySet(D.head.extra,$,z,ve,V)),512&D.flags&&(D.check=l(D.check,$,ve,z)),X-=ve,z+=ve,D.length-=ve),D.length))break e;D.length=0,D.mode=7;case 7:if(2048&D.flags){if(X===0)break e;for(ve=0;V=$[z+ve++],D.head&&V&&D.length<65536&&(D.head.name+=String.fromCharCode(V)),V&&ve<X;);if(512&D.flags&&(D.check=l(D.check,$,ve,z)),X-=ve,z+=ve,V)break e}else D.head&&(D.head.name=null);D.length=0,D.mode=8;case 8:if(4096&D.flags){if(X===0)break e;for(ve=0;V=$[z+ve++],D.head&&V&&D.length<65536&&(D.head.comment+=String.fromCharCode(V)),V&&ve<X;);if(512&D.flags&&(D.check=l(D.check,$,ve,z)),X-=ve,z+=ve,V)break e}else D.head&&(D.head.comment=null);D.mode=9;case 9:if(512&D.flags){for(;K<16;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(H!==(65535&D.check)){L.msg="header crc mismatch",D.mode=30;break}K=H=0}D.head&&(D.head.hcrc=D.flags>>9&1,D.head.done=!0),L.adler=D.check=0,D.mode=12;break;case 10:for(;K<32;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}L.adler=D.check=y(H),K=H=0,D.mode=11;case 11:if(D.havedict===0)return L.next_out=W,L.avail_out=ae,L.next_in=z,L.avail_in=X,D.hold=H,D.bits=K,2;L.adler=D.check=1,D.mode=12;case 12:if(B===5||B===6)break e;case 13:if(D.last){H>>>=7&K,K-=7&K,D.mode=27;break}for(;K<3;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}switch(D.last=1&H,K-=1,3&(H>>>=1)){case 0:D.mode=14;break;case 1:if(E(D),D.mode=20,B!==6)break;H>>>=2,K-=2;break e;case 2:D.mode=17;break;case 3:L.msg="invalid block type",D.mode=30}H>>>=2,K-=2;break;case 14:for(H>>>=7&K,K-=7&K;K<32;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if((65535&H)!=(H>>>16^65535)){L.msg="invalid stored block lengths",D.mode=30;break}if(D.length=65535&H,K=H=0,D.mode=15,B===6)break e;case 15:D.mode=16;case 16:if(ve=D.length){if(X<ve&&(ve=X),ae<ve&&(ve=ae),ve===0)break e;s.arraySet(G,$,z,ve,W),X-=ve,z+=ve,ae-=ve,W+=ve,D.length-=ve;break}D.mode=12;break;case 17:for(;K<14;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(D.nlen=257+(31&H),H>>>=5,K-=5,D.ndist=1+(31&H),H>>>=5,K-=5,D.ncode=4+(15&H),H>>>=4,K-=4,286<D.nlen||30<D.ndist){L.msg="too many length or distance symbols",D.mode=30;break}D.have=0,D.mode=18;case 18:for(;D.have<D.ncode;){for(;K<3;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.lens[Le[D.have++]]=7&H,H>>>=3,K-=3}for(;D.have<19;)D.lens[Le[D.have++]]=0;if(D.lencode=D.lendyn,D.lenbits=7,me={bits:D.lenbits},Y=u(0,D.lens,0,19,D.lencode,0,D.work,me),D.lenbits=me.bits,Y){L.msg="invalid code lengths set",D.mode=30;break}D.have=0,D.mode=19;case 19:for(;D.have<D.nlen+D.ndist;){for(;he=(se=D.lencode[H&(1<<D.lenbits)-1])>>>16&255,oe=65535&se,!((je=se>>>24)<=K);){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(oe<16)H>>>=je,K-=je,D.lens[D.have++]=oe;else{if(oe===16){for(Q=je+2;K<Q;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(H>>>=je,K-=je,D.have===0){L.msg="invalid bit length repeat",D.mode=30;break}V=D.lens[D.have-1],ve=3+(3&H),H>>>=2,K-=2}else if(oe===17){for(Q=je+3;K<Q;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}K-=je,V=0,ve=3+(7&(H>>>=je)),H>>>=3,K-=3}else{for(Q=je+7;K<Q;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}K-=je,V=0,ve=11+(127&(H>>>=je)),H>>>=7,K-=7}if(D.have+ve>D.nlen+D.ndist){L.msg="invalid bit length repeat",D.mode=30;break}for(;ve--;)D.lens[D.have++]=V}}if(D.mode===30)break;if(D.lens[256]===0){L.msg="invalid code -- missing end-of-block",D.mode=30;break}if(D.lenbits=9,me={bits:D.lenbits},Y=u(d,D.lens,0,D.nlen,D.lencode,0,D.work,me),D.lenbits=me.bits,Y){L.msg="invalid literal/lengths set",D.mode=30;break}if(D.distbits=6,D.distcode=D.distdyn,me={bits:D.distbits},Y=u(h,D.lens,D.nlen,D.ndist,D.distcode,0,D.work,me),D.distbits=me.bits,Y){L.msg="invalid distances set",D.mode=30;break}if(D.mode=20,B===6)break e;case 20:D.mode=21;case 21:if(6<=X&&258<=ae){L.next_out=W,L.avail_out=ae,L.next_in=z,L.avail_in=X,D.hold=H,D.bits=K,c(L,Z),W=L.next_out,G=L.output,ae=L.avail_out,z=L.next_in,$=L.input,X=L.avail_in,H=D.hold,K=D.bits,D.mode===12&&(D.back=-1);break}for(D.back=0;he=(se=D.lencode[H&(1<<D.lenbits)-1])>>>16&255,oe=65535&se,!((je=se>>>24)<=K);){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(he&&(240&he)==0){for(_e=je,ie=he,ze=oe;he=(se=D.lencode[ze+((H&(1<<_e+ie)-1)>>_e)])>>>16&255,oe=65535&se,!(_e+(je=se>>>24)<=K);){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}H>>>=_e,K-=_e,D.back+=_e}if(H>>>=je,K-=je,D.back+=je,D.length=oe,he===0){D.mode=26;break}if(32&he){D.back=-1,D.mode=12;break}if(64&he){L.msg="invalid literal/length code",D.mode=30;break}D.extra=15&he,D.mode=22;case 22:if(D.extra){for(Q=D.extra;K<Q;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.length+=H&(1<<D.extra)-1,H>>>=D.extra,K-=D.extra,D.back+=D.extra}D.was=D.length,D.mode=23;case 23:for(;he=(se=D.distcode[H&(1<<D.distbits)-1])>>>16&255,oe=65535&se,!((je=se>>>24)<=K);){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if((240&he)==0){for(_e=je,ie=he,ze=oe;he=(se=D.distcode[ze+((H&(1<<_e+ie)-1)>>_e)])>>>16&255,oe=65535&se,!(_e+(je=se>>>24)<=K);){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}H>>>=_e,K-=_e,D.back+=_e}if(H>>>=je,K-=je,D.back+=je,64&he){L.msg="invalid distance code",D.mode=30;break}D.offset=oe,D.extra=15&he,D.mode=24;case 24:if(D.extra){for(Q=D.extra;K<Q;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}D.offset+=H&(1<<D.extra)-1,H>>>=D.extra,K-=D.extra,D.back+=D.extra}if(D.offset>D.dmax){L.msg="invalid distance too far back",D.mode=30;break}D.mode=25;case 25:if(ae===0)break e;if(ve=Z-ae,D.offset>ve){if((ve=D.offset-ve)>D.whave&&D.sane){L.msg="invalid distance too far back",D.mode=30;break}ce=ve>D.wnext?(ve-=D.wnext,D.wsize-ve):D.wnext-ve,ve>D.length&&(ve=D.length),ee=D.window}else ee=G,ce=W-D.offset,ve=D.length;for(ae<ve&&(ve=ae),ae-=ve,D.length-=ve;G[W++]=ee[ce++],--ve;);D.length===0&&(D.mode=21);break;case 26:if(ae===0)break e;G[W++]=D.length,ae--,D.mode=21;break;case 27:if(D.wrap){for(;K<32;){if(X===0)break e;X--,H|=$[z++]<<K,K+=8}if(Z-=ae,L.total_out+=Z,D.total+=Z,Z&&(L.adler=D.check=D.flags?l(D.check,G,Z,W-Z):o(D.check,G,Z,W-Z)),Z=ae,(D.flags?H:y(H))!==D.check){L.msg="incorrect data check",D.mode=30;break}K=H=0}D.mode=28;case 28:if(D.wrap&&D.flags){for(;K<32;){if(X===0)break e;X--,H+=$[z++]<<K,K+=8}if(H!==(4294967295&D.total)){L.msg="incorrect length check",D.mode=30;break}K=H=0}D.mode=29;case 29:Y=1;break e;case 30:Y=-3;break e;case 31:return-4;default:return p}return L.next_out=W,L.avail_out=ae,L.next_in=z,L.avail_in=X,D.hold=H,D.bits=K,(D.wsize||Z!==L.avail_out&&D.mode<30&&(D.mode<27||B!==4))&&U(L,L.output,L.next_out,Z-L.avail_out)?(D.mode=31,-4):(te-=L.avail_in,Z-=L.avail_out,L.total_in+=te,L.total_out+=Z,D.total+=Z,D.wrap&&Z&&(L.adler=D.check=D.flags?l(D.check,G,Z,L.next_out-Z):o(D.check,G,Z,L.next_out-Z)),L.data_type=D.bits+(D.last?64:0)+(D.mode===12?128:0)+(D.mode===20||D.mode===15?256:0),(te==0&&Z===0||B===4)&&Y===f&&(Y=-5),Y)},a.inflateEnd=function(L){if(!L||!L.state)return p;var B=L.state;return B.window&&(B.window=null),L.state=null,f},a.inflateGetHeader=function(L,B){var D;return L&&L.state?(2&(D=L.state).wrap)==0?p:((D.head=B).done=!1,f):p},a.inflateSetDictionary=function(L,B){var D,$=B.length;return L&&L.state?(D=L.state).wrap!==0&&D.mode!==11?p:D.mode===11&&o(1,B,$,0)!==D.check?-3:U(L,B,$,$)?(D.mode=31,-4):(D.havedict=1,f):p},a.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(n,r,a){var s=n("../utils/common"),o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],c=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],u=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];r.exports=function(d,h,f,p,x,v,g,y){var _,N,k,A,M,C,j,P,E,U=y.bits,L=0,B=0,D=0,$=0,G=0,z=0,W=0,X=0,ae=0,H=0,K=null,te=0,Z=new s.Buf16(16),ve=new s.Buf16(16),ce=null,ee=0;for(L=0;L<=15;L++)Z[L]=0;for(B=0;B<p;B++)Z[h[f+B]]++;for(G=U,$=15;1<=$&&Z[$]===0;$--);if($<G&&(G=$),$===0)return x[v++]=20971520,x[v++]=20971520,y.bits=1,0;for(D=1;D<$&&Z[D]===0;D++);for(G<D&&(G=D),L=X=1;L<=15;L++)if(X<<=1,(X-=Z[L])<0)return-1;if(0<X&&(d===0||$!==1))return-1;for(ve[1]=0,L=1;L<15;L++)ve[L+1]=ve[L]+Z[L];for(B=0;B<p;B++)h[f+B]!==0&&(g[ve[h[f+B]]++]=B);if(C=d===0?(K=ce=g,19):d===1?(K=o,te-=257,ce=l,ee-=257,256):(K=c,ce=u,-1),L=D,M=v,W=B=H=0,k=-1,A=(ae=1<<(z=G))-1,d===1&&852<ae||d===2&&592<ae)return 1;for(;;){for(j=L-W,E=g[B]<C?(P=0,g[B]):g[B]>C?(P=ce[ee+g[B]],K[te+g[B]]):(P=96,0),_=1<<L-W,D=N=1<<z;x[M+(H>>W)+(N-=_)]=j<<24|P<<16|E|0,N!==0;);for(_=1<<L-1;H&_;)_>>=1;if(_!==0?(H&=_-1,H+=_):H=0,B++,--Z[L]==0){if(L===$)break;L=h[f+g[B]]}if(G<L&&(H&A)!==k){for(W===0&&(W=G),M+=D,X=1<<(z=L-W);z+W<$&&!((X-=Z[z+W])<=0);)z++,X<<=1;if(ae+=1<<z,d===1&&852<ae||d===2&&592<ae)return 1;x[k=H&A]=G<<24|z<<16|M-v|0}}return H!==0&&(x[M+H]=L-W<<24|64<<16|0),y.bits=G,0}},{"../utils/common":41}],51:[function(n,r,a){r.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(n,r,a){var s=n("../utils/common"),o=0,l=1;function c(se){for(var de=se.length;0<=--de;)se[de]=0}var u=0,d=29,h=256,f=h+1+d,p=30,x=19,v=2*f+1,g=15,y=16,_=7,N=256,k=16,A=17,M=18,C=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],j=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],P=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],E=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],U=new Array(2*(f+2));c(U);var L=new Array(2*p);c(L);var B=new Array(512);c(B);var D=new Array(256);c(D);var $=new Array(d);c($);var G,z,W,X=new Array(p);function ae(se,de,Le,Ne,be){this.static_tree=se,this.extra_bits=de,this.extra_base=Le,this.elems=Ne,this.max_length=be,this.has_stree=se&&se.length}function H(se,de){this.dyn_tree=se,this.max_code=0,this.stat_desc=de}function K(se){return se<256?B[se]:B[256+(se>>>7)]}function te(se,de){se.pending_buf[se.pending++]=255&de,se.pending_buf[se.pending++]=de>>>8&255}function Z(se,de,Le){se.bi_valid>y-Le?(se.bi_buf|=de<<se.bi_valid&65535,te(se,se.bi_buf),se.bi_buf=de>>y-se.bi_valid,se.bi_valid+=Le-y):(se.bi_buf|=de<<se.bi_valid&65535,se.bi_valid+=Le)}function ve(se,de,Le){Z(se,Le[2*de],Le[2*de+1])}function ce(se,de){for(var Le=0;Le|=1&se,se>>>=1,Le<<=1,0<--de;);return Le>>>1}function ee(se,de,Le){var Ne,be,O=new Array(g+1),R=0;for(Ne=1;Ne<=g;Ne++)O[Ne]=R=R+Le[Ne-1]<<1;for(be=0;be<=de;be++){var q=se[2*be+1];q!==0&&(se[2*be]=ce(O[q]++,q))}}function je(se){var de;for(de=0;de<f;de++)se.dyn_ltree[2*de]=0;for(de=0;de<p;de++)se.dyn_dtree[2*de]=0;for(de=0;de<x;de++)se.bl_tree[2*de]=0;se.dyn_ltree[2*N]=1,se.opt_len=se.static_len=0,se.last_lit=se.matches=0}function he(se){8<se.bi_valid?te(se,se.bi_buf):0<se.bi_valid&&(se.pending_buf[se.pending++]=se.bi_buf),se.bi_buf=0,se.bi_valid=0}function oe(se,de,Le,Ne){var be=2*de,O=2*Le;return se[be]<se[O]||se[be]===se[O]&&Ne[de]<=Ne[Le]}function _e(se,de,Le){for(var Ne=se.heap[Le],be=Le<<1;be<=se.heap_len&&(be<se.heap_len&&oe(de,se.heap[be+1],se.heap[be],se.depth)&&be++,!oe(de,Ne,se.heap[be],se.depth));)se.heap[Le]=se.heap[be],Le=be,be<<=1;se.heap[Le]=Ne}function ie(se,de,Le){var Ne,be,O,R,q=0;if(se.last_lit!==0)for(;Ne=se.pending_buf[se.d_buf+2*q]<<8|se.pending_buf[se.d_buf+2*q+1],be=se.pending_buf[se.l_buf+q],q++,Ne===0?ve(se,be,de):(ve(se,(O=D[be])+h+1,de),(R=C[O])!==0&&Z(se,be-=$[O],R),ve(se,O=K(--Ne),Le),(R=j[O])!==0&&Z(se,Ne-=X[O],R)),q<se.last_lit;);ve(se,N,de)}function ze(se,de){var Le,Ne,be,O=de.dyn_tree,R=de.stat_desc.static_tree,q=de.stat_desc.has_stree,J=de.stat_desc.elems,fe=-1;for(se.heap_len=0,se.heap_max=v,Le=0;Le<J;Le++)O[2*Le]!==0?(se.heap[++se.heap_len]=fe=Le,se.depth[Le]=0):O[2*Le+1]=0;for(;se.heap_len<2;)O[2*(be=se.heap[++se.heap_len]=fe<2?++fe:0)]=1,se.depth[be]=0,se.opt_len--,q&&(se.static_len-=R[2*be+1]);for(de.max_code=fe,Le=se.heap_len>>1;1<=Le;Le--)_e(se,O,Le);for(be=J;Le=se.heap[1],se.heap[1]=se.heap[se.heap_len--],_e(se,O,1),Ne=se.heap[1],se.heap[--se.heap_max]=Le,se.heap[--se.heap_max]=Ne,O[2*be]=O[2*Le]+O[2*Ne],se.depth[be]=(se.depth[Le]>=se.depth[Ne]?se.depth[Le]:se.depth[Ne])+1,O[2*Le+1]=O[2*Ne+1]=be,se.heap[1]=be++,_e(se,O,1),2<=se.heap_len;);se.heap[--se.heap_max]=se.heap[1],(function(le,Be){var Ie,Ke,Oe,pe,xe,ke,ge=Be.dyn_tree,we=Be.max_code,qe=Be.stat_desc.static_tree,Ee=Be.stat_desc.has_stree,tt=Be.stat_desc.extra_bits,De=Be.stat_desc.extra_base,We=Be.stat_desc.max_length,Ae=0;for(pe=0;pe<=g;pe++)le.bl_count[pe]=0;for(ge[2*le.heap[le.heap_max]+1]=0,Ie=le.heap_max+1;Ie<v;Ie++)We<(pe=ge[2*ge[2*(Ke=le.heap[Ie])+1]+1]+1)&&(pe=We,Ae++),ge[2*Ke+1]=pe,we<Ke||(le.bl_count[pe]++,xe=0,De<=Ke&&(xe=tt[Ke-De]),ke=ge[2*Ke],le.opt_len+=ke*(pe+xe),Ee&&(le.static_len+=ke*(qe[2*Ke+1]+xe)));if(Ae!==0){do{for(pe=We-1;le.bl_count[pe]===0;)pe--;le.bl_count[pe]--,le.bl_count[pe+1]+=2,le.bl_count[We]--,Ae-=2}while(0<Ae);for(pe=We;pe!==0;pe--)for(Ke=le.bl_count[pe];Ke!==0;)we<(Oe=le.heap[--Ie])||(ge[2*Oe+1]!==pe&&(le.opt_len+=(pe-ge[2*Oe+1])*ge[2*Oe],ge[2*Oe+1]=pe),Ke--)}})(se,de),ee(O,fe,se.bl_count)}function V(se,de,Le){var Ne,be,O=-1,R=de[1],q=0,J=7,fe=4;for(R===0&&(J=138,fe=3),de[2*(Le+1)+1]=65535,Ne=0;Ne<=Le;Ne++)be=R,R=de[2*(Ne+1)+1],++q<J&&be===R||(q<fe?se.bl_tree[2*be]+=q:be!==0?(be!==O&&se.bl_tree[2*be]++,se.bl_tree[2*k]++):q<=10?se.bl_tree[2*A]++:se.bl_tree[2*M]++,O=be,fe=(q=0)===R?(J=138,3):be===R?(J=6,3):(J=7,4))}function Y(se,de,Le){var Ne,be,O=-1,R=de[1],q=0,J=7,fe=4;for(R===0&&(J=138,fe=3),Ne=0;Ne<=Le;Ne++)if(be=R,R=de[2*(Ne+1)+1],!(++q<J&&be===R)){if(q<fe)for(;ve(se,be,se.bl_tree),--q!=0;);else be!==0?(be!==O&&(ve(se,be,se.bl_tree),q--),ve(se,k,se.bl_tree),Z(se,q-3,2)):q<=10?(ve(se,A,se.bl_tree),Z(se,q-3,3)):(ve(se,M,se.bl_tree),Z(se,q-11,7));O=be,fe=(q=0)===R?(J=138,3):be===R?(J=6,3):(J=7,4)}}c(X);var me=!1;function Q(se,de,Le,Ne){Z(se,(u<<1)+(Ne?1:0),3),(function(be,O,R,q){he(be),te(be,R),te(be,~R),s.arraySet(be.pending_buf,be.window,O,R,be.pending),be.pending+=R})(se,de,Le)}a._tr_init=function(se){me||((function(){var de,Le,Ne,be,O,R=new Array(g+1);for(be=Ne=0;be<d-1;be++)for($[be]=Ne,de=0;de<1<<C[be];de++)D[Ne++]=be;for(D[Ne-1]=be,be=O=0;be<16;be++)for(X[be]=O,de=0;de<1<<j[be];de++)B[O++]=be;for(O>>=7;be<p;be++)for(X[be]=O<<7,de=0;de<1<<j[be]-7;de++)B[256+O++]=be;for(Le=0;Le<=g;Le++)R[Le]=0;for(de=0;de<=143;)U[2*de+1]=8,de++,R[8]++;for(;de<=255;)U[2*de+1]=9,de++,R[9]++;for(;de<=279;)U[2*de+1]=7,de++,R[7]++;for(;de<=287;)U[2*de+1]=8,de++,R[8]++;for(ee(U,f+1,R),de=0;de<p;de++)L[2*de+1]=5,L[2*de]=ce(de,5);G=new ae(U,C,h+1,f,g),z=new ae(L,j,0,p,g),W=new ae(new Array(0),P,0,x,_)})(),me=!0),se.l_desc=new H(se.dyn_ltree,G),se.d_desc=new H(se.dyn_dtree,z),se.bl_desc=new H(se.bl_tree,W),se.bi_buf=0,se.bi_valid=0,je(se)},a._tr_stored_block=Q,a._tr_flush_block=function(se,de,Le,Ne){var be,O,R=0;0<se.level?(se.strm.data_type===2&&(se.strm.data_type=(function(q){var J,fe=4093624447;for(J=0;J<=31;J++,fe>>>=1)if(1&fe&&q.dyn_ltree[2*J]!==0)return o;if(q.dyn_ltree[18]!==0||q.dyn_ltree[20]!==0||q.dyn_ltree[26]!==0)return l;for(J=32;J<h;J++)if(q.dyn_ltree[2*J]!==0)return l;return o})(se)),ze(se,se.l_desc),ze(se,se.d_desc),R=(function(q){var J;for(V(q,q.dyn_ltree,q.l_desc.max_code),V(q,q.dyn_dtree,q.d_desc.max_code),ze(q,q.bl_desc),J=x-1;3<=J&&q.bl_tree[2*E[J]+1]===0;J--);return q.opt_len+=3*(J+1)+5+5+4,J})(se),be=se.opt_len+3+7>>>3,(O=se.static_len+3+7>>>3)<=be&&(be=O)):be=O=Le+5,Le+4<=be&&de!==-1?Q(se,de,Le,Ne):se.strategy===4||O===be?(Z(se,2+(Ne?1:0),3),ie(se,U,L)):(Z(se,4+(Ne?1:0),3),(function(q,J,fe,le){var Be;for(Z(q,J-257,5),Z(q,fe-1,5),Z(q,le-4,4),Be=0;Be<le;Be++)Z(q,q.bl_tree[2*E[Be]+1],3);Y(q,q.dyn_ltree,J-1),Y(q,q.dyn_dtree,fe-1)})(se,se.l_desc.max_code+1,se.d_desc.max_code+1,R+1),ie(se,se.dyn_ltree,se.dyn_dtree)),je(se),Ne&&he(se)},a._tr_tally=function(se,de,Le){return se.pending_buf[se.d_buf+2*se.last_lit]=de>>>8&255,se.pending_buf[se.d_buf+2*se.last_lit+1]=255&de,se.pending_buf[se.l_buf+se.last_lit]=255&Le,se.last_lit++,de===0?se.dyn_ltree[2*Le]++:(se.matches++,de--,se.dyn_ltree[2*(D[Le]+h+1)]++,se.dyn_dtree[2*K(de)]++),se.last_lit===se.lit_bufsize-1},a._tr_align=function(se){Z(se,2,3),ve(se,N,U),(function(de){de.bi_valid===16?(te(de,de.bi_buf),de.bi_buf=0,de.bi_valid=0):8<=de.bi_valid&&(de.pending_buf[de.pending++]=255&de.bi_buf,de.bi_buf>>=8,de.bi_valid-=8)})(se)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(s){(function(o,l){if(!o.setImmediate){var c,u,d,h,f=1,p={},x=!1,v=o.document,g=Object.getPrototypeOf&&Object.getPrototypeOf(o);g=g&&g.setTimeout?g:o,c={}.toString.call(o.process)==="[object process]"?function(k){process.nextTick(function(){_(k)})}:(function(){if(o.postMessage&&!o.importScripts){var k=!0,A=o.onmessage;return o.onmessage=function(){k=!1},o.postMessage("","*"),o.onmessage=A,k}})()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",N,!1):o.attachEvent("onmessage",N),function(k){o.postMessage(h+k,"*")}):o.MessageChannel?((d=new MessageChannel).port1.onmessage=function(k){_(k.data)},function(k){d.port2.postMessage(k)}):v&&"onreadystatechange"in v.createElement("script")?(u=v.documentElement,function(k){var A=v.createElement("script");A.onreadystatechange=function(){_(k),A.onreadystatechange=null,u.removeChild(A),A=null},u.appendChild(A)}):function(k){setTimeout(_,0,k)},g.setImmediate=function(k){typeof k!="function"&&(k=new Function(""+k));for(var A=new Array(arguments.length-1),M=0;M<A.length;M++)A[M]=arguments[M+1];var C={callback:k,args:A};return p[f]=C,c(f),f++},g.clearImmediate=y}function y(k){delete p[k]}function _(k){if(x)setTimeout(_,0,k);else{var A=p[k];if(A){x=!0;try{(function(M){var C=M.callback,j=M.args;switch(j.length){case 0:C();break;case 1:C(j[0]);break;case 2:C(j[0],j[1]);break;case 3:C(j[0],j[1],j[2]);break;default:C.apply(l,j)}})(A)}finally{y(k),x=!1}}}}function N(k){k.source===o&&typeof k.data=="string"&&k.data.indexOf(h)===0&&_(+k.data.slice(h.length))}})(typeof self>"u"?s===void 0?this:s:self)}).call(this,typeof eS<"u"?eS:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(vP)),vP.exports}var gSe=pSe();const bSe=nc(gSe);function xSe(t){const e=new ri;if(!t)return e;const n=t.trim().split(/\s+/).map(parseFloat);return n.length>=12&&e.set(n[0],n[1],n[2],n[9],n[3],n[4],n[5],n[10],n[6],n[7],n[8],n[11],0,0,0,1),e}const Z8=xSe;async function J8(t,e=0){const n=[],r=t.getElementsByTagName("mesh");for(let a=0;a<r.length;a++){const s=r[a],o=[],l=[],c=s.getElementsByTagName("vertex");for(let d=0;d<c.length;d++){const h=c[d];o.push(parseFloat(h.getAttribute("x")||"0"),parseFloat(h.getAttribute("y")||"0"),parseFloat(h.getAttribute("z")||"0"))}const u=s.getElementsByTagName("triangle");for(let d=0;d<u.length;d++){const h=u[d];l.push(parseInt(h.getAttribute("v1")||"0"),parseInt(h.getAttribute("v2")||"0"),parseInt(h.getAttribute("v3")||"0"))}o.length>0&&l.length>0&&n.push({vertices:o,triangles:l,extruder:e})}return n}function e6(t){const e=Array.from(t.attributes).find(r=>{const a=r.name.toLowerCase();return a==="plate_id"||a==="plater_id"||a==="plateid"||a==="platerid"||a.endsWith(":plate_id")||a.endsWith(":plater_id")});if(!e?.value)return null;const n=Number.parseInt(e.value,10);return Number.isFinite(n)?n:null}async function ySe(t){let e;try{e=await bSe.loadAsync(t)}catch{throw new Error("Unsupported file format")}const n=new Map,r=[],a=new Map,s=new Map,o=new DOMParser;async function l(N){const k=N.startsWith("/")?N.slice(1):N,A=e.files[k];if(!A)return null;const M=await A.async("string");return o.parseFromString(M,"application/xml")}const c=new Map,u=new Map,d=new Map,h=new Map,f=e.files["Metadata/model_settings.config"];if(f)try{const N=await f.async("string"),k=o.parseFromString(N,"application/xml"),A=k.getElementsByTagName("object");for(let C=0;C<A.length;C++){const j=A[C],P=j.getAttribute("id");if(!P)continue;const E=Array.from(j.children).filter(D=>D.tagName==="metadata"&&D.getAttribute("key")==="extruder");if(E.length>0){const D=E[0].getAttribute("value");D&&c.set(P,Math.max(0,parseInt(D,10)-1))}const L=Array.from(j.children).find(D=>D.tagName==="metadata"&&D.getAttribute("key")==="name")?.getAttribute("value");L&&d.set(P,L);const B=j.getElementsByTagName("part");for(let D=0;D<B.length;D++){const $=B[D],G=$.getAttribute("id");if(!G)continue;const z=Array.from($.children).filter(W=>W.tagName==="metadata"&&W.getAttribute("key")==="extruder");if(z.length>0){const W=z[0].getAttribute("value");W&&u.set(`${P}:${G}`,Math.max(0,parseInt(W,10)-1))}}}const M=k.getElementsByTagName("plate");for(let C=0;C<M.length;C++){const j=M[C];let P=null;const E=j.getElementsByTagName("metadata");let U=0,L=0;for(let D=0;D<E.length;D++){const $=E[D],G=$.getAttribute("key");if(G==="plater_id"||G==="plate_id"){const z=$.getAttribute("value");if(z){const W=Number.parseInt(z,10);Number.isFinite(W)&&(P=W)}}else if(G==="pos_x"){const z=$.getAttribute("value"),W=z?Number.parseFloat(z):Number.NaN;Number.isFinite(W)&&(U=W)}else if(G==="pos_y"){const z=$.getAttribute("value"),W=z?Number.parseFloat(z):Number.NaN;Number.isFinite(W)&&(L=W)}}if(P==null)continue;(U!==0||L!==0)&&s.set(P,{offsetX:U,offsetY:L});const B=j.getElementsByTagName("model_instance");for(let D=0;D<B.length;D++){const G=B[D].getElementsByTagName("metadata");for(let z=0;z<G.length;z++){const W=G[z];if(W.getAttribute("key")==="object_id"){const X=W.getAttribute("value");X&&h.set(X,P)}}}}}catch{}const p=new Map,x=Object.keys(e.files).filter(N=>N.startsWith("Metadata/plate_")&&N.endsWith(".json"));for(const N of x){const k=N.match(/^Metadata\/plate_(\d+)\.json$/);if(!k)continue;const A=Number.parseInt(k[1],10);if(Number.isFinite(A))try{const M=await e.files[N].async("string"),C=JSON.parse(M),j=C.bbox_objects??[];for(const P of j)P?.name&&p.set(P.name,A);if(Array.isArray(C.bbox_all)&&C.bbox_all.length>=4){const[P,E,U,L]=C.bbox_all;[P,E,U,L].every(B=>Number.isFinite(B))&&a.set(A,{minX:P,minY:E,maxX:U,maxY:L})}}catch{}}const v=Object.keys(e.files).find(N=>N==="3D/3dmodel.model"||N.endsWith("/3dmodel.model"));if(!v){const N=Object.keys(e.files).find(k=>k.endsWith(".model"));if(N){const k=await l(N);if(k){const A=await J8(k,0);A.length>0&&n.set("1",{id:"1",meshes:A,defaultExtruder:0})}}return{objects:n,buildItems:r,plateBounds:a,plateOffsets:s}}const g=await l(v);if(!g)return{objects:n,buildItems:r,plateBounds:a,plateOffsets:s};const y=g.getElementsByTagName("object");for(let N=0;N<y.length;N++){const k=y[N],A=k.getAttribute("id");if(!A)continue;const M=e6(k)??h.get(A)??null;let C=c.get(A)??-1;if(C<0){const U=k.getAttribute("p:extruder")||k.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","extruder")||"1";C=Math.max(0,parseInt(U,10)-1)}const j=[],P=k.getElementsByTagName("mesh");for(let U=0;U<P.length;U++){const L=P[U],B=[],D=[],$=L.getElementsByTagName("vertex");for(let z=0;z<$.length;z++){const W=$[z];B.push(parseFloat(W.getAttribute("x")||"0"),parseFloat(W.getAttribute("y")||"0"),parseFloat(W.getAttribute("z")||"0"))}const G=L.getElementsByTagName("triangle");for(let z=0;z<G.length;z++){const W=G[z];D.push(parseInt(W.getAttribute("v1")||"0"),parseInt(W.getAttribute("v2")||"0"),parseInt(W.getAttribute("v3")||"0"))}B.length>0&&D.length>0&&j.push({vertices:B,triangles:D,extruder:C})}const E=k.getElementsByTagName("component");for(let U=0;U<E.length;U++){const L=E[U],B=L.getAttribute("p:path")||L.getAttributeNS("http://schemas.microsoft.com/3dmanufacturing/production/2015/06","path"),D=L.getAttribute("objectid");if(B){const $=await l(B);if($){const G=D?`${A}:${D}`:null,z=G?u.get(G)??C:C,W=await J8($,z),X=L.getAttribute("transform"),ae=Z8(X);for(const H of W)if(X){const K=[];for(let te=0;te<H.vertices.length;te+=3){const Z=new ft(H.vertices[te],H.vertices[te+1],H.vertices[te+2]);Z.applyMatrix4(ae),K.push(Z.x,Z.y,Z.z)}j.push({vertices:K,triangles:H.triangles,extruder:H.extruder})}else j.push(H)}}}j.length>0&&n.set(A,{id:A,meshes:j,defaultExtruder:C,plateId:M})}const _=g.getElementsByTagName("build");if(_.length>0){const N=_[0].getElementsByTagName("item");for(let k=0;k<N.length;k++){const A=N[k],M=A.getAttribute("objectid");if(!M)continue;const C=Z8(A.getAttribute("transform")),j=e6(A),P=n.get(M)?.plateId??null,E=d.get(M),U=E?p.get(E)??null:null;r.push({objectId:M,transform:C,plateId:j??P??U??null})}}return{objects:n,buildItems:r,plateBounds:a,plateOffsets:s}}function t6(t){const e=new wl,n=new Float32Array(t.vertices.length);for(let r=0;r<t.vertices.length;r+=3)n[r]=t.vertices[r],n[r+1]=t.vertices[r+2],n[r+2]=t.vertices[r+1];return e.setAttribute("position",new Ds(n,3)),e.setIndex(t.triangles),e.computeVertexNormals(),e}function vSe(t){t.traverse(e=>{if(e instanceof Sl)if(e.geometry.dispose(),Array.isArray(e.material))for(const n of e.material)n.dispose();else e.material.dispose()})}function wSe(t,e,n){const{objects:r,buildItems:a}=t,s=new zg,o=h=>{const p=n?.[h]||"#00ae42",x=new $n(p);return new cY({color:x,shininess:30,flatShading:!1})},l=new Map,c=a.some(h=>h.plateId!=null),u=e==null||!c?a:a.filter(h=>h.plateId===e),d=u.length>0?u:a;if(d.length>0)for(const h of d){const f=r.get(h.objectId);if(f)for(const p of f.meshes){const x=h.extruder??p.extruder,v=[];for(let y=0;y<p.vertices.length;y+=3){const _=new ft(p.vertices[y],p.vertices[y+1],p.vertices[y+2]);_.applyMatrix4(h.transform),v.push(_.x,_.y,_.z)}const g=t6({vertices:v,triangles:p.triangles});l.has(x)||l.set(x,[]),l.get(x).push(g)}}else for(const h of r.values())for(const f of h.meshes){const p=f.extruder,x=t6(f);l.has(p)||l.set(p,[]),l.get(p).push(x)}for(const[h,f]of l){if(f.length===0)continue;const p=f.length===1?f[0]:mSe(f,!1);if(p){const x=o(h),v=new Sl(p,x);s.add(v)}if(f.length>1)for(const x of f)x.dispose()}return s}function xY({url:t,fileType:e,buildVolume:n={x:256,y:256,z:256},filamentColors:r,selectedPlateId:a=null,className:s=""}){const{t:o}=Ot(),l=w.useRef(null),c=w.useRef(null),u=w.useRef(null),d=w.useRef(null),h=w.useRef(null),f=w.useRef(null),p=w.useRef(null),x=w.useRef(null),[v,g]=w.useState(!0),[y,_]=w.useState(null),[N,k]=w.useState(null),[A,M]=w.useState(null);w.useEffect(()=>{if(!l.current)return;const P=l.current,E=P.clientWidth,U=P.clientHeight,L=new Wbe;L.background=new $n(1710618),u.current=L;const B=new sl(45,E/U,.1,1e4);B.position.set(150,150,150),d.current=B;const D=new Zwe({antialias:!0});D.setSize(E,U),D.setPixelRatio(window.devicePixelRatio),P.appendChild(D.domElement),c.current=D;const $=new eSe(B,D.domElement);$.enableDamping=!0,$.dampingFactor=.05,h.current=$;const G=new lxe(16777215,.6);L.add(G);const z=new S8(16777215,.8);z.position.set(100,100,100),L.add(z);const W=new S8(16777215,.4);W.position.set(-100,50,-100),L.add(W);const X=Math.max(n.x,n.y),ae=Math.ceil(X/16),H=new uxe(X,ae,4473924,3355443);L.add(H),x.current=H;const K=new KF(n.x,n.y),te=new qF({color:44610,transparent:!0,opacity:.15,side:_c}),Z=new Sl(K,te);Z.rotation.x=-Math.PI/2,Z.position.y=-.5,L.add(Z),p.current=Z;let ve;const ce=()=>{ve=requestAnimationFrame(ce),$.update(),D.render(L,B)};ce(),g(!0),_(null),k(null),M(null);const ee=(e||t.split("?")[0].split(".").pop()||"").toLowerCase(),je={},he=rd();he&&(je.Authorization=`Bearer ${he}`),ee==="stl"?fetch(t,{headers:je}).then(ie=>{if(!ie.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return ie.arrayBuffer()}).then(ie=>{const V=new fSe().parse(ie);V.computeVertexNormals(),V.rotateX(-Math.PI/2),M(V)}).catch(ie=>{_(ie.message),g(!1)}):ee==="3mf"?fetch(t,{headers:je}).then(ie=>{if(!ie.ok)throw new Error(o("modelViewer.errors.failedToLoad"));return ie.arrayBuffer()}).then(ySe).then(ie=>{if(ie.objects.size===0)throw new Error(o("modelViewer.errors.noMeshes"));k(ie)}).catch(ie=>{_(ie.message),g(!1)}):(_(o("modelViewer.errors.unsupportedFormat")),g(!1));const oe=()=>{if(!P)return;const ie=P.clientWidth,ze=P.clientHeight;ie===0||ze===0||(B.aspect=ie/ze,B.updateProjectionMatrix(),D.setSize(ie,ze))};window.addEventListener("resize",oe);const _e=new ResizeObserver(()=>{oe()});return _e.observe(P),()=>{window.removeEventListener("resize",oe),_e.disconnect(),cancelAnimationFrame(ve),$.dispose(),D.dispose(),P.removeChild(D.domElement),f.current=null,p.current=null,x.current=null}},[t,n,e,o]),w.useEffect(()=>{if(!u.current||!d.current||!h.current||!N&&!A)return;f.current&&(u.current.remove(f.current),vSe(f.current));const P=!!A,E=P?(()=>{const ee=r?.[0]||"#00ae42",je=new cY({color:new $n(ee),shininess:30}),he=new Sl(A,je),oe=new zg;return oe.add(he),oe})():wSe(N,a??null,r);f.current=E,u.current.add(E);const U=new Rh().setFromObject(E),L=U.getCenter(new ft);E.position.y=-U.min.y;const B=!P&&a!=null&&N.buildItems.length>0?N.plateBounds.get(a):void 0,D=!P&&a!=null?N.plateOffsets.get(a):void 0,$=P||N.buildItems.length===0||a!=null&&!B&&!D,G=$?-L.x:0,z=$?-L.z:0;let W=0,X=0;if(!P&&a!=null&&N.buildItems.length>0&&B){const ee=new Rh().setFromObject(E);W=ee.min.x-B.minX,X=ee.min.z-B.minY}const ae=n.x/2,H=n.y/2;!P&&a!=null&&N.buildItems.length>0&&B?(E.position.x=G-W,E.position.z=z-X):!P&&a!=null&&D?(E.position.x=G+(ae-D.offsetX),E.position.z=z+(H-D.offsetY)):$?(E.position.x=G+ae,E.position.z=z+H):(E.position.x=G,E.position.z=z),p.current&&(p.current.position.x=ae,p.current.position.z=H),x.current&&(x.current.position.x=ae,x.current.position.z=H);const K=new Rh().setFromObject(E),te=K.getCenter(new ft),Z=K.getSize(new ft),ce=Math.max(Z.x,Z.y,Z.z)*1.8;d.current.position.set(te.x+ce*.7,te.y+ce*.5,te.z+ce*.7),h.current.target.copy(te),h.current.update(),g(!1)},[N,A,a,r,n]);const C=()=>{d.current&&h.current&&(d.current.position.set(150,150,150),h.current.target.set(0,50,0),h.current.update())},j=P=>{d.current&&d.current.position.multiplyScalar(P)};return i.jsxs("div",{className:`relative ${s}`,children:[i.jsx("div",{ref:l,className:"w-full h-full min-h-[400px]"}),v&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}),y&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsx("p",{className:"text-red-400",children:y})}),!v&&!y&&i.jsxs("div",{className:"absolute bottom-4 right-4 flex gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>j(.8),children:i.jsx(EF,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>j(1.25),children:i.jsx(jF,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:C,children:i.jsx(so,{className:"w-4 h-4"})})]})]})}const sk="159",ng={ROTATE:0,DOLLY:1,PAN:2},rg={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},SSe=0,n6=1,_Se=2,yY=1,NSe=2,Mu=3,Wh=0,no=1,Du=2,Fh=0,Zg=1,r6=2,a6=3,i6=4,CSe=5,Km=100,kSe=101,ASe=102,s6=103,o6=104,TSe=200,MSe=201,PSe=202,ESe=203,nD=204,rD=205,jSe=206,DSe=207,RSe=208,FSe=209,LSe=210,OSe=211,ISe=212,zSe=213,USe=214,BSe=0,HSe=1,$Se=2,j1=3,VSe=4,qSe=5,GSe=6,WSe=7,QF=0,KSe=1,XSe=2,Lh=0,YSe=1,QSe=2,ZSe=3,JSe=4,e_e=5,vY=300,yb=301,vb=302,aD=303,iD=304,ok=306,sD=1e3,Ul=1001,oD=1002,Xi=1003,l6=1004,wP=1005,ol=1006,t_e=1007,Cv=1008,Oh=1009,n_e=1010,r_e=1011,ZF=1012,wY=1013,wh=1014,zu=1015,kv=1016,SY=1017,_Y=1018,mf=1020,a_e=1021,ll=1023,i_e=1024,s_e=1025,ff=1026,wb=1027,o_e=1028,NY=1029,l_e=1030,CY=1031,kY=1033,SP=33776,_P=33777,NP=33778,CP=33779,c6=35840,u6=35841,d6=35842,h6=35843,AY=36196,m6=37492,f6=37496,p6=37808,g6=37809,b6=37810,x6=37811,y6=37812,v6=37813,w6=37814,S6=37815,_6=37816,N6=37817,C6=37818,k6=37819,A6=37820,T6=37821,kP=36492,M6=36494,P6=36495,c_e=36283,E6=36284,j6=36285,D6=36286,TY=3e3,pf=3001,u_e=3200,d_e=3201,MY=0,h_e=1,cl="",Yi="srgb",id="srgb-linear",JF="display-p3",lk="display-p3-linear",D1="linear",ea="srgb",R1="rec709",F1="p3",ag=7680,R6=519,m_e=512,f_e=513,p_e=514,PY=515,g_e=516,b_e=517,x_e=518,y_e=519,lD=35044,F6="300 es",cD=1035,Ac=2e3,Av=2001;class rp{addEventListener(e,n){this._listeners===void 0&&(this._listeners={});const r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(n)===-1&&r[e].push(n)}hasEventListener(e,n){if(this._listeners===void 0)return!1;const r=this._listeners;return r[e]!==void 0&&r[e].indexOf(n)!==-1}removeEventListener(e,n){if(this._listeners===void 0)return;const a=this._listeners[e];if(a!==void 0){const s=a.indexOf(n);s!==-1&&a.splice(s,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const r=this._listeners[e.type];if(r!==void 0){e.target=this;const a=r.slice(0);for(let s=0,o=a.length;s<o;s++)a[s].call(this,e);e.target=null}}}const ls=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let L6=1234567;const qy=Math.PI/180,Tv=180/Math.PI;function Gu(){const t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(ls[t&255]+ls[t>>8&255]+ls[t>>16&255]+ls[t>>24&255]+"-"+ls[e&255]+ls[e>>8&255]+"-"+ls[e>>16&15|64]+ls[e>>24&255]+"-"+ls[n&63|128]+ls[n>>8&255]+"-"+ls[n>>16&255]+ls[n>>24&255]+ls[r&255]+ls[r>>8&255]+ls[r>>16&255]+ls[r>>24&255]).toLowerCase()}function Qi(t,e,n){return Math.max(e,Math.min(n,t))}function eL(t,e){return(t%e+e)%e}function v_e(t,e,n,r,a){return r+(t-e)*(a-r)/(n-e)}function w_e(t,e,n){return t!==e?(n-t)/(e-t):0}function Gy(t,e,n){return(1-n)*t+n*e}function S_e(t,e,n,r){return Gy(t,e,1-Math.exp(-n*r))}function __e(t,e=1){return e-Math.abs(eL(t,e*2)-e)}function N_e(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*(3-2*t))}function C_e(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e),t*t*t*(t*(t*6-15)+10))}function k_e(t,e){return t+Math.floor(Math.random()*(e-t+1))}function A_e(t,e){return t+Math.random()*(e-t)}function T_e(t){return t*(.5-Math.random())}function M_e(t){t!==void 0&&(L6=t);let e=L6+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function P_e(t){return t*qy}function E_e(t){return t*Tv}function uD(t){return(t&t-1)===0&&t!==0}function j_e(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))}function L1(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function D_e(t,e,n,r,a){const s=Math.cos,o=Math.sin,l=s(n/2),c=o(n/2),u=s((e+r)/2),d=o((e+r)/2),h=s((e-r)/2),f=o((e-r)/2),p=s((r-e)/2),x=o((r-e)/2);switch(a){case"XYX":t.set(l*d,c*h,c*f,l*u);break;case"YZY":t.set(c*f,l*d,c*h,l*u);break;case"ZXZ":t.set(c*h,c*f,l*d,l*u);break;case"XZX":t.set(l*d,c*x,c*p,l*u);break;case"YXY":t.set(c*p,l*d,c*x,l*u);break;case"ZYZ":t.set(c*x,c*p,l*d,l*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+a)}}function Nc(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Rr(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(t*4294967295);case Uint16Array:return Math.round(t*65535);case Uint8Array:return Math.round(t*255);case Int32Array:return Math.round(t*2147483647);case Int16Array:return Math.round(t*32767);case Int8Array:return Math.round(t*127);default:throw new Error("Invalid component type.")}}const EY={DEG2RAD:qy,RAD2DEG:Tv,generateUUID:Gu,clamp:Qi,euclideanModulo:eL,mapLinear:v_e,inverseLerp:w_e,lerp:Gy,damp:S_e,pingpong:__e,smoothstep:N_e,smootherstep:C_e,randInt:k_e,randFloat:A_e,randFloatSpread:T_e,seededRandom:M_e,degToRad:P_e,radToDeg:E_e,isPowerOfTwo:uD,ceilPowerOfTwo:j_e,floorPowerOfTwo:L1,setQuaternionFromProperEuler:D_e,normalize:Rr,denormalize:Nc};class _n{constructor(e=0,n=0){_n.prototype.isVector2=!0,this.x=e,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,n){return this.x=e,this.y=n,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const n=this.x,r=this.y,a=e.elements;return this.x=a[0]*n+a[3]*r+a[6],this.y=a[1]*n+a[4]*r+a[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Qi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y;return n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this}rotateAround(e,n){const r=Math.cos(n),a=Math.sin(n),s=this.x-e.x,o=this.y-e.y;return this.x=s*r-o*a+e.x,this.y=s*a+o*r+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class qn{constructor(e,n,r,a,s,o,l,c,u){qn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,n,r,a,s,o,l,c,u)}set(e,n,r,a,s,o,l,c,u){const d=this.elements;return d[0]=e,d[1]=a,d[2]=l,d[3]=n,d[4]=s,d[5]=c,d[6]=r,d[7]=o,d[8]=u,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],this}extractBasis(e,n,r){return e.setFromMatrix3Column(this,0),n.setFromMatrix3Column(this,1),r.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const n=e.elements;return this.set(n[0],n[4],n[8],n[1],n[5],n[9],n[2],n[6],n[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,a=n.elements,s=this.elements,o=r[0],l=r[3],c=r[6],u=r[1],d=r[4],h=r[7],f=r[2],p=r[5],x=r[8],v=a[0],g=a[3],y=a[6],_=a[1],N=a[4],k=a[7],A=a[2],M=a[5],C=a[8];return s[0]=o*v+l*_+c*A,s[3]=o*g+l*N+c*M,s[6]=o*y+l*k+c*C,s[1]=u*v+d*_+h*A,s[4]=u*g+d*N+h*M,s[7]=u*y+d*k+h*C,s[2]=f*v+p*_+x*A,s[5]=f*g+p*N+x*M,s[8]=f*y+p*k+x*C,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[3]*=e,n[6]*=e,n[1]*=e,n[4]*=e,n[7]*=e,n[2]*=e,n[5]*=e,n[8]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8];return n*o*d-n*l*u-r*s*d+r*l*c+a*s*u-a*o*c}invert(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=d*o-l*u,f=l*c-d*s,p=u*s-o*c,x=n*h+r*f+a*p;if(x===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/x;return e[0]=h*v,e[1]=(a*u-d*r)*v,e[2]=(l*r-a*o)*v,e[3]=f*v,e[4]=(d*n-a*c)*v,e[5]=(a*s-l*n)*v,e[6]=p*v,e[7]=(r*c-u*n)*v,e[8]=(o*n-r*s)*v,this}transpose(){let e;const n=this.elements;return e=n[1],n[1]=n[3],n[3]=e,e=n[2],n[2]=n[6],n[6]=e,e=n[5],n[5]=n[7],n[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const n=this.elements;return e[0]=n[0],e[1]=n[3],e[2]=n[6],e[3]=n[1],e[4]=n[4],e[5]=n[7],e[6]=n[2],e[7]=n[5],e[8]=n[8],this}setUvTransform(e,n,r,a,s,o,l){const c=Math.cos(s),u=Math.sin(s);return this.set(r*c,r*u,-r*(c*o+u*l)+o+e,-a*u,a*c,-a*(-u*o+c*l)+l+n,0,0,1),this}scale(e,n){return this.premultiply(AP.makeScale(e,n)),this}rotate(e){return this.premultiply(AP.makeRotation(-e)),this}translate(e,n){return this.premultiply(AP.makeTranslation(e,n)),this}makeTranslation(e,n){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,n,0,0,1),this}makeRotation(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,r,n,0,0,0,1),this}makeScale(e,n){return this.set(e,0,0,0,n,0,0,0,1),this}equals(e){const n=this.elements,r=e.elements;for(let a=0;a<9;a++)if(n[a]!==r[a])return!1;return!0}fromArray(e,n=0){for(let r=0;r<9;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const AP=new qn;function jY(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}function O1(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function R_e(){const t=O1("canvas");return t.style.display="block",t}const O6={};function Wy(t){t in O6||(O6[t]=!0,console.warn(t))}const I6=new qn().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),z6=new qn().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),MS={[id]:{transfer:D1,primaries:R1,toReference:t=>t,fromReference:t=>t},[Yi]:{transfer:ea,primaries:R1,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[lk]:{transfer:D1,primaries:F1,toReference:t=>t.applyMatrix3(z6),fromReference:t=>t.applyMatrix3(I6)},[JF]:{transfer:ea,primaries:F1,toReference:t=>t.convertSRGBToLinear().applyMatrix3(z6),fromReference:t=>t.applyMatrix3(I6).convertLinearToSRGB()}},F_e=new Set([id,lk]),Fr={enabled:!0,_workingColorSpace:id,get legacyMode(){return console.warn("THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150."),!this.enabled},set legacyMode(t){console.warn("THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150."),this.enabled=!t},get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!F_e.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(this.enabled===!1||e===n||!e||!n)return t;const r=MS[e].toReference,a=MS[n].fromReference;return a(r(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return MS[t].primaries},getTransfer:function(t){return t===cl?D1:MS[t].transfer}};function Jg(t){return t<.04045?t*.0773993808:Math.pow(t*.9478672986+.0521327014,2.4)}function TP(t){return t<.0031308?t*12.92:1.055*Math.pow(t,.41666)-.055}let ig;class DY{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{ig===void 0&&(ig=O1("canvas")),ig.width=e.width,ig.height=e.height;const r=ig.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),n=ig}return n.width>2048||n.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),n.toDataURL("image/jpeg",.6)):n.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const n=O1("canvas");n.width=e.width,n.height=e.height;const r=n.getContext("2d");r.drawImage(e,0,0,e.width,e.height);const a=r.getImageData(0,0,e.width,e.height),s=a.data;for(let o=0;o<s.length;o++)s[o]=Jg(s[o]/255)*255;return r.putImageData(a,0,0),n}else if(e.data){const n=e.data.slice(0);for(let r=0;r<n.length;r++)n instanceof Uint8Array||n instanceof Uint8ClampedArray?n[r]=Math.floor(Jg(n[r]/255)*255):n[r]=Jg(n[r]);return{data:n,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let L_e=0;class RY{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:L_e++}),this.uuid=Gu(),this.data=e,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const r={uuid:this.uuid,url:""},a=this.data;if(a!==null){let s;if(Array.isArray(a)){s=[];for(let o=0,l=a.length;o<l;o++)a[o].isDataTexture?s.push(MP(a[o].image)):s.push(MP(a[o]))}else s=MP(a);r.url=s}return n||(e.images[this.uuid]=r),r}}function MP(t){return typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap?DY.getDataURL(t):t.data?{data:Array.from(t.data),width:t.width,height:t.height,type:t.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let O_e=0;class ro extends rp{constructor(e=ro.DEFAULT_IMAGE,n=ro.DEFAULT_MAPPING,r=Ul,a=Ul,s=ol,o=Cv,l=ll,c=Oh,u=ro.DEFAULT_ANISOTROPY,d=cl){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:O_e++}),this.uuid=Gu(),this.name="",this.source=new RY(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=a,this.magFilter=s,this.minFilter=o,this.anisotropy=u,this.format=l,this.internalFormat=null,this.type=c,this.offset=new _n(0,0),this.repeat=new _n(1,1),this.center=new _n(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new qn,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof d=="string"?this.colorSpace=d:(Wy("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=d===pf?Yi:cl),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.needsPMREMUpdate=!1}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){const n=e===void 0||typeof e=="string";if(!n&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const r={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(r.userData=this.userData),n||(e.textures[this.uuid]=r),r}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==vY)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case sD:e.x=e.x-Math.floor(e.x);break;case Ul:e.x=e.x<0?0:1;break;case oD:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case sD:e.y=e.y-Math.floor(e.y);break;case Ul:e.y=e.y<0?0:1;break;case oD:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}get encoding(){return Wy("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Yi?pf:TY}set encoding(e){Wy("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===pf?Yi:cl}}ro.DEFAULT_IMAGE=null;ro.DEFAULT_MAPPING=vY;ro.DEFAULT_ANISOTROPY=1;class Or{constructor(e=0,n=0,r=0,a=1){Or.prototype.isVector4=!0,this.x=e,this.y=n,this.z=r,this.w=a}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,n,r,a){return this.x=e,this.y=n,this.z=r,this.w=a,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;case 3:this.w=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this.w=e.w+n.w,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this.w+=e.w*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this.w=e.w-n.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const n=this.x,r=this.y,a=this.z,s=this.w,o=e.elements;return this.x=o[0]*n+o[4]*r+o[8]*a+o[12]*s,this.y=o[1]*n+o[5]*r+o[9]*a+o[13]*s,this.z=o[2]*n+o[6]*r+o[10]*a+o[14]*s,this.w=o[3]*n+o[7]*r+o[11]*a+o[15]*s,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const n=Math.sqrt(1-e.w*e.w);return n<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/n,this.y=e.y/n,this.z=e.z/n),this}setAxisAngleFromRotationMatrix(e){let n,r,a,s;const c=e.elements,u=c[0],d=c[4],h=c[8],f=c[1],p=c[5],x=c[9],v=c[2],g=c[6],y=c[10];if(Math.abs(d-f)<.01&&Math.abs(h-v)<.01&&Math.abs(x-g)<.01){if(Math.abs(d+f)<.1&&Math.abs(h+v)<.1&&Math.abs(x+g)<.1&&Math.abs(u+p+y-3)<.1)return this.set(1,0,0,0),this;n=Math.PI;const N=(u+1)/2,k=(p+1)/2,A=(y+1)/2,M=(d+f)/4,C=(h+v)/4,j=(x+g)/4;return N>k&&N>A?N<.01?(r=0,a=.707106781,s=.707106781):(r=Math.sqrt(N),a=M/r,s=C/r):k>A?k<.01?(r=.707106781,a=0,s=.707106781):(a=Math.sqrt(k),r=M/a,s=j/a):A<.01?(r=.707106781,a=.707106781,s=0):(s=Math.sqrt(A),r=C/s,a=j/s),this.set(r,a,s,n),this}let _=Math.sqrt((g-x)*(g-x)+(h-v)*(h-v)+(f-d)*(f-d));return Math.abs(_)<.001&&(_=1),this.x=(g-x)/_,this.y=(h-v)/_,this.z=(f-d)/_,this.w=Math.acos((u+p+y-1)/2),this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this.w=Math.max(e.w,Math.min(n.w,this.w)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this.w=Math.max(e,Math.min(n,this.w)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this.w+=(e.w-this.w)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this.w=e.w+(n.w-e.w)*r,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this.w=e[n+3],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e[n+3]=this.w,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this.w=e.getW(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class I_e extends rp{constructor(e=1,n=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=n,this.depth=1,this.scissor=new Or(0,0,e,n),this.scissorTest=!1,this.viewport=new Or(0,0,e,n);const a={width:e,height:n,depth:1};r.encoding!==void 0&&(Wy("THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace."),r.colorSpace=r.encoding===pf?Yi:cl),r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ol,depthBuffer:!0,stencilBuffer:!1,depthTexture:null,samples:0},r),this.texture=new ro(a,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.flipY=!1,this.texture.generateMipmaps=r.generateMipmaps,this.texture.internalFormat=r.internalFormat,this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.depthTexture=r.depthTexture,this.samples=r.samples}setSize(e,n,r=1){(this.width!==e||this.height!==n||this.depth!==r)&&(this.width=e,this.height=n,this.depth=r,this.texture.image.width=e,this.texture.image.height=n,this.texture.image.depth=r,this.dispose()),this.viewport.set(0,0,e,n),this.scissor.set(0,0,e,n)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.texture=e.texture.clone(),this.texture.isRenderTargetTexture=!0;const n=Object.assign({},e.texture.image);return this.texture.source=new RY(n),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class If extends I_e{constructor(e=1,n=1,r={}){super(e,n,r),this.isWebGLRenderTarget=!0}}class FY extends ro{constructor(e=null,n=1,r=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:r,depth:a},this.magFilter=Xi,this.minFilter=Xi,this.wrapR=Ul,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class z_e extends ro{constructor(e=null,n=1,r=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:r,depth:a},this.magFilter=Xi,this.minFilter=Xi,this.wrapR=Ul,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class zf{constructor(e=0,n=0,r=0,a=1){this.isQuaternion=!0,this._x=e,this._y=n,this._z=r,this._w=a}static slerpFlat(e,n,r,a,s,o,l){let c=r[a+0],u=r[a+1],d=r[a+2],h=r[a+3];const f=s[o+0],p=s[o+1],x=s[o+2],v=s[o+3];if(l===0){e[n+0]=c,e[n+1]=u,e[n+2]=d,e[n+3]=h;return}if(l===1){e[n+0]=f,e[n+1]=p,e[n+2]=x,e[n+3]=v;return}if(h!==v||c!==f||u!==p||d!==x){let g=1-l;const y=c*f+u*p+d*x+h*v,_=y>=0?1:-1,N=1-y*y;if(N>Number.EPSILON){const A=Math.sqrt(N),M=Math.atan2(A,y*_);g=Math.sin(g*M)/A,l=Math.sin(l*M)/A}const k=l*_;if(c=c*g+f*k,u=u*g+p*k,d=d*g+x*k,h=h*g+v*k,g===1-l){const A=1/Math.sqrt(c*c+u*u+d*d+h*h);c*=A,u*=A,d*=A,h*=A}}e[n]=c,e[n+1]=u,e[n+2]=d,e[n+3]=h}static multiplyQuaternionsFlat(e,n,r,a,s,o){const l=r[a],c=r[a+1],u=r[a+2],d=r[a+3],h=s[o],f=s[o+1],p=s[o+2],x=s[o+3];return e[n]=l*x+d*h+c*p-u*f,e[n+1]=c*x+d*f+u*h-l*p,e[n+2]=u*x+d*p+l*f-c*h,e[n+3]=d*x-l*h-c*f-u*p,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,n,r,a){return this._x=e,this._y=n,this._z=r,this._w=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,n){const r=e._x,a=e._y,s=e._z,o=e._order,l=Math.cos,c=Math.sin,u=l(r/2),d=l(a/2),h=l(s/2),f=c(r/2),p=c(a/2),x=c(s/2);switch(o){case"XYZ":this._x=f*d*h+u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h-f*p*x;break;case"YXZ":this._x=f*d*h+u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h+f*p*x;break;case"ZXY":this._x=f*d*h-u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h-f*p*x;break;case"ZYX":this._x=f*d*h-u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h+f*p*x;break;case"YZX":this._x=f*d*h+u*p*x,this._y=u*p*h+f*d*x,this._z=u*d*x-f*p*h,this._w=u*d*h-f*p*x;break;case"XZY":this._x=f*d*h-u*p*x,this._y=u*p*h-f*d*x,this._z=u*d*x+f*p*h,this._w=u*d*h+f*p*x;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return n!==!1&&this._onChangeCallback(),this}setFromAxisAngle(e,n){const r=n/2,a=Math.sin(r);return this._x=e.x*a,this._y=e.y*a,this._z=e.z*a,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){const n=e.elements,r=n[0],a=n[4],s=n[8],o=n[1],l=n[5],c=n[9],u=n[2],d=n[6],h=n[10],f=r+l+h;if(f>0){const p=.5/Math.sqrt(f+1);this._w=.25/p,this._x=(d-c)*p,this._y=(s-u)*p,this._z=(o-a)*p}else if(r>l&&r>h){const p=2*Math.sqrt(1+r-l-h);this._w=(d-c)/p,this._x=.25*p,this._y=(a+o)/p,this._z=(s+u)/p}else if(l>h){const p=2*Math.sqrt(1+l-r-h);this._w=(s-u)/p,this._x=(a+o)/p,this._y=.25*p,this._z=(c+d)/p}else{const p=2*Math.sqrt(1+h-r-l);this._w=(o-a)/p,this._x=(s+u)/p,this._y=(c+d)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,n){let r=e.dot(n)+1;return r<Number.EPSILON?(r=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*n.z-e.z*n.y,this._y=e.z*n.x-e.x*n.z,this._z=e.x*n.y-e.y*n.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Qi(this.dot(e),-1,1)))}rotateTowards(e,n){const r=this.angleTo(e);if(r===0)return this;const a=Math.min(1,n/r);return this.slerp(e,a),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,n){const r=e._x,a=e._y,s=e._z,o=e._w,l=n._x,c=n._y,u=n._z,d=n._w;return this._x=r*d+o*l+a*u-s*c,this._y=a*d+o*c+s*l-r*u,this._z=s*d+o*u+r*c-a*l,this._w=o*d-r*l-a*c-s*u,this._onChangeCallback(),this}slerp(e,n){if(n===0)return this;if(n===1)return this.copy(e);const r=this._x,a=this._y,s=this._z,o=this._w;let l=o*e._w+r*e._x+a*e._y+s*e._z;if(l<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,l=-l):this.copy(e),l>=1)return this._w=o,this._x=r,this._y=a,this._z=s,this;const c=1-l*l;if(c<=Number.EPSILON){const p=1-n;return this._w=p*o+n*this._w,this._x=p*r+n*this._x,this._y=p*a+n*this._y,this._z=p*s+n*this._z,this.normalize(),this._onChangeCallback(),this}const u=Math.sqrt(c),d=Math.atan2(u,l),h=Math.sin((1-n)*d)/u,f=Math.sin(n*d)/u;return this._w=o*h+this._w*f,this._x=r*h+this._x*f,this._y=a*h+this._y*f,this._z=s*h+this._z*f,this._onChangeCallback(),this}slerpQuaternions(e,n,r){return this.copy(e).slerp(n,r)}random(){const e=Math.random(),n=Math.sqrt(1-e),r=Math.sqrt(e),a=2*Math.PI*Math.random(),s=2*Math.PI*Math.random();return this.set(n*Math.cos(a),r*Math.sin(s),r*Math.cos(s),n*Math.sin(a))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,n=0){return this._x=e[n],this._y=e[n+1],this._z=e[n+2],this._w=e[n+3],this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._w,e}fromBufferAttribute(e,n){return this._x=e.getX(n),this._y=e.getY(n),this._z=e.getZ(n),this._w=e.getW(n),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ze{constructor(e=0,n=0,r=0){Ze.prototype.isVector3=!0,this.x=e,this.y=n,this.z=r}set(e,n,r){return r===void 0&&(r=this.z),this.x=e,this.y=n,this.z=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,n){switch(e){case 0:this.x=n;break;case 1:this.y=n;break;case 2:this.z=n;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,n){return this.x=e.x+n.x,this.y=e.y+n.y,this.z=e.z+n.z,this}addScaledVector(e,n){return this.x+=e.x*n,this.y+=e.y*n,this.z+=e.z*n,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,n){return this.x=e.x-n.x,this.y=e.y-n.y,this.z=e.z-n.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,n){return this.x=e.x*n.x,this.y=e.y*n.y,this.z=e.z*n.z,this}applyEuler(e){return this.applyQuaternion(U6.setFromEuler(e))}applyAxisAngle(e,n){return this.applyQuaternion(U6.setFromAxisAngle(e,n))}applyMatrix3(e){const n=this.x,r=this.y,a=this.z,s=e.elements;return this.x=s[0]*n+s[3]*r+s[6]*a,this.y=s[1]*n+s[4]*r+s[7]*a,this.z=s[2]*n+s[5]*r+s[8]*a,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const n=this.x,r=this.y,a=this.z,s=e.elements,o=1/(s[3]*n+s[7]*r+s[11]*a+s[15]);return this.x=(s[0]*n+s[4]*r+s[8]*a+s[12])*o,this.y=(s[1]*n+s[5]*r+s[9]*a+s[13])*o,this.z=(s[2]*n+s[6]*r+s[10]*a+s[14])*o,this}applyQuaternion(e){const n=this.x,r=this.y,a=this.z,s=e.x,o=e.y,l=e.z,c=e.w,u=2*(o*a-l*r),d=2*(l*n-s*a),h=2*(s*r-o*n);return this.x=n+c*u+o*h-l*d,this.y=r+c*d+l*u-s*h,this.z=a+c*h+s*d-o*u,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const n=this.x,r=this.y,a=this.z,s=e.elements;return this.x=s[0]*n+s[4]*r+s[8]*a,this.y=s[1]*n+s[5]*r+s[9]*a,this.z=s[2]*n+s[6]*r+s[10]*a,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,n){return this.x=Math.max(e.x,Math.min(n.x,this.x)),this.y=Math.max(e.y,Math.min(n.y,this.y)),this.z=Math.max(e.z,Math.min(n.z,this.z)),this}clampScalar(e,n){return this.x=Math.max(e,Math.min(n,this.x)),this.y=Math.max(e,Math.min(n,this.y)),this.z=Math.max(e,Math.min(n,this.z)),this}clampLength(e,n){const r=this.length();return this.divideScalar(r||1).multiplyScalar(Math.max(e,Math.min(n,r)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,n){return this.x+=(e.x-this.x)*n,this.y+=(e.y-this.y)*n,this.z+=(e.z-this.z)*n,this}lerpVectors(e,n,r){return this.x=e.x+(n.x-e.x)*r,this.y=e.y+(n.y-e.y)*r,this.z=e.z+(n.z-e.z)*r,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,n){const r=e.x,a=e.y,s=e.z,o=n.x,l=n.y,c=n.z;return this.x=a*c-s*l,this.y=s*o-r*c,this.z=r*l-a*o,this}projectOnVector(e){const n=e.lengthSq();if(n===0)return this.set(0,0,0);const r=e.dot(this)/n;return this.copy(e).multiplyScalar(r)}projectOnPlane(e){return PP.copy(this).projectOnVector(e),this.sub(PP)}reflect(e){return this.sub(PP.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const n=Math.sqrt(this.lengthSq()*e.lengthSq());if(n===0)return Math.PI/2;const r=this.dot(e)/n;return Math.acos(Qi(r,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const n=this.x-e.x,r=this.y-e.y,a=this.z-e.z;return n*n+r*r+a*a}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,n,r){const a=Math.sin(n)*e;return this.x=a*Math.sin(r),this.y=Math.cos(n)*e,this.z=a*Math.cos(r),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,n,r){return this.x=e*Math.sin(n),this.y=r,this.z=e*Math.cos(n),this}setFromMatrixPosition(e){const n=e.elements;return this.x=n[12],this.y=n[13],this.z=n[14],this}setFromMatrixScale(e){const n=this.setFromMatrixColumn(e,0).length(),r=this.setFromMatrixColumn(e,1).length(),a=this.setFromMatrixColumn(e,2).length();return this.x=n,this.y=r,this.z=a,this}setFromMatrixColumn(e,n){return this.fromArray(e.elements,n*4)}setFromMatrix3Column(e,n){return this.fromArray(e.elements,n*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,n=0){return this.x=e[n],this.y=e[n+1],this.z=e[n+2],this}toArray(e=[],n=0){return e[n]=this.x,e[n+1]=this.y,e[n+2]=this.z,e}fromBufferAttribute(e,n){return this.x=e.getX(n),this.y=e.getY(n),this.z=e.getZ(n),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=(Math.random()-.5)*2,n=Math.random()*Math.PI*2,r=Math.sqrt(1-e**2);return this.x=r*Math.cos(n),this.y=r*Math.sin(n),this.z=e,this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const PP=new Ze,U6=new zf;class pl{constructor(e=new Ze(1/0,1/0,1/0),n=new Ze(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=n}set(e,n){return this.min.copy(e),this.max.copy(n),this}setFromArray(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n+=3)this.expandByPoint(Ll.fromArray(e,n));return this}setFromBufferAttribute(e){this.makeEmpty();for(let n=0,r=e.count;n<r;n++)this.expandByPoint(Ll.fromBufferAttribute(e,n));return this}setFromPoints(e){this.makeEmpty();for(let n=0,r=e.length;n<r;n++)this.expandByPoint(e[n]);return this}setFromCenterAndSize(e,n){const r=Ll.copy(n).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}setFromObject(e,n=!1){return this.makeEmpty(),this.expandByObject(e,n)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,n=!1){e.updateWorldMatrix(!1,!1);const r=e.geometry;if(r!==void 0){const s=r.getAttribute("position");if(n===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,l=s.count;o<l;o++)e.isMesh===!0?e.getVertexPosition(o,Ll):Ll.fromBufferAttribute(s,o),Ll.applyMatrix4(e.matrixWorld),this.expandByPoint(Ll);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),PS.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),PS.copy(r.boundingBox)),PS.applyMatrix4(e.matrixWorld),this.union(PS)}const a=e.children;for(let s=0,o=a.length;s<o;s++)this.expandByObject(a[s],n);return this}containsPoint(e){return!(e.x<this.min.x||e.x>this.max.x||e.y<this.min.y||e.y>this.max.y||e.z<this.min.z||e.z>this.max.z)}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,n){return n.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return!(e.max.x<this.min.x||e.min.x>this.max.x||e.max.y<this.min.y||e.min.y>this.max.y||e.max.z<this.min.z||e.min.z>this.max.z)}intersectsSphere(e){return this.clampPoint(e.center,Ll),Ll.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let n,r;return e.normal.x>0?(n=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(n=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(n+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(n+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(n+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(n+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),n<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ly),ES.subVectors(this.max,ly),sg.subVectors(e.a,ly),og.subVectors(e.b,ly),lg.subVectors(e.c,ly),Kd.subVectors(og,sg),Xd.subVectors(lg,og),jm.subVectors(sg,lg);let n=[0,-Kd.z,Kd.y,0,-Xd.z,Xd.y,0,-jm.z,jm.y,Kd.z,0,-Kd.x,Xd.z,0,-Xd.x,jm.z,0,-jm.x,-Kd.y,Kd.x,0,-Xd.y,Xd.x,0,-jm.y,jm.x,0];return!EP(n,sg,og,lg,ES)||(n=[1,0,0,0,1,0,0,0,1],!EP(n,sg,og,lg,ES))?!1:(jS.crossVectors(Kd,Xd),n=[jS.x,jS.y,jS.z],EP(n,sg,og,lg,ES))}clampPoint(e,n){return n.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ll).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ll).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(yu[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),yu[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),yu[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),yu[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),yu[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),yu[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),yu[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),yu[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(yu),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const yu=[new Ze,new Ze,new Ze,new Ze,new Ze,new Ze,new Ze,new Ze],Ll=new Ze,PS=new pl,sg=new Ze,og=new Ze,lg=new Ze,Kd=new Ze,Xd=new Ze,jm=new Ze,ly=new Ze,ES=new Ze,jS=new Ze,Dm=new Ze;function EP(t,e,n,r,a){for(let s=0,o=t.length-3;s<=o;s+=3){Dm.fromArray(t,s);const l=a.x*Math.abs(Dm.x)+a.y*Math.abs(Dm.y)+a.z*Math.abs(Dm.z),c=e.dot(Dm),u=n.dot(Dm),d=r.dot(Dm);if(Math.max(-Math.max(c,u,d),Math.min(c,u,d))>l)return!1}return!0}const U_e=new pl,cy=new Ze,jP=new Ze;class jc{constructor(e=new Ze,n=-1){this.center=e,this.radius=n}set(e,n){return this.center.copy(e),this.radius=n,this}setFromPoints(e,n){const r=this.center;n!==void 0?r.copy(n):U_e.setFromPoints(e).getCenter(r);let a=0;for(let s=0,o=e.length;s<o;s++)a=Math.max(a,r.distanceToSquared(e[s]));return this.radius=Math.sqrt(a),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const n=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=n*n}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,n){const r=this.center.distanceToSquared(e);return n.copy(e),r>this.radius*this.radius&&(n.sub(this.center).normalize(),n.multiplyScalar(this.radius).add(this.center)),n}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;cy.subVectors(e,this.center);const n=cy.lengthSq();if(n>this.radius*this.radius){const r=Math.sqrt(n),a=(r-this.radius)*.5;this.center.addScaledVector(cy,a/r),this.radius+=a}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(jP.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cy.copy(e.center).add(jP)),this.expandByPoint(cy.copy(e.center).sub(jP))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const vu=new Ze,DP=new Ze,DS=new Ze,Yd=new Ze,RP=new Ze,RS=new Ze,FP=new Ze;class tL{constructor(e=new Ze,n=new Ze(0,0,-1)){this.origin=e,this.direction=n}set(e,n){return this.origin.copy(e),this.direction.copy(n),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,n){return n.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,vu)),this}closestPointToPoint(e,n){n.subVectors(e,this.origin);const r=n.dot(this.direction);return r<0?n.copy(this.origin):n.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const n=vu.subVectors(e,this.origin).dot(this.direction);return n<0?this.origin.distanceToSquared(e):(vu.copy(this.origin).addScaledVector(this.direction,n),vu.distanceToSquared(e))}distanceSqToSegment(e,n,r,a){DP.copy(e).add(n).multiplyScalar(.5),DS.copy(n).sub(e).normalize(),Yd.copy(this.origin).sub(DP);const s=e.distanceTo(n)*.5,o=-this.direction.dot(DS),l=Yd.dot(this.direction),c=-Yd.dot(DS),u=Yd.lengthSq(),d=Math.abs(1-o*o);let h,f,p,x;if(d>0)if(h=o*c-l,f=o*l-c,x=s*d,h>=0)if(f>=-x)if(f<=x){const v=1/d;h*=v,f*=v,p=h*(h+o*f+2*l)+f*(o*h+f+2*c)+u}else f=s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;else f=-s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;else f<=-x?(h=Math.max(0,-(-o*s+l)),f=h>0?-s:Math.min(Math.max(-s,-c),s),p=-h*h+f*(f+2*c)+u):f<=x?(h=0,f=Math.min(Math.max(-s,-c),s),p=f*(f+2*c)+u):(h=Math.max(0,-(o*s+l)),f=h>0?s:Math.min(Math.max(-s,-c),s),p=-h*h+f*(f+2*c)+u);else f=o>0?-s:s,h=Math.max(0,-(o*f+l)),p=-h*h+f*(f+2*c)+u;return r&&r.copy(this.origin).addScaledVector(this.direction,h),a&&a.copy(DP).addScaledVector(DS,f),p}intersectSphere(e,n){vu.subVectors(e.center,this.origin);const r=vu.dot(this.direction),a=vu.dot(vu)-r*r,s=e.radius*e.radius;if(a>s)return null;const o=Math.sqrt(s-a),l=r-o,c=r+o;return c<0?null:l<0?this.at(c,n):this.at(l,n)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const n=e.normal.dot(this.direction);if(n===0)return e.distanceToPoint(this.origin)===0?0:null;const r=-(this.origin.dot(e.normal)+e.constant)/n;return r>=0?r:null}intersectPlane(e,n){const r=this.distanceToPlane(e);return r===null?null:this.at(r,n)}intersectsPlane(e){const n=e.distanceToPoint(this.origin);return n===0||e.normal.dot(this.direction)*n<0}intersectBox(e,n){let r,a,s,o,l,c;const u=1/this.direction.x,d=1/this.direction.y,h=1/this.direction.z,f=this.origin;return u>=0?(r=(e.min.x-f.x)*u,a=(e.max.x-f.x)*u):(r=(e.max.x-f.x)*u,a=(e.min.x-f.x)*u),d>=0?(s=(e.min.y-f.y)*d,o=(e.max.y-f.y)*d):(s=(e.max.y-f.y)*d,o=(e.min.y-f.y)*d),r>o||s>a||((s>r||isNaN(r))&&(r=s),(o<a||isNaN(a))&&(a=o),h>=0?(l=(e.min.z-f.z)*h,c=(e.max.z-f.z)*h):(l=(e.max.z-f.z)*h,c=(e.min.z-f.z)*h),r>c||l>a)||((l>r||r!==r)&&(r=l),(c<a||a!==a)&&(a=c),a<0)?null:this.at(r>=0?r:a,n)}intersectsBox(e){return this.intersectBox(e,vu)!==null}intersectTriangle(e,n,r,a,s){RP.subVectors(n,e),RS.subVectors(r,e),FP.crossVectors(RP,RS);let o=this.direction.dot(FP),l;if(o>0){if(a)return null;l=1}else if(o<0)l=-1,o=-o;else return null;Yd.subVectors(this.origin,e);const c=l*this.direction.dot(RS.crossVectors(Yd,RS));if(c<0)return null;const u=l*this.direction.dot(RP.cross(Yd));if(u<0||c+u>o)return null;const d=-l*Yd.dot(FP);return d<0?null:this.at(d/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Yr{constructor(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g){Yr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g)}set(e,n,r,a,s,o,l,c,u,d,h,f,p,x,v,g){const y=this.elements;return y[0]=e,y[4]=n,y[8]=r,y[12]=a,y[1]=s,y[5]=o,y[9]=l,y[13]=c,y[2]=u,y[6]=d,y[10]=h,y[14]=f,y[3]=p,y[7]=x,y[11]=v,y[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Yr().fromArray(this.elements)}copy(e){const n=this.elements,r=e.elements;return n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3],n[4]=r[4],n[5]=r[5],n[6]=r[6],n[7]=r[7],n[8]=r[8],n[9]=r[9],n[10]=r[10],n[11]=r[11],n[12]=r[12],n[13]=r[13],n[14]=r[14],n[15]=r[15],this}copyPosition(e){const n=this.elements,r=e.elements;return n[12]=r[12],n[13]=r[13],n[14]=r[14],this}setFromMatrix3(e){const n=e.elements;return this.set(n[0],n[3],n[6],0,n[1],n[4],n[7],0,n[2],n[5],n[8],0,0,0,0,1),this}extractBasis(e,n,r){return e.setFromMatrixColumn(this,0),n.setFromMatrixColumn(this,1),r.setFromMatrixColumn(this,2),this}makeBasis(e,n,r){return this.set(e.x,n.x,r.x,0,e.y,n.y,r.y,0,e.z,n.z,r.z,0,0,0,0,1),this}extractRotation(e){const n=this.elements,r=e.elements,a=1/cg.setFromMatrixColumn(e,0).length(),s=1/cg.setFromMatrixColumn(e,1).length(),o=1/cg.setFromMatrixColumn(e,2).length();return n[0]=r[0]*a,n[1]=r[1]*a,n[2]=r[2]*a,n[3]=0,n[4]=r[4]*s,n[5]=r[5]*s,n[6]=r[6]*s,n[7]=0,n[8]=r[8]*o,n[9]=r[9]*o,n[10]=r[10]*o,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromEuler(e){const n=this.elements,r=e.x,a=e.y,s=e.z,o=Math.cos(r),l=Math.sin(r),c=Math.cos(a),u=Math.sin(a),d=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const f=o*d,p=o*h,x=l*d,v=l*h;n[0]=c*d,n[4]=-c*h,n[8]=u,n[1]=p+x*u,n[5]=f-v*u,n[9]=-l*c,n[2]=v-f*u,n[6]=x+p*u,n[10]=o*c}else if(e.order==="YXZ"){const f=c*d,p=c*h,x=u*d,v=u*h;n[0]=f+v*l,n[4]=x*l-p,n[8]=o*u,n[1]=o*h,n[5]=o*d,n[9]=-l,n[2]=p*l-x,n[6]=v+f*l,n[10]=o*c}else if(e.order==="ZXY"){const f=c*d,p=c*h,x=u*d,v=u*h;n[0]=f-v*l,n[4]=-o*h,n[8]=x+p*l,n[1]=p+x*l,n[5]=o*d,n[9]=v-f*l,n[2]=-o*u,n[6]=l,n[10]=o*c}else if(e.order==="ZYX"){const f=o*d,p=o*h,x=l*d,v=l*h;n[0]=c*d,n[4]=x*u-p,n[8]=f*u+v,n[1]=c*h,n[5]=v*u+f,n[9]=p*u-x,n[2]=-u,n[6]=l*c,n[10]=o*c}else if(e.order==="YZX"){const f=o*c,p=o*u,x=l*c,v=l*u;n[0]=c*d,n[4]=v-f*h,n[8]=x*h+p,n[1]=h,n[5]=o*d,n[9]=-l*d,n[2]=-u*d,n[6]=p*h+x,n[10]=f-v*h}else if(e.order==="XZY"){const f=o*c,p=o*u,x=l*c,v=l*u;n[0]=c*d,n[4]=-h,n[8]=u*d,n[1]=f*h+v,n[5]=o*d,n[9]=p*h-x,n[2]=x*h-p,n[6]=l*d,n[10]=v*h+f}return n[3]=0,n[7]=0,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this}makeRotationFromQuaternion(e){return this.compose(B_e,e,H_e)}lookAt(e,n,r){const a=this.elements;return No.subVectors(e,n),No.lengthSq()===0&&(No.z=1),No.normalize(),Qd.crossVectors(r,No),Qd.lengthSq()===0&&(Math.abs(r.z)===1?No.x+=1e-4:No.z+=1e-4,No.normalize(),Qd.crossVectors(r,No)),Qd.normalize(),FS.crossVectors(No,Qd),a[0]=Qd.x,a[4]=FS.x,a[8]=No.x,a[1]=Qd.y,a[5]=FS.y,a[9]=No.y,a[2]=Qd.z,a[6]=FS.z,a[10]=No.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,n){const r=e.elements,a=n.elements,s=this.elements,o=r[0],l=r[4],c=r[8],u=r[12],d=r[1],h=r[5],f=r[9],p=r[13],x=r[2],v=r[6],g=r[10],y=r[14],_=r[3],N=r[7],k=r[11],A=r[15],M=a[0],C=a[4],j=a[8],P=a[12],E=a[1],U=a[5],L=a[9],B=a[13],D=a[2],$=a[6],G=a[10],z=a[14],W=a[3],X=a[7],ae=a[11],H=a[15];return s[0]=o*M+l*E+c*D+u*W,s[4]=o*C+l*U+c*$+u*X,s[8]=o*j+l*L+c*G+u*ae,s[12]=o*P+l*B+c*z+u*H,s[1]=d*M+h*E+f*D+p*W,s[5]=d*C+h*U+f*$+p*X,s[9]=d*j+h*L+f*G+p*ae,s[13]=d*P+h*B+f*z+p*H,s[2]=x*M+v*E+g*D+y*W,s[6]=x*C+v*U+g*$+y*X,s[10]=x*j+v*L+g*G+y*ae,s[14]=x*P+v*B+g*z+y*H,s[3]=_*M+N*E+k*D+A*W,s[7]=_*C+N*U+k*$+A*X,s[11]=_*j+N*L+k*G+A*ae,s[15]=_*P+N*B+k*z+A*H,this}multiplyScalar(e){const n=this.elements;return n[0]*=e,n[4]*=e,n[8]*=e,n[12]*=e,n[1]*=e,n[5]*=e,n[9]*=e,n[13]*=e,n[2]*=e,n[6]*=e,n[10]*=e,n[14]*=e,n[3]*=e,n[7]*=e,n[11]*=e,n[15]*=e,this}determinant(){const e=this.elements,n=e[0],r=e[4],a=e[8],s=e[12],o=e[1],l=e[5],c=e[9],u=e[13],d=e[2],h=e[6],f=e[10],p=e[14],x=e[3],v=e[7],g=e[11],y=e[15];return x*(+s*c*h-a*u*h-s*l*f+r*u*f+a*l*p-r*c*p)+v*(+n*c*p-n*u*f+s*o*f-a*o*p+a*u*d-s*c*d)+g*(+n*u*h-n*l*p-s*o*h+r*o*p+s*l*d-r*u*d)+y*(-a*l*d-n*c*h+n*l*f+a*o*h-r*o*f+r*c*d)}transpose(){const e=this.elements;let n;return n=e[1],e[1]=e[4],e[4]=n,n=e[2],e[2]=e[8],e[8]=n,n=e[6],e[6]=e[9],e[9]=n,n=e[3],e[3]=e[12],e[12]=n,n=e[7],e[7]=e[13],e[13]=n,n=e[11],e[11]=e[14],e[14]=n,this}setPosition(e,n,r){const a=this.elements;return e.isVector3?(a[12]=e.x,a[13]=e.y,a[14]=e.z):(a[12]=e,a[13]=n,a[14]=r),this}invert(){const e=this.elements,n=e[0],r=e[1],a=e[2],s=e[3],o=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],x=e[12],v=e[13],g=e[14],y=e[15],_=h*g*u-v*f*u+v*c*p-l*g*p-h*c*y+l*f*y,N=x*f*u-d*g*u-x*c*p+o*g*p+d*c*y-o*f*y,k=d*v*u-x*h*u+x*l*p-o*v*p-d*l*y+o*h*y,A=x*h*c-d*v*c-x*l*f+o*v*f+d*l*g-o*h*g,M=n*_+r*N+a*k+s*A;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/M;return e[0]=_*C,e[1]=(v*f*s-h*g*s-v*a*p+r*g*p+h*a*y-r*f*y)*C,e[2]=(l*g*s-v*c*s+v*a*u-r*g*u-l*a*y+r*c*y)*C,e[3]=(h*c*s-l*f*s-h*a*u+r*f*u+l*a*p-r*c*p)*C,e[4]=N*C,e[5]=(d*g*s-x*f*s+x*a*p-n*g*p-d*a*y+n*f*y)*C,e[6]=(x*c*s-o*g*s-x*a*u+n*g*u+o*a*y-n*c*y)*C,e[7]=(o*f*s-d*c*s+d*a*u-n*f*u-o*a*p+n*c*p)*C,e[8]=k*C,e[9]=(x*h*s-d*v*s-x*r*p+n*v*p+d*r*y-n*h*y)*C,e[10]=(o*v*s-x*l*s+x*r*u-n*v*u-o*r*y+n*l*y)*C,e[11]=(d*l*s-o*h*s-d*r*u+n*h*u+o*r*p-n*l*p)*C,e[12]=A*C,e[13]=(d*v*a-x*h*a+x*r*f-n*v*f-d*r*g+n*h*g)*C,e[14]=(x*l*a-o*v*a-x*r*c+n*v*c+o*r*g-n*l*g)*C,e[15]=(o*h*a-d*l*a+d*r*c-n*h*c-o*r*f+n*l*f)*C,this}scale(e){const n=this.elements,r=e.x,a=e.y,s=e.z;return n[0]*=r,n[4]*=a,n[8]*=s,n[1]*=r,n[5]*=a,n[9]*=s,n[2]*=r,n[6]*=a,n[10]*=s,n[3]*=r,n[7]*=a,n[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,n=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],r=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],a=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(n,r,a))}makeTranslation(e,n,r){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,n,0,0,1,r,0,0,0,1),this}makeRotationX(e){const n=Math.cos(e),r=Math.sin(e);return this.set(1,0,0,0,0,n,-r,0,0,r,n,0,0,0,0,1),this}makeRotationY(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,0,r,0,0,1,0,0,-r,0,n,0,0,0,0,1),this}makeRotationZ(e){const n=Math.cos(e),r=Math.sin(e);return this.set(n,-r,0,0,r,n,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,n){const r=Math.cos(n),a=Math.sin(n),s=1-r,o=e.x,l=e.y,c=e.z,u=s*o,d=s*l;return this.set(u*o+r,u*l-a*c,u*c+a*l,0,u*l+a*c,d*l+r,d*c-a*o,0,u*c-a*l,d*c+a*o,s*c*c+r,0,0,0,0,1),this}makeScale(e,n,r){return this.set(e,0,0,0,0,n,0,0,0,0,r,0,0,0,0,1),this}makeShear(e,n,r,a,s,o){return this.set(1,r,s,0,e,1,o,0,n,a,1,0,0,0,0,1),this}compose(e,n,r){const a=this.elements,s=n._x,o=n._y,l=n._z,c=n._w,u=s+s,d=o+o,h=l+l,f=s*u,p=s*d,x=s*h,v=o*d,g=o*h,y=l*h,_=c*u,N=c*d,k=c*h,A=r.x,M=r.y,C=r.z;return a[0]=(1-(v+y))*A,a[1]=(p+k)*A,a[2]=(x-N)*A,a[3]=0,a[4]=(p-k)*M,a[5]=(1-(f+y))*M,a[6]=(g+_)*M,a[7]=0,a[8]=(x+N)*C,a[9]=(g-_)*C,a[10]=(1-(f+v))*C,a[11]=0,a[12]=e.x,a[13]=e.y,a[14]=e.z,a[15]=1,this}decompose(e,n,r){const a=this.elements;let s=cg.set(a[0],a[1],a[2]).length();const o=cg.set(a[4],a[5],a[6]).length(),l=cg.set(a[8],a[9],a[10]).length();this.determinant()<0&&(s=-s),e.x=a[12],e.y=a[13],e.z=a[14],Ol.copy(this);const u=1/s,d=1/o,h=1/l;return Ol.elements[0]*=u,Ol.elements[1]*=u,Ol.elements[2]*=u,Ol.elements[4]*=d,Ol.elements[5]*=d,Ol.elements[6]*=d,Ol.elements[8]*=h,Ol.elements[9]*=h,Ol.elements[10]*=h,n.setFromRotationMatrix(Ol),r.x=s,r.y=o,r.z=l,this}makePerspective(e,n,r,a,s,o,l=Ac){const c=this.elements,u=2*s/(n-e),d=2*s/(r-a),h=(n+e)/(n-e),f=(r+a)/(r-a);let p,x;if(l===Ac)p=-(o+s)/(o-s),x=-2*o*s/(o-s);else if(l===Av)p=-o/(o-s),x=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+l);return c[0]=u,c[4]=0,c[8]=h,c[12]=0,c[1]=0,c[5]=d,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=x,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,n,r,a,s,o,l=Ac){const c=this.elements,u=1/(n-e),d=1/(r-a),h=1/(o-s),f=(n+e)*u,p=(r+a)*d;let x,v;if(l===Ac)x=(o+s)*h,v=-2*h;else if(l===Av)x=s*h,v=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+l);return c[0]=2*u,c[4]=0,c[8]=0,c[12]=-f,c[1]=0,c[5]=2*d,c[9]=0,c[13]=-p,c[2]=0,c[6]=0,c[10]=v,c[14]=-x,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const n=this.elements,r=e.elements;for(let a=0;a<16;a++)if(n[a]!==r[a])return!1;return!0}fromArray(e,n=0){for(let r=0;r<16;r++)this.elements[r]=e[r+n];return this}toArray(e=[],n=0){const r=this.elements;return e[n]=r[0],e[n+1]=r[1],e[n+2]=r[2],e[n+3]=r[3],e[n+4]=r[4],e[n+5]=r[5],e[n+6]=r[6],e[n+7]=r[7],e[n+8]=r[8],e[n+9]=r[9],e[n+10]=r[10],e[n+11]=r[11],e[n+12]=r[12],e[n+13]=r[13],e[n+14]=r[14],e[n+15]=r[15],e}}const cg=new Ze,Ol=new Yr,B_e=new Ze(0,0,0),H_e=new Ze(1,1,1),Qd=new Ze,FS=new Ze,No=new Ze,B6=new Yr,H6=new zf;class g0{constructor(e=0,n=0,r=0,a=g0.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=n,this._z=r,this._order=a}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,n,r,a=this._order){return this._x=e,this._y=n,this._z=r,this._order=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,n=this._order,r=!0){const a=e.elements,s=a[0],o=a[4],l=a[8],c=a[1],u=a[5],d=a[9],h=a[2],f=a[6],p=a[10];switch(n){case"XYZ":this._y=Math.asin(Qi(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-d,p),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(f,u),this._z=0);break;case"YXZ":this._x=Math.asin(-Qi(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(l,p),this._z=Math.atan2(c,u)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(Qi(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-h,p),this._z=Math.atan2(-o,u)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Qi(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(f,p),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,u));break;case"YZX":this._z=Math.asin(Qi(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,u),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(l,p));break;case"XZY":this._z=Math.asin(-Qi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(f,u),this._y=Math.atan2(l,s)):(this._x=Math.atan2(-d,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+n)}return this._order=n,r===!0&&this._onChangeCallback(),this}setFromQuaternion(e,n,r){return B6.makeRotationFromQuaternion(e),this.setFromRotationMatrix(B6,n,r)}setFromVector3(e,n=this._order){return this.set(e.x,e.y,e.z,n)}reorder(e){return H6.setFromEuler(this),this.setFromQuaternion(H6,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],n=0){return e[n]=this._x,e[n+1]=this._y,e[n+2]=this._z,e[n+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}g0.DEFAULT_ORDER="XYZ";class LY{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let $_e=0;const $6=new Ze,ug=new zf,wu=new Yr,LS=new Ze,uy=new Ze,V_e=new Ze,q_e=new zf,V6=new Ze(1,0,0),q6=new Ze(0,1,0),G6=new Ze(0,0,1),G_e={type:"added"},W_e={type:"removed"};class Rs extends rp{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:$_e++}),this.uuid=Gu(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Rs.DEFAULT_UP.clone();const e=new Ze,n=new g0,r=new zf,a=new Ze(1,1,1);function s(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(s),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:a},modelViewMatrix:{value:new Yr},normalMatrix:{value:new qn}}),this.matrix=new Yr,this.matrixWorld=new Yr,this.matrixAutoUpdate=Rs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Rs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new LY,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,n){this.quaternion.setFromAxisAngle(e,n)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,n){return ug.setFromAxisAngle(e,n),this.quaternion.multiply(ug),this}rotateOnWorldAxis(e,n){return ug.setFromAxisAngle(e,n),this.quaternion.premultiply(ug),this}rotateX(e){return this.rotateOnAxis(V6,e)}rotateY(e){return this.rotateOnAxis(q6,e)}rotateZ(e){return this.rotateOnAxis(G6,e)}translateOnAxis(e,n){return $6.copy(e).applyQuaternion(this.quaternion),this.position.add($6.multiplyScalar(n)),this}translateX(e){return this.translateOnAxis(V6,e)}translateY(e){return this.translateOnAxis(q6,e)}translateZ(e){return this.translateOnAxis(G6,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(wu.copy(this.matrixWorld).invert())}lookAt(e,n,r){e.isVector3?LS.copy(e):LS.set(e,n,r);const a=this.parent;this.updateWorldMatrix(!0,!1),uy.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?wu.lookAt(uy,LS,this.up):wu.lookAt(LS,uy,this.up),this.quaternion.setFromRotationMatrix(wu),a&&(wu.extractRotation(a.matrixWorld),ug.setFromRotationMatrix(wu),this.quaternion.premultiply(ug.invert()))}add(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.parent!==null&&e.parent.remove(e),e.parent=this,this.children.push(e),e.dispatchEvent(G_e)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.remove(arguments[r]);return this}const n=this.children.indexOf(e);return n!==-1&&(e.parent=null,this.children.splice(n,1),e.dispatchEvent(W_e)),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),wu.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),wu.multiply(e.parent.matrixWorld)),e.applyMatrix4(wu),this.add(e),e.updateWorldMatrix(!1,!0),this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,n){if(this[e]===n)return this;for(let r=0,a=this.children.length;r<a;r++){const o=this.children[r].getObjectByProperty(e,n);if(o!==void 0)return o}}getObjectsByProperty(e,n,r=[]){this[e]===n&&r.push(this);const a=this.children;for(let s=0,o=a.length;s<o;s++)a[s].getObjectsByProperty(e,n,r);return r}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(uy,e,V_e),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(uy,q_e,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const n=this.matrixWorld.elements;return e.set(n[8],n[9],n[10]).normalize()}raycast(){}traverse(e){e(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].traverseVisible(e)}traverseAncestors(e){const n=this.parent;n!==null&&(e(n),n.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,e=!0);const n=this.children;for(let r=0,a=n.length;r<a;r++){const s=n[r];(s.matrixWorldAutoUpdate===!0||e===!0)&&s.updateMatrixWorld(e)}}updateWorldMatrix(e,n){const r=this.parent;if(e===!0&&r!==null&&r.matrixWorldAutoUpdate===!0&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),n===!0){const a=this.children;for(let s=0,o=a.length;s<o;s++){const l=a[s];l.matrixWorldAutoUpdate===!0&&l.updateWorldMatrix(!1,!0)}}}toJSON(e){const n=e===void 0||typeof e=="string",r={};n&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},r.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const a={};a.uuid=this.uuid,a.type=this.type,this.name!==""&&(a.name=this.name),this.castShadow===!0&&(a.castShadow=!0),this.receiveShadow===!0&&(a.receiveShadow=!0),this.visible===!1&&(a.visible=!1),this.frustumCulled===!1&&(a.frustumCulled=!1),this.renderOrder!==0&&(a.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(a.userData=this.userData),a.layers=this.layers.mask,a.matrix=this.matrix.toArray(),a.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(a.matrixAutoUpdate=!1),this.isInstancedMesh&&(a.type="InstancedMesh",a.count=this.count,a.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(a.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(a.type="BatchedMesh",a.perObjectFrustumCulled=this.perObjectFrustumCulled,a.sortObjects=this.sortObjects,a.drawRanges=this._drawRanges,a.reservedRanges=this._reservedRanges,a.visibility=this._visibility,a.active=this._active,a.bounds=this._bounds.map(l=>({boxInitialized:l.boxInitialized,boxMin:l.box.min.toArray(),boxMax:l.box.max.toArray(),sphereInitialized:l.sphereInitialized,sphereRadius:l.sphere.radius,sphereCenter:l.sphere.center.toArray()})),a.maxGeometryCount=this._maxGeometryCount,a.maxVertexCount=this._maxVertexCount,a.maxIndexCount=this._maxIndexCount,a.geometryInitialized=this._geometryInitialized,a.geometryCount=this._geometryCount,a.matricesTexture=this._matricesTexture.toJSON(e),this.boundingSphere!==null&&(a.boundingSphere={center:a.boundingSphere.center.toArray(),radius:a.boundingSphere.radius}),this.boundingBox!==null&&(a.boundingBox={min:a.boundingBox.min.toArray(),max:a.boundingBox.max.toArray()}));function s(l,c){return l[c.uuid]===void 0&&(l[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?a.background=this.background.toJSON():this.background.isTexture&&(a.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(a.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){a.geometry=s(e.geometries,this.geometry);const l=this.geometry.parameters;if(l!==void 0&&l.shapes!==void 0){const c=l.shapes;if(Array.isArray(c))for(let u=0,d=c.length;u<d;u++){const h=c[u];s(e.shapes,h)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(a.bindMode=this.bindMode,a.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),a.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const l=[];for(let c=0,u=this.material.length;c<u;c++)l.push(s(e.materials,this.material[c]));a.material=l}else a.material=s(e.materials,this.material);if(this.children.length>0){a.children=[];for(let l=0;l<this.children.length;l++)a.children.push(this.children[l].toJSON(e).object)}if(this.animations.length>0){a.animations=[];for(let l=0;l<this.animations.length;l++){const c=this.animations[l];a.animations.push(s(e.animations,c))}}if(n){const l=o(e.geometries),c=o(e.materials),u=o(e.textures),d=o(e.images),h=o(e.shapes),f=o(e.skeletons),p=o(e.animations),x=o(e.nodes);l.length>0&&(r.geometries=l),c.length>0&&(r.materials=c),u.length>0&&(r.textures=u),d.length>0&&(r.images=d),h.length>0&&(r.shapes=h),f.length>0&&(r.skeletons=f),p.length>0&&(r.animations=p),x.length>0&&(r.nodes=x)}return r.object=a,r;function o(l){const c=[];for(const u in l){const d=l[u];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,n=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),n===!0)for(let r=0;r<e.children.length;r++){const a=e.children[r];this.add(a.clone())}return this}}Rs.DEFAULT_UP=new Ze(0,1,0);Rs.DEFAULT_MATRIX_AUTO_UPDATE=!0;Rs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Il=new Ze,Su=new Ze,LP=new Ze,_u=new Ze,dg=new Ze,hg=new Ze,W6=new Ze,OP=new Ze,IP=new Ze,zP=new Ze;let OS=!1;class zl{constructor(e=new Ze,n=new Ze,r=new Ze){this.a=e,this.b=n,this.c=r}static getNormal(e,n,r,a){a.subVectors(r,n),Il.subVectors(e,n),a.cross(Il);const s=a.lengthSq();return s>0?a.multiplyScalar(1/Math.sqrt(s)):a.set(0,0,0)}static getBarycoord(e,n,r,a,s){Il.subVectors(a,n),Su.subVectors(r,n),LP.subVectors(e,n);const o=Il.dot(Il),l=Il.dot(Su),c=Il.dot(LP),u=Su.dot(Su),d=Su.dot(LP),h=o*u-l*l;if(h===0)return s.set(-2,-1,-1);const f=1/h,p=(u*c-l*d)*f,x=(o*d-l*c)*f;return s.set(1-p-x,x,p)}static containsPoint(e,n,r,a){return this.getBarycoord(e,n,r,a,_u),_u.x>=0&&_u.y>=0&&_u.x+_u.y<=1}static getUV(e,n,r,a,s,o,l,c){return OS===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),OS=!0),this.getInterpolation(e,n,r,a,s,o,l,c)}static getInterpolation(e,n,r,a,s,o,l,c){return this.getBarycoord(e,n,r,a,_u),c.setScalar(0),c.addScaledVector(s,_u.x),c.addScaledVector(o,_u.y),c.addScaledVector(l,_u.z),c}static isFrontFacing(e,n,r,a){return Il.subVectors(r,n),Su.subVectors(e,n),Il.cross(Su).dot(a)<0}set(e,n,r){return this.a.copy(e),this.b.copy(n),this.c.copy(r),this}setFromPointsAndIndices(e,n,r,a){return this.a.copy(e[n]),this.b.copy(e[r]),this.c.copy(e[a]),this}setFromAttributeAndIndices(e,n,r,a){return this.a.fromBufferAttribute(e,n),this.b.fromBufferAttribute(e,r),this.c.fromBufferAttribute(e,a),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Il.subVectors(this.c,this.b),Su.subVectors(this.a,this.b),Il.cross(Su).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return zl.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,n){return zl.getBarycoord(e,this.a,this.b,this.c,n)}getUV(e,n,r,a,s){return OS===!1&&(console.warn("THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation()."),OS=!0),zl.getInterpolation(e,this.a,this.b,this.c,n,r,a,s)}getInterpolation(e,n,r,a,s){return zl.getInterpolation(e,this.a,this.b,this.c,n,r,a,s)}containsPoint(e){return zl.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return zl.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,n){const r=this.a,a=this.b,s=this.c;let o,l;dg.subVectors(a,r),hg.subVectors(s,r),OP.subVectors(e,r);const c=dg.dot(OP),u=hg.dot(OP);if(c<=0&&u<=0)return n.copy(r);IP.subVectors(e,a);const d=dg.dot(IP),h=hg.dot(IP);if(d>=0&&h<=d)return n.copy(a);const f=c*h-d*u;if(f<=0&&c>=0&&d<=0)return o=c/(c-d),n.copy(r).addScaledVector(dg,o);zP.subVectors(e,s);const p=dg.dot(zP),x=hg.dot(zP);if(x>=0&&p<=x)return n.copy(s);const v=p*u-c*x;if(v<=0&&u>=0&&x<=0)return l=u/(u-x),n.copy(r).addScaledVector(hg,l);const g=d*x-p*h;if(g<=0&&h-d>=0&&p-x>=0)return W6.subVectors(s,a),l=(h-d)/(h-d+(p-x)),n.copy(a).addScaledVector(W6,l);const y=1/(g+v+f);return o=v*y,l=f*y,n.copy(r).addScaledVector(dg,o).addScaledVector(hg,l)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const OY={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Zd={h:0,s:0,l:0},IS={h:0,s:0,l:0};function UP(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*6*(2/3-n):t}let dn=class{constructor(e,n,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,n,r)}set(e,n,r){if(n===void 0&&r===void 0){const a=e;a&&a.isColor?this.copy(a):typeof a=="number"?this.setHex(a):typeof a=="string"&&this.setStyle(a)}else this.setRGB(e,n,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,n=Yi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Fr.toWorkingColorSpace(this,n),this}setRGB(e,n,r,a=Fr.workingColorSpace){return this.r=e,this.g=n,this.b=r,Fr.toWorkingColorSpace(this,a),this}setHSL(e,n,r,a=Fr.workingColorSpace){if(e=eL(e,1),n=Qi(n,0,1),r=Qi(r,0,1),n===0)this.r=this.g=this.b=r;else{const s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;this.r=UP(o,s,e+1/3),this.g=UP(o,s,e),this.b=UP(o,s,e-1/3)}return Fr.toWorkingColorSpace(this,a),this}setStyle(e,n=Yi){function r(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let a;if(a=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=a[1],l=a[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,n);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,n);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l))return r(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,n);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(a=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=a[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,n);if(o===6)return this.setHex(parseInt(s,16),n);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,n);return this}setColorName(e,n=Yi){const r=OY[e.toLowerCase()];return r!==void 0?this.setHex(r,n):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Jg(e.r),this.g=Jg(e.g),this.b=Jg(e.b),this}copyLinearToSRGB(e){return this.r=TP(e.r),this.g=TP(e.g),this.b=TP(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Yi){return Fr.fromWorkingColorSpace(cs.copy(this),e),Math.round(Qi(cs.r*255,0,255))*65536+Math.round(Qi(cs.g*255,0,255))*256+Math.round(Qi(cs.b*255,0,255))}getHexString(e=Yi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,n=Fr.workingColorSpace){Fr.fromWorkingColorSpace(cs.copy(this),n);const r=cs.r,a=cs.g,s=cs.b,o=Math.max(r,a,s),l=Math.min(r,a,s);let c,u;const d=(l+o)/2;if(l===o)c=0,u=0;else{const h=o-l;switch(u=d<=.5?h/(o+l):h/(2-o-l),o){case r:c=(a-s)/h+(a<s?6:0);break;case a:c=(s-r)/h+2;break;case s:c=(r-a)/h+4;break}c/=6}return e.h=c,e.s=u,e.l=d,e}getRGB(e,n=Fr.workingColorSpace){return Fr.fromWorkingColorSpace(cs.copy(this),n),e.r=cs.r,e.g=cs.g,e.b=cs.b,e}getStyle(e=Yi){Fr.fromWorkingColorSpace(cs.copy(this),e);const n=cs.r,r=cs.g,a=cs.b;return e!==Yi?`color(${e} ${n.toFixed(3)} ${r.toFixed(3)} ${a.toFixed(3)})`:`rgb(${Math.round(n*255)},${Math.round(r*255)},${Math.round(a*255)})`}offsetHSL(e,n,r){return this.getHSL(Zd),this.setHSL(Zd.h+e,Zd.s+n,Zd.l+r)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,n){return this.r=e.r+n.r,this.g=e.g+n.g,this.b=e.b+n.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,n){return this.r+=(e.r-this.r)*n,this.g+=(e.g-this.g)*n,this.b+=(e.b-this.b)*n,this}lerpColors(e,n,r){return this.r=e.r+(n.r-e.r)*r,this.g=e.g+(n.g-e.g)*r,this.b=e.b+(n.b-e.b)*r,this}lerpHSL(e,n){this.getHSL(Zd),e.getHSL(IS);const r=Gy(Zd.h,IS.h,n),a=Gy(Zd.s,IS.s,n),s=Gy(Zd.l,IS.l,n);return this.setHSL(r,a,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const n=this.r,r=this.g,a=this.b,s=e.elements;return this.r=s[0]*n+s[3]*r+s[6]*a,this.g=s[1]*n+s[4]*r+s[7]*a,this.b=s[2]*n+s[5]*r+s[8]*a,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,n=0){return this.r=e[n],this.g=e[n+1],this.b=e[n+2],this}toArray(e=[],n=0){return e[n]=this.r,e[n+1]=this.g,e[n+2]=this.b,e}fromBufferAttribute(e,n){return this.r=e.getX(n),this.g=e.getY(n),this.b=e.getZ(n),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}};const cs=new dn;dn.NAMES=OY;let K_e=0;class Xb extends rp{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:K_e++}),this.uuid=Gu(),this.name="",this.type="Material",this.blending=Zg,this.side=Wh,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=nD,this.blendDst=rD,this.blendEquation=Km,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new dn(0,0,0),this.blendAlpha=0,this.depthFunc=j1,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=R6,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ag,this.stencilZFail=ag,this.stencilZPass=ag,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const n in e){const r=e[n];if(r===void 0){console.warn(`THREE.Material: parameter '${n}' has value of undefined.`);continue}const a=this[n];if(a===void 0){console.warn(`THREE.Material: '${n}' is not a property of THREE.${this.type}.`);continue}a&&a.isColor?a.set(r):a&&a.isVector3&&r&&r.isVector3?a.copy(r):this[n]=r}}toJSON(e){const n=e===void 0||typeof e=="string";n&&(e={textures:{},images:{}});const r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==Zg&&(r.blending=this.blending),this.side!==Wh&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==nD&&(r.blendSrc=this.blendSrc),this.blendDst!==rD&&(r.blendDst=this.blendDst),this.blendEquation!==Km&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==j1&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==R6&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ag&&(r.stencilFail=this.stencilFail),this.stencilZFail!==ag&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==ag&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function a(s){const o=[];for(const l in s){const c=s[l];delete c.metadata,o.push(c)}return o}if(n){const s=a(e.textures),o=a(e.images);s.length>0&&(r.textures=s),o.length>0&&(r.images=o)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const n=e.clippingPlanes;let r=null;if(n!==null){const a=n.length;r=new Array(a);for(let s=0;s!==a;++s)r[s]=n[s].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class IY extends Xb{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new dn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=QF,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Qa=new Ze,zS=new _n;class Do{constructor(e,n,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=n,this.count=e!==void 0?e.length/n:0,this.normalized=r,this.usage=lD,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=zu,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.BufferAttribute: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,n,r){e*=this.itemSize,r*=n.itemSize;for(let a=0,s=this.itemSize;a<s;a++)this.array[e+a]=n.array[r+a];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let n=0,r=this.count;n<r;n++)zS.fromBufferAttribute(this,n),zS.applyMatrix3(e),this.setXY(n,zS.x,zS.y);else if(this.itemSize===3)for(let n=0,r=this.count;n<r;n++)Qa.fromBufferAttribute(this,n),Qa.applyMatrix3(e),this.setXYZ(n,Qa.x,Qa.y,Qa.z);return this}applyMatrix4(e){for(let n=0,r=this.count;n<r;n++)Qa.fromBufferAttribute(this,n),Qa.applyMatrix4(e),this.setXYZ(n,Qa.x,Qa.y,Qa.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)Qa.fromBufferAttribute(this,n),Qa.applyNormalMatrix(e),this.setXYZ(n,Qa.x,Qa.y,Qa.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)Qa.fromBufferAttribute(this,n),Qa.transformDirection(e),this.setXYZ(n,Qa.x,Qa.y,Qa.z);return this}set(e,n=0){return this.array.set(e,n),this}getComponent(e,n){let r=this.array[e*this.itemSize+n];return this.normalized&&(r=Nc(r,this.array)),r}setComponent(e,n,r){return this.normalized&&(r=Rr(r,this.array)),this.array[e*this.itemSize+n]=r,this}getX(e){let n=this.array[e*this.itemSize];return this.normalized&&(n=Nc(n,this.array)),n}setX(e,n){return this.normalized&&(n=Rr(n,this.array)),this.array[e*this.itemSize]=n,this}getY(e){let n=this.array[e*this.itemSize+1];return this.normalized&&(n=Nc(n,this.array)),n}setY(e,n){return this.normalized&&(n=Rr(n,this.array)),this.array[e*this.itemSize+1]=n,this}getZ(e){let n=this.array[e*this.itemSize+2];return this.normalized&&(n=Nc(n,this.array)),n}setZ(e,n){return this.normalized&&(n=Rr(n,this.array)),this.array[e*this.itemSize+2]=n,this}getW(e){let n=this.array[e*this.itemSize+3];return this.normalized&&(n=Nc(n,this.array)),n}setW(e,n){return this.normalized&&(n=Rr(n,this.array)),this.array[e*this.itemSize+3]=n,this}setXY(e,n,r){return e*=this.itemSize,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array)),this.array[e+0]=n,this.array[e+1]=r,this}setXYZ(e,n,r,a){return e*=this.itemSize,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array),a=Rr(a,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=a,this}setXYZW(e,n,r,a,s){return e*=this.itemSize,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array),a=Rr(a,this.array),s=Rr(s,this.array)),this.array[e+0]=n,this.array[e+1]=r,this.array[e+2]=a,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==lD&&(e.usage=this.usage),e}}class zY extends Do{constructor(e,n,r){super(new Uint16Array(e),n,r)}}class UY extends Do{constructor(e,n,r){super(new Uint32Array(e),n,r)}}class Ha extends Do{constructor(e,n,r){super(new Float32Array(e),n,r)}}let X_e=0;const Ko=new Yr,BP=new Rs,mg=new Ze,Co=new pl,dy=new pl,Ti=new Ze;class ys extends rp{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:X_e++}),this.uuid=Gu(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(jY(e)?UY:zY)(e,1):this.index=e,this}getAttribute(e){return this.attributes[e]}setAttribute(e,n){return this.attributes[e]=n,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,n,r=0){this.groups.push({start:e,count:n,materialIndex:r})}clearGroups(){this.groups=[]}setDrawRange(e,n){this.drawRange.start=e,this.drawRange.count=n}applyMatrix4(e){const n=this.attributes.position;n!==void 0&&(n.applyMatrix4(e),n.needsUpdate=!0);const r=this.attributes.normal;if(r!==void 0){const s=new qn().getNormalMatrix(e);r.applyNormalMatrix(s),r.needsUpdate=!0}const a=this.attributes.tangent;return a!==void 0&&(a.transformDirection(e),a.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ko.makeRotationFromQuaternion(e),this.applyMatrix4(Ko),this}rotateX(e){return Ko.makeRotationX(e),this.applyMatrix4(Ko),this}rotateY(e){return Ko.makeRotationY(e),this.applyMatrix4(Ko),this}rotateZ(e){return Ko.makeRotationZ(e),this.applyMatrix4(Ko),this}translate(e,n,r){return Ko.makeTranslation(e,n,r),this.applyMatrix4(Ko),this}scale(e,n,r){return Ko.makeScale(e,n,r),this.applyMatrix4(Ko),this}lookAt(e){return BP.lookAt(e),BP.updateMatrix(),this.applyMatrix4(BP.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(mg).negate(),this.translate(mg.x,mg.y,mg.z),this}setFromPoints(e){const n=[];for(let r=0,a=e.length;r<a;r++){const s=e[r];n.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new Ha(n,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new pl);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingBox.set(new Ze(-1/0,-1/0,-1/0),new Ze(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),n)for(let r=0,a=n.length;r<a;r++){const s=n[r];Co.setFromBufferAttribute(s),this.morphTargetsRelative?(Ti.addVectors(this.boundingBox.min,Co.min),this.boundingBox.expandByPoint(Ti),Ti.addVectors(this.boundingBox.max,Co.max),this.boundingBox.expandByPoint(Ti)):(this.boundingBox.expandByPoint(Co.min),this.boundingBox.expandByPoint(Co.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new jc);const e=this.attributes.position,n=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this),this.boundingSphere.set(new Ze,1/0);return}if(e){const r=this.boundingSphere.center;if(Co.setFromBufferAttribute(e),n)for(let s=0,o=n.length;s<o;s++){const l=n[s];dy.setFromBufferAttribute(l),this.morphTargetsRelative?(Ti.addVectors(Co.min,dy.min),Co.expandByPoint(Ti),Ti.addVectors(Co.max,dy.max),Co.expandByPoint(Ti)):(Co.expandByPoint(dy.min),Co.expandByPoint(dy.max))}Co.getCenter(r);let a=0;for(let s=0,o=e.count;s<o;s++)Ti.fromBufferAttribute(e,s),a=Math.max(a,r.distanceToSquared(Ti));if(n)for(let s=0,o=n.length;s<o;s++){const l=n[s],c=this.morphTargetsRelative;for(let u=0,d=l.count;u<d;u++)Ti.fromBufferAttribute(l,u),c&&(mg.fromBufferAttribute(e,u),Ti.add(mg)),a=Math.max(a,r.distanceToSquared(Ti))}this.boundingSphere.radius=Math.sqrt(a),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,n=this.attributes;if(e===null||n.position===void 0||n.normal===void 0||n.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const r=e.array,a=n.position.array,s=n.normal.array,o=n.uv.array,l=a.length/3;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Do(new Float32Array(4*l),4));const c=this.getAttribute("tangent").array,u=[],d=[];for(let E=0;E<l;E++)u[E]=new Ze,d[E]=new Ze;const h=new Ze,f=new Ze,p=new Ze,x=new _n,v=new _n,g=new _n,y=new Ze,_=new Ze;function N(E,U,L){h.fromArray(a,E*3),f.fromArray(a,U*3),p.fromArray(a,L*3),x.fromArray(o,E*2),v.fromArray(o,U*2),g.fromArray(o,L*2),f.sub(h),p.sub(h),v.sub(x),g.sub(x);const B=1/(v.x*g.y-g.x*v.y);isFinite(B)&&(y.copy(f).multiplyScalar(g.y).addScaledVector(p,-v.y).multiplyScalar(B),_.copy(p).multiplyScalar(v.x).addScaledVector(f,-g.x).multiplyScalar(B),u[E].add(y),u[U].add(y),u[L].add(y),d[E].add(_),d[U].add(_),d[L].add(_))}let k=this.groups;k.length===0&&(k=[{start:0,count:r.length}]);for(let E=0,U=k.length;E<U;++E){const L=k[E],B=L.start,D=L.count;for(let $=B,G=B+D;$<G;$+=3)N(r[$+0],r[$+1],r[$+2])}const A=new Ze,M=new Ze,C=new Ze,j=new Ze;function P(E){C.fromArray(s,E*3),j.copy(C);const U=u[E];A.copy(U),A.sub(C.multiplyScalar(C.dot(U))).normalize(),M.crossVectors(j,U);const B=M.dot(d[E])<0?-1:1;c[E*4]=A.x,c[E*4+1]=A.y,c[E*4+2]=A.z,c[E*4+3]=B}for(let E=0,U=k.length;E<U;++E){const L=k[E],B=L.start,D=L.count;for(let $=B,G=B+D;$<G;$+=3)P(r[$+0]),P(r[$+1]),P(r[$+2])}}computeVertexNormals(){const e=this.index,n=this.getAttribute("position");if(n!==void 0){let r=this.getAttribute("normal");if(r===void 0)r=new Do(new Float32Array(n.count*3),3),this.setAttribute("normal",r);else for(let f=0,p=r.count;f<p;f++)r.setXYZ(f,0,0,0);const a=new Ze,s=new Ze,o=new Ze,l=new Ze,c=new Ze,u=new Ze,d=new Ze,h=new Ze;if(e)for(let f=0,p=e.count;f<p;f+=3){const x=e.getX(f+0),v=e.getX(f+1),g=e.getX(f+2);a.fromBufferAttribute(n,x),s.fromBufferAttribute(n,v),o.fromBufferAttribute(n,g),d.subVectors(o,s),h.subVectors(a,s),d.cross(h),l.fromBufferAttribute(r,x),c.fromBufferAttribute(r,v),u.fromBufferAttribute(r,g),l.add(d),c.add(d),u.add(d),r.setXYZ(x,l.x,l.y,l.z),r.setXYZ(v,c.x,c.y,c.z),r.setXYZ(g,u.x,u.y,u.z)}else for(let f=0,p=n.count;f<p;f+=3)a.fromBufferAttribute(n,f+0),s.fromBufferAttribute(n,f+1),o.fromBufferAttribute(n,f+2),d.subVectors(o,s),h.subVectors(a,s),d.cross(h),r.setXYZ(f+0,d.x,d.y,d.z),r.setXYZ(f+1,d.x,d.y,d.z),r.setXYZ(f+2,d.x,d.y,d.z);this.normalizeNormals(),r.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let n=0,r=e.count;n<r;n++)Ti.fromBufferAttribute(e,n),Ti.normalize(),e.setXYZ(n,Ti.x,Ti.y,Ti.z)}toNonIndexed(){function e(l,c){const u=l.array,d=l.itemSize,h=l.normalized,f=new u.constructor(c.length*d);let p=0,x=0;for(let v=0,g=c.length;v<g;v++){l.isInterleavedBufferAttribute?p=c[v]*l.data.stride+l.offset:p=c[v]*d;for(let y=0;y<d;y++)f[x++]=u[p++]}return new Do(f,d,h)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const n=new ys,r=this.index.array,a=this.attributes;for(const l in a){const c=a[l],u=e(c,r);n.setAttribute(l,u)}const s=this.morphAttributes;for(const l in s){const c=[],u=s[l];for(let d=0,h=u.length;d<h;d++){const f=u[d],p=e(f,r);c.push(p)}n.morphAttributes[l]=c}n.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let l=0,c=o.length;l<c;l++){const u=o[l];n.addGroup(u.start,u.count,u.materialIndex)}return n}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const u in c)c[u]!==void 0&&(e[u]=c[u]);return e}e.data={attributes:{}};const n=this.index;n!==null&&(e.data.index={type:n.array.constructor.name,array:Array.prototype.slice.call(n.array)});const r=this.attributes;for(const c in r){const u=r[c];e.data.attributes[c]=u.toJSON(e.data)}const a={};let s=!1;for(const c in this.morphAttributes){const u=this.morphAttributes[c],d=[];for(let h=0,f=u.length;h<f;h++){const p=u[h];d.push(p.toJSON(e.data))}d.length>0&&(a[c]=d,s=!0)}s&&(e.data.morphAttributes=a,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const l=this.boundingSphere;return l!==null&&(e.data.boundingSphere={center:l.center.toArray(),radius:l.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone(n));const a=e.attributes;for(const u in a){const d=a[u];this.setAttribute(u,d.clone(n))}const s=e.morphAttributes;for(const u in s){const d=[],h=s[u];for(let f=0,p=h.length;f<p;f++)d.push(h[f].clone(n));this.morphAttributes[u]=d}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let u=0,d=o.length;u<d;u++){const h=o[u];this.addGroup(h.start,h.count,h.materialIndex)}const l=e.boundingBox;l!==null&&(this.boundingBox=l.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const K6=new Yr,Rm=new tL,US=new jc,X6=new Ze,fg=new Ze,pg=new Ze,gg=new Ze,HP=new Ze,BS=new Ze,HS=new _n,$S=new _n,VS=new _n,Y6=new Ze,Q6=new Ze,Z6=new Ze,qS=new Ze,GS=new Ze;class Gl extends Rs{constructor(e=new ys,n=new IY){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const l=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}getVertexPosition(e,n){const r=this.geometry,a=r.attributes.position,s=r.morphAttributes.position,o=r.morphTargetsRelative;n.fromBufferAttribute(a,e);const l=this.morphTargetInfluences;if(s&&l){BS.set(0,0,0);for(let c=0,u=s.length;c<u;c++){const d=l[c],h=s[c];d!==0&&(HP.fromBufferAttribute(h,e),o?BS.addScaledVector(HP,d):BS.addScaledVector(HP.sub(n),d))}n.add(BS)}return n}raycast(e,n){const r=this.geometry,a=this.material,s=this.matrixWorld;a!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),US.copy(r.boundingSphere),US.applyMatrix4(s),Rm.copy(e.ray).recast(e.near),!(US.containsPoint(Rm.origin)===!1&&(Rm.intersectSphere(US,X6)===null||Rm.origin.distanceToSquared(X6)>(e.far-e.near)**2))&&(K6.copy(s).invert(),Rm.copy(e.ray).applyMatrix4(K6),!(r.boundingBox!==null&&Rm.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Rm)))}_computeIntersections(e,n,r){let a;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,u=s.attributes.uv,d=s.attributes.uv1,h=s.attributes.normal,f=s.groups,p=s.drawRange;if(l!==null)if(Array.isArray(o))for(let x=0,v=f.length;x<v;x++){const g=f[x],y=o[g.materialIndex],_=Math.max(g.start,p.start),N=Math.min(l.count,Math.min(g.start+g.count,p.start+p.count));for(let k=_,A=N;k<A;k+=3){const M=l.getX(k),C=l.getX(k+1),j=l.getX(k+2);a=WS(this,y,e,r,u,d,h,M,C,j),a&&(a.faceIndex=Math.floor(k/3),a.face.materialIndex=g.materialIndex,n.push(a))}}else{const x=Math.max(0,p.start),v=Math.min(l.count,p.start+p.count);for(let g=x,y=v;g<y;g+=3){const _=l.getX(g),N=l.getX(g+1),k=l.getX(g+2);a=WS(this,o,e,r,u,d,h,_,N,k),a&&(a.faceIndex=Math.floor(g/3),n.push(a))}}else if(c!==void 0)if(Array.isArray(o))for(let x=0,v=f.length;x<v;x++){const g=f[x],y=o[g.materialIndex],_=Math.max(g.start,p.start),N=Math.min(c.count,Math.min(g.start+g.count,p.start+p.count));for(let k=_,A=N;k<A;k+=3){const M=k,C=k+1,j=k+2;a=WS(this,y,e,r,u,d,h,M,C,j),a&&(a.faceIndex=Math.floor(k/3),a.face.materialIndex=g.materialIndex,n.push(a))}}else{const x=Math.max(0,p.start),v=Math.min(c.count,p.start+p.count);for(let g=x,y=v;g<y;g+=3){const _=g,N=g+1,k=g+2;a=WS(this,o,e,r,u,d,h,_,N,k),a&&(a.faceIndex=Math.floor(g/3),n.push(a))}}}}function Y_e(t,e,n,r,a,s,o,l){let c;if(e.side===no?c=r.intersectTriangle(o,s,a,!0,l):c=r.intersectTriangle(a,s,o,e.side===Wh,l),c===null)return null;GS.copy(l),GS.applyMatrix4(t.matrixWorld);const u=n.ray.origin.distanceTo(GS);return u<n.near||u>n.far?null:{distance:u,point:GS.clone(),object:t}}function WS(t,e,n,r,a,s,o,l,c,u){t.getVertexPosition(l,fg),t.getVertexPosition(c,pg),t.getVertexPosition(u,gg);const d=Y_e(t,e,n,r,fg,pg,gg,qS);if(d){a&&(HS.fromBufferAttribute(a,l),$S.fromBufferAttribute(a,c),VS.fromBufferAttribute(a,u),d.uv=zl.getInterpolation(qS,fg,pg,gg,HS,$S,VS,new _n)),s&&(HS.fromBufferAttribute(s,l),$S.fromBufferAttribute(s,c),VS.fromBufferAttribute(s,u),d.uv1=zl.getInterpolation(qS,fg,pg,gg,HS,$S,VS,new _n),d.uv2=d.uv1),o&&(Y6.fromBufferAttribute(o,l),Q6.fromBufferAttribute(o,c),Z6.fromBufferAttribute(o,u),d.normal=zl.getInterpolation(qS,fg,pg,gg,Y6,Q6,Z6,new Ze),d.normal.dot(r.direction)>0&&d.normal.multiplyScalar(-1));const h={a:l,b:c,c:u,normal:new Ze,materialIndex:0};zl.getNormal(fg,pg,gg,h.normal),d.face=h}return d}class b0 extends ys{constructor(e=1,n=1,r=1,a=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:a,heightSegments:s,depthSegments:o};const l=this;a=Math.floor(a),s=Math.floor(s),o=Math.floor(o);const c=[],u=[],d=[],h=[];let f=0,p=0;x("z","y","x",-1,-1,r,n,e,o,s,0),x("z","y","x",1,-1,r,n,-e,o,s,1),x("x","z","y",1,1,e,r,n,a,o,2),x("x","z","y",1,-1,e,r,-n,a,o,3),x("x","y","z",1,-1,e,n,r,a,s,4),x("x","y","z",-1,-1,e,n,-r,a,s,5),this.setIndex(c),this.setAttribute("position",new Ha(u,3)),this.setAttribute("normal",new Ha(d,3)),this.setAttribute("uv",new Ha(h,2));function x(v,g,y,_,N,k,A,M,C,j,P){const E=k/C,U=A/j,L=k/2,B=A/2,D=M/2,$=C+1,G=j+1;let z=0,W=0;const X=new Ze;for(let ae=0;ae<G;ae++){const H=ae*U-B;for(let K=0;K<$;K++){const te=K*E-L;X[v]=te*_,X[g]=H*N,X[y]=D,u.push(X.x,X.y,X.z),X[v]=0,X[g]=0,X[y]=M>0?1:-1,d.push(X.x,X.y,X.z),h.push(K/C),h.push(1-ae/j),z+=1}}for(let ae=0;ae<j;ae++)for(let H=0;H<C;H++){const K=f+H+$*ae,te=f+H+$*(ae+1),Z=f+(H+1)+$*(ae+1),ve=f+(H+1)+$*ae;c.push(K,te,ve),c.push(te,Z,ve),W+=6}l.addGroup(p,W,P),p+=W,f+=z}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new b0(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Sb(t){const e={};for(const n in t){e[n]={};for(const r in t[n]){const a=t[n][r];a&&(a.isColor||a.isMatrix3||a.isMatrix4||a.isVector2||a.isVector3||a.isVector4||a.isTexture||a.isQuaternion)?a.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[n][r]=null):e[n][r]=a.clone():Array.isArray(a)?e[n][r]=a.slice():e[n][r]=a}}return e}function As(t){const e={};for(let n=0;n<t.length;n++){const r=Sb(t[n]);for(const a in r)e[a]=r[a]}return e}function Q_e(t){const e=[];for(let n=0;n<t.length;n++)e.push(t[n].clone());return e}function BY(t){return t.getRenderTarget()===null?t.outputColorSpace:Fr.workingColorSpace}const nL={clone:Sb,merge:As};var Z_e=`void main() {
  3840. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  3841. }`,J_e=`void main() {
  3842. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  3843. }`;class Kh extends Xb{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Z_e,this.fragmentShader=J_e,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Sb(e.uniforms),this.uniformsGroups=Q_e(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const n=super.toJSON(e);n.glslVersion=this.glslVersion,n.uniforms={};for(const a in this.uniforms){const o=this.uniforms[a].value;o&&o.isTexture?n.uniforms[a]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?n.uniforms[a]={type:"c",value:o.getHex()}:o&&o.isVector2?n.uniforms[a]={type:"v2",value:o.toArray()}:o&&o.isVector3?n.uniforms[a]={type:"v3",value:o.toArray()}:o&&o.isVector4?n.uniforms[a]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?n.uniforms[a]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?n.uniforms[a]={type:"m4",value:o.toArray()}:n.uniforms[a]={value:o}}Object.keys(this.defines).length>0&&(n.defines=this.defines),n.vertexShader=this.vertexShader,n.fragmentShader=this.fragmentShader,n.lights=this.lights,n.clipping=this.clipping;const r={};for(const a in this.extensions)this.extensions[a]===!0&&(r[a]=!0);return Object.keys(r).length>0&&(n.extensions=r),n}}class HY extends Rs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Yr,this.projectionMatrix=new Yr,this.projectionMatrixInverse=new Yr,this.coordinateSystem=Ac}copy(e,n){return super.copy(e,n),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,n){super.updateWorldMatrix(e,n),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}class Ao extends HY{constructor(e=50,n=1,r=.1,a=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=a,this.focus=10,this.aspect=n,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const n=.5*this.getFilmHeight()/e;this.fov=Tv*2*Math.atan(n),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(qy*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Tv*2*Math.atan(Math.tan(qy*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}setViewOffset(e,n,r,a,s,o){this.aspect=e/n,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let n=e*Math.tan(qy*.5*this.fov)/this.zoom,r=2*n,a=this.aspect*r,s=-.5*a;const o=this.view;if(this.view!==null&&this.view.enabled){const c=o.fullWidth,u=o.fullHeight;s+=o.offsetX*a/c,n-=o.offsetY*r/u,a*=o.width/c,r*=o.height/u}const l=this.filmOffset;l!==0&&(s+=e*l/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+a,n,n-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.fov=this.fov,n.object.zoom=this.zoom,n.object.near=this.near,n.object.far=this.far,n.object.focus=this.focus,n.object.aspect=this.aspect,this.view!==null&&(n.object.view=Object.assign({},this.view)),n.object.filmGauge=this.filmGauge,n.object.filmOffset=this.filmOffset,n}}const bg=-90,xg=1;class e1e extends Rs{constructor(e,n,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;const a=new Ao(bg,xg,e,n);a.layers=this.layers,this.add(a);const s=new Ao(bg,xg,e,n);s.layers=this.layers,this.add(s);const o=new Ao(bg,xg,e,n);o.layers=this.layers,this.add(o);const l=new Ao(bg,xg,e,n);l.layers=this.layers,this.add(l);const c=new Ao(bg,xg,e,n);c.layers=this.layers,this.add(c);const u=new Ao(bg,xg,e,n);u.layers=this.layers,this.add(u)}updateCoordinateSystem(){const e=this.coordinateSystem,n=this.children.concat(),[r,a,s,o,l,c]=n;for(const u of n)this.remove(u);if(e===Ac)r.up.set(0,1,0),r.lookAt(1,0,0),a.up.set(0,1,0),a.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),l.up.set(0,1,0),l.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Av)r.up.set(0,-1,0),r.lookAt(-1,0,0),a.up.set(0,-1,0),a.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),l.up.set(0,-1,0),l.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const u of n)this.add(u),u.updateMatrixWorld()}update(e,n){this.parent===null&&this.updateMatrixWorld();const{renderTarget:r,activeMipmapLevel:a}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,l,c,u,d]=this.children,h=e.getRenderTarget(),f=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),x=e.xr.enabled;e.xr.enabled=!1;const v=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,a),e.render(n,s),e.setRenderTarget(r,1,a),e.render(n,o),e.setRenderTarget(r,2,a),e.render(n,l),e.setRenderTarget(r,3,a),e.render(n,c),e.setRenderTarget(r,4,a),e.render(n,u),r.texture.generateMipmaps=v,e.setRenderTarget(r,5,a),e.render(n,d),e.setRenderTarget(h,f,p),e.xr.enabled=x,r.texture.needsPMREMUpdate=!0}}class $Y extends ro{constructor(e,n,r,a,s,o,l,c,u,d){e=e!==void 0?e:[],n=n!==void 0?n:yb,super(e,n,r,a,s,o,l,c,u,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class t1e extends If{constructor(e=1,n={}){super(e,e,n),this.isWebGLCubeRenderTarget=!0;const r={width:e,height:e,depth:1},a=[r,r,r,r,r,r];n.encoding!==void 0&&(Wy("THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace."),n.colorSpace=n.encoding===pf?Yi:cl),this.texture=new $Y(a,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=n.generateMipmaps!==void 0?n.generateMipmaps:!1,this.texture.minFilter=n.minFilter!==void 0?n.minFilter:ol}fromEquirectangularTexture(e,n){this.texture.type=n.type,this.texture.colorSpace=n.colorSpace,this.texture.generateMipmaps=n.generateMipmaps,this.texture.minFilter=n.minFilter,this.texture.magFilter=n.magFilter;const r={uniforms:{tEquirect:{value:null}},vertexShader:`
  3844. varying vec3 vWorldDirection;
  3845. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  3846. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  3847. }
  3848. void main() {
  3849. vWorldDirection = transformDirection( position, modelMatrix );
  3850. #include <begin_vertex>
  3851. #include <project_vertex>
  3852. }
  3853. `,fragmentShader:`
  3854. uniform sampler2D tEquirect;
  3855. varying vec3 vWorldDirection;
  3856. #include <common>
  3857. void main() {
  3858. vec3 direction = normalize( vWorldDirection );
  3859. vec2 sampleUV = equirectUv( direction );
  3860. gl_FragColor = texture2D( tEquirect, sampleUV );
  3861. }
  3862. `},a=new b0(5,5,5),s=new Kh({name:"CubemapFromEquirect",uniforms:Sb(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:no,blending:Fh});s.uniforms.tEquirect.value=n;const o=new Gl(a,s),l=n.minFilter;return n.minFilter===Cv&&(n.minFilter=ol),new e1e(1,10,this).update(e,o),n.minFilter=l,o.geometry.dispose(),o.material.dispose(),this}clear(e,n,r,a){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(n,r,a);e.setRenderTarget(s)}}const $P=new Ze,n1e=new Ze,r1e=new qn;class sh{constructor(e=new Ze(1,0,0),n=0){this.isPlane=!0,this.normal=e,this.constant=n}set(e,n){return this.normal.copy(e),this.constant=n,this}setComponents(e,n,r,a){return this.normal.set(e,n,r),this.constant=a,this}setFromNormalAndCoplanarPoint(e,n){return this.normal.copy(e),this.constant=-n.dot(this.normal),this}setFromCoplanarPoints(e,n,r){const a=$P.subVectors(r,n).cross(n1e.subVectors(e,n)).normalize();return this.setFromNormalAndCoplanarPoint(a,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,n){return n.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,n){const r=e.delta($P),a=this.normal.dot(r);if(a===0)return this.distanceToPoint(e.start)===0?n.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/a;return s<0||s>1?null:n.copy(e.start).addScaledVector(r,s)}intersectsLine(e){const n=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return n<0&&r>0||r<0&&n>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,n){const r=n||r1e.getNormalMatrix(e),a=this.coplanarPoint($P).applyMatrix4(e),s=this.normal.applyMatrix3(r).normalize();return this.constant=-a.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Fm=new jc,KS=new Ze;class ck{constructor(e=new sh,n=new sh,r=new sh,a=new sh,s=new sh,o=new sh){this.planes=[e,n,r,a,s,o]}set(e,n,r,a,s,o){const l=this.planes;return l[0].copy(e),l[1].copy(n),l[2].copy(r),l[3].copy(a),l[4].copy(s),l[5].copy(o),this}copy(e){const n=this.planes;for(let r=0;r<6;r++)n[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,n=Ac){const r=this.planes,a=e.elements,s=a[0],o=a[1],l=a[2],c=a[3],u=a[4],d=a[5],h=a[6],f=a[7],p=a[8],x=a[9],v=a[10],g=a[11],y=a[12],_=a[13],N=a[14],k=a[15];if(r[0].setComponents(c-s,f-u,g-p,k-y).normalize(),r[1].setComponents(c+s,f+u,g+p,k+y).normalize(),r[2].setComponents(c+o,f+d,g+x,k+_).normalize(),r[3].setComponents(c-o,f-d,g-x,k-_).normalize(),r[4].setComponents(c-l,f-h,g-v,k-N).normalize(),n===Ac)r[5].setComponents(c+l,f+h,g+v,k+N).normalize();else if(n===Av)r[5].setComponents(l,h,v,N).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+n);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Fm.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const n=e.geometry;n.boundingSphere===null&&n.computeBoundingSphere(),Fm.copy(n.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Fm)}intersectsSprite(e){return Fm.center.set(0,0,0),Fm.radius=.7071067811865476,Fm.applyMatrix4(e.matrixWorld),this.intersectsSphere(Fm)}intersectsSphere(e){const n=this.planes,r=e.center,a=-e.radius;for(let s=0;s<6;s++)if(n[s].distanceToPoint(r)<a)return!1;return!0}intersectsBox(e){const n=this.planes;for(let r=0;r<6;r++){const a=n[r];if(KS.x=a.normal.x>0?e.max.x:e.min.x,KS.y=a.normal.y>0?e.max.y:e.min.y,KS.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(KS)<0)return!1}return!0}containsPoint(e){const n=this.planes;for(let r=0;r<6;r++)if(n[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function VY(){let t=null,e=!1,n=null,r=null;function a(s,o){n(s,o),r=t.requestAnimationFrame(a)}return{start:function(){e!==!0&&n!==null&&(r=t.requestAnimationFrame(a),e=!0)},stop:function(){t.cancelAnimationFrame(r),e=!1},setAnimationLoop:function(s){n=s},setContext:function(s){t=s}}}function a1e(t,e){const n=e.isWebGL2,r=new WeakMap;function a(u,d){const h=u.array,f=u.usage,p=h.byteLength,x=t.createBuffer();t.bindBuffer(d,x),t.bufferData(d,h,f),u.onUploadCallback();let v;if(h instanceof Float32Array)v=t.FLOAT;else if(h instanceof Uint16Array)if(u.isFloat16BufferAttribute)if(n)v=t.HALF_FLOAT;else throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");else v=t.UNSIGNED_SHORT;else if(h instanceof Int16Array)v=t.SHORT;else if(h instanceof Uint32Array)v=t.UNSIGNED_INT;else if(h instanceof Int32Array)v=t.INT;else if(h instanceof Int8Array)v=t.BYTE;else if(h instanceof Uint8Array)v=t.UNSIGNED_BYTE;else if(h instanceof Uint8ClampedArray)v=t.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+h);return{buffer:x,type:v,bytesPerElement:h.BYTES_PER_ELEMENT,version:u.version,size:p}}function s(u,d,h){const f=d.array,p=d._updateRange,x=d.updateRanges;if(t.bindBuffer(h,u),p.count===-1&&x.length===0&&t.bufferSubData(h,0,f),x.length!==0){for(let v=0,g=x.length;v<g;v++){const y=x[v];n?t.bufferSubData(h,y.start*f.BYTES_PER_ELEMENT,f,y.start,y.count):t.bufferSubData(h,y.start*f.BYTES_PER_ELEMENT,f.subarray(y.start,y.start+y.count))}d.clearUpdateRanges()}p.count!==-1&&(n?t.bufferSubData(h,p.offset*f.BYTES_PER_ELEMENT,f,p.offset,p.count):t.bufferSubData(h,p.offset*f.BYTES_PER_ELEMENT,f.subarray(p.offset,p.offset+p.count)),p.count=-1),d.onUploadCallback()}function o(u){return u.isInterleavedBufferAttribute&&(u=u.data),r.get(u)}function l(u){u.isInterleavedBufferAttribute&&(u=u.data);const d=r.get(u);d&&(t.deleteBuffer(d.buffer),r.delete(u))}function c(u,d){if(u.isGLBufferAttribute){const f=r.get(u);(!f||f.version<u.version)&&r.set(u,{buffer:u.buffer,type:u.type,bytesPerElement:u.elementSize,version:u.version});return}u.isInterleavedBufferAttribute&&(u=u.data);const h=r.get(u);if(h===void 0)r.set(u,a(u,d));else if(h.version<u.version){if(h.size!==u.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");s(h.buffer,u,d),h.version=u.version}}return{get:o,remove:l,update:c}}class rL extends ys{constructor(e=1,n=1,r=1,a=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:n,widthSegments:r,heightSegments:a};const s=e/2,o=n/2,l=Math.floor(r),c=Math.floor(a),u=l+1,d=c+1,h=e/l,f=n/c,p=[],x=[],v=[],g=[];for(let y=0;y<d;y++){const _=y*f-o;for(let N=0;N<u;N++){const k=N*h-s;x.push(k,-_,0),v.push(0,0,1),g.push(N/l),g.push(1-y/c)}}for(let y=0;y<c;y++)for(let _=0;_<l;_++){const N=_+u*y,k=_+u*(y+1),A=_+1+u*(y+1),M=_+1+u*y;p.push(N,k,M),p.push(k,A,M)}this.setIndex(p),this.setAttribute("position",new Ha(x,3)),this.setAttribute("normal",new Ha(v,3)),this.setAttribute("uv",new Ha(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new rL(e.width,e.height,e.widthSegments,e.heightSegments)}}var i1e=`#ifdef USE_ALPHAHASH
  3863. if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
  3864. #endif`,s1e=`#ifdef USE_ALPHAHASH
  3865. const float ALPHA_HASH_SCALE = 0.05;
  3866. float hash2D( vec2 value ) {
  3867. return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
  3868. }
  3869. float hash3D( vec3 value ) {
  3870. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  3871. }
  3872. float getAlphaHashThreshold( vec3 position ) {
  3873. float maxDeriv = max(
  3874. length( dFdx( position.xyz ) ),
  3875. length( dFdy( position.xyz ) )
  3876. );
  3877. float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
  3878. vec2 pixScales = vec2(
  3879. exp2( floor( log2( pixScale ) ) ),
  3880. exp2( ceil( log2( pixScale ) ) )
  3881. );
  3882. vec2 alpha = vec2(
  3883. hash3D( floor( pixScales.x * position.xyz ) ),
  3884. hash3D( floor( pixScales.y * position.xyz ) )
  3885. );
  3886. float lerpFactor = fract( log2( pixScale ) );
  3887. float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
  3888. float a = min( lerpFactor, 1.0 - lerpFactor );
  3889. vec3 cases = vec3(
  3890. x * x / ( 2.0 * a * ( 1.0 - a ) ),
  3891. ( x - 0.5 * a ) / ( 1.0 - a ),
  3892. 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
  3893. );
  3894. float threshold = ( x < ( 1.0 - a ) )
  3895. ? ( ( x < a ) ? cases.x : cases.y )
  3896. : cases.z;
  3897. return clamp( threshold , 1.0e-6, 1.0 );
  3898. }
  3899. #endif`,o1e=`#ifdef USE_ALPHAMAP
  3900. diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
  3901. #endif`,l1e=`#ifdef USE_ALPHAMAP
  3902. uniform sampler2D alphaMap;
  3903. #endif`,c1e=`#ifdef USE_ALPHATEST
  3904. if ( diffuseColor.a < alphaTest ) discard;
  3905. #endif`,u1e=`#ifdef USE_ALPHATEST
  3906. uniform float alphaTest;
  3907. #endif`,d1e=`#ifdef USE_AOMAP
  3908. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  3909. reflectedLight.indirectDiffuse *= ambientOcclusion;
  3910. #if defined( USE_CLEARCOAT )
  3911. clearcoatSpecularIndirect *= ambientOcclusion;
  3912. #endif
  3913. #if defined( USE_SHEEN )
  3914. sheenSpecularIndirect *= ambientOcclusion;
  3915. #endif
  3916. #if defined( USE_ENVMAP ) && defined( STANDARD )
  3917. float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
  3918. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  3919. #endif
  3920. #endif`,h1e=`#ifdef USE_AOMAP
  3921. uniform sampler2D aoMap;
  3922. uniform float aoMapIntensity;
  3923. #endif`,m1e=`#ifdef USE_BATCHING
  3924. attribute float batchId;
  3925. uniform highp sampler2D batchingTexture;
  3926. mat4 getBatchingMatrix( const in float i ) {
  3927. int size = textureSize( batchingTexture, 0 ).x;
  3928. int j = int( i ) * 4;
  3929. int x = j % size;
  3930. int y = j / size;
  3931. vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
  3932. vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
  3933. vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
  3934. vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
  3935. return mat4( v1, v2, v3, v4 );
  3936. }
  3937. #endif`,f1e=`#ifdef USE_BATCHING
  3938. mat4 batchingMatrix = getBatchingMatrix( batchId );
  3939. #endif`,p1e=`vec3 transformed = vec3( position );
  3940. #ifdef USE_ALPHAHASH
  3941. vPosition = vec3( position );
  3942. #endif`,g1e=`vec3 objectNormal = vec3( normal );
  3943. #ifdef USE_TANGENT
  3944. vec3 objectTangent = vec3( tangent.xyz );
  3945. #endif`,b1e=`float G_BlinnPhong_Implicit( ) {
  3946. return 0.25;
  3947. }
  3948. float D_BlinnPhong( const in float shininess, const in float dotNH ) {
  3949. return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
  3950. }
  3951. vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
  3952. vec3 halfDir = normalize( lightDir + viewDir );
  3953. float dotNH = saturate( dot( normal, halfDir ) );
  3954. float dotVH = saturate( dot( viewDir, halfDir ) );
  3955. vec3 F = F_Schlick( specularColor, 1.0, dotVH );
  3956. float G = G_BlinnPhong_Implicit( );
  3957. float D = D_BlinnPhong( shininess, dotNH );
  3958. return F * ( G * D );
  3959. } // validated`,x1e=`#ifdef USE_IRIDESCENCE
  3960. const mat3 XYZ_TO_REC709 = mat3(
  3961. 3.2404542, -0.9692660, 0.0556434,
  3962. -1.5371385, 1.8760108, -0.2040259,
  3963. -0.4985314, 0.0415560, 1.0572252
  3964. );
  3965. vec3 Fresnel0ToIor( vec3 fresnel0 ) {
  3966. vec3 sqrtF0 = sqrt( fresnel0 );
  3967. return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
  3968. }
  3969. vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
  3970. return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
  3971. }
  3972. float IorToFresnel0( float transmittedIor, float incidentIor ) {
  3973. return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
  3974. }
  3975. vec3 evalSensitivity( float OPD, vec3 shift ) {
  3976. float phase = 2.0 * PI * OPD * 1.0e-9;
  3977. vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  3978. vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  3979. vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  3980. vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
  3981. xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
  3982. xyz /= 1.0685e-7;
  3983. vec3 rgb = XYZ_TO_REC709 * xyz;
  3984. return rgb;
  3985. }
  3986. vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
  3987. vec3 I;
  3988. float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  3989. float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
  3990. float cosTheta2Sq = 1.0 - sinTheta2Sq;
  3991. if ( cosTheta2Sq < 0.0 ) {
  3992. return vec3( 1.0 );
  3993. }
  3994. float cosTheta2 = sqrt( cosTheta2Sq );
  3995. float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  3996. float R12 = F_Schlick( R0, 1.0, cosTheta1 );
  3997. float T121 = 1.0 - R12;
  3998. float phi12 = 0.0;
  3999. if ( iridescenceIOR < outsideIOR ) phi12 = PI;
  4000. float phi21 = PI - phi12;
  4001. vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
  4002. vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
  4003. vec3 phi23 = vec3( 0.0 );
  4004. if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
  4005. if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
  4006. if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
  4007. float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
  4008. vec3 phi = vec3( phi21 ) + phi23;
  4009. vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
  4010. vec3 r123 = sqrt( R123 );
  4011. vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
  4012. vec3 C0 = R12 + Rs;
  4013. I = C0;
  4014. vec3 Cm = Rs - T121;
  4015. for ( int m = 1; m <= 2; ++ m ) {
  4016. Cm *= r123;
  4017. vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
  4018. I += Cm * Sm;
  4019. }
  4020. return max( I, vec3( 0.0 ) );
  4021. }
  4022. #endif`,y1e=`#ifdef USE_BUMPMAP
  4023. uniform sampler2D bumpMap;
  4024. uniform float bumpScale;
  4025. vec2 dHdxy_fwd() {
  4026. vec2 dSTdx = dFdx( vBumpMapUv );
  4027. vec2 dSTdy = dFdy( vBumpMapUv );
  4028. float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
  4029. float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
  4030. float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
  4031. return vec2( dBx, dBy );
  4032. }
  4033. vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
  4034. vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
  4035. vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
  4036. vec3 vN = surf_norm;
  4037. vec3 R1 = cross( vSigmaY, vN );
  4038. vec3 R2 = cross( vN, vSigmaX );
  4039. float fDet = dot( vSigmaX, R1 ) * faceDirection;
  4040. vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
  4041. return normalize( abs( fDet ) * surf_norm - vGrad );
  4042. }
  4043. #endif`,v1e=`#if NUM_CLIPPING_PLANES > 0
  4044. vec4 plane;
  4045. #pragma unroll_loop_start
  4046. for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
  4047. plane = clippingPlanes[ i ];
  4048. if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
  4049. }
  4050. #pragma unroll_loop_end
  4051. #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
  4052. bool clipped = true;
  4053. #pragma unroll_loop_start
  4054. for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
  4055. plane = clippingPlanes[ i ];
  4056. clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
  4057. }
  4058. #pragma unroll_loop_end
  4059. if ( clipped ) discard;
  4060. #endif
  4061. #endif`,w1e=`#if NUM_CLIPPING_PLANES > 0
  4062. varying vec3 vClipPosition;
  4063. uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
  4064. #endif`,S1e=`#if NUM_CLIPPING_PLANES > 0
  4065. varying vec3 vClipPosition;
  4066. #endif`,_1e=`#if NUM_CLIPPING_PLANES > 0
  4067. vClipPosition = - mvPosition.xyz;
  4068. #endif`,N1e=`#if defined( USE_COLOR_ALPHA )
  4069. diffuseColor *= vColor;
  4070. #elif defined( USE_COLOR )
  4071. diffuseColor.rgb *= vColor;
  4072. #endif`,C1e=`#if defined( USE_COLOR_ALPHA )
  4073. varying vec4 vColor;
  4074. #elif defined( USE_COLOR )
  4075. varying vec3 vColor;
  4076. #endif`,k1e=`#if defined( USE_COLOR_ALPHA )
  4077. varying vec4 vColor;
  4078. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4079. varying vec3 vColor;
  4080. #endif`,A1e=`#if defined( USE_COLOR_ALPHA )
  4081. vColor = vec4( 1.0 );
  4082. #elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )
  4083. vColor = vec3( 1.0 );
  4084. #endif
  4085. #ifdef USE_COLOR
  4086. vColor *= color;
  4087. #endif
  4088. #ifdef USE_INSTANCING_COLOR
  4089. vColor.xyz *= instanceColor.xyz;
  4090. #endif`,T1e=`#define PI 3.141592653589793
  4091. #define PI2 6.283185307179586
  4092. #define PI_HALF 1.5707963267948966
  4093. #define RECIPROCAL_PI 0.3183098861837907
  4094. #define RECIPROCAL_PI2 0.15915494309189535
  4095. #define EPSILON 1e-6
  4096. #ifndef saturate
  4097. #define saturate( a ) clamp( a, 0.0, 1.0 )
  4098. #endif
  4099. #define whiteComplement( a ) ( 1.0 - saturate( a ) )
  4100. float pow2( const in float x ) { return x*x; }
  4101. vec3 pow2( const in vec3 x ) { return x*x; }
  4102. float pow3( const in float x ) { return x*x*x; }
  4103. float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
  4104. float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
  4105. float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
  4106. highp float rand( const in vec2 uv ) {
  4107. const highp float a = 12.9898, b = 78.233, c = 43758.5453;
  4108. highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
  4109. return fract( sin( sn ) * c );
  4110. }
  4111. #ifdef HIGH_PRECISION
  4112. float precisionSafeLength( vec3 v ) { return length( v ); }
  4113. #else
  4114. float precisionSafeLength( vec3 v ) {
  4115. float maxComponent = max3( abs( v ) );
  4116. return length( v / maxComponent ) * maxComponent;
  4117. }
  4118. #endif
  4119. struct IncidentLight {
  4120. vec3 color;
  4121. vec3 direction;
  4122. bool visible;
  4123. };
  4124. struct ReflectedLight {
  4125. vec3 directDiffuse;
  4126. vec3 directSpecular;
  4127. vec3 indirectDiffuse;
  4128. vec3 indirectSpecular;
  4129. };
  4130. #ifdef USE_ALPHAHASH
  4131. varying vec3 vPosition;
  4132. #endif
  4133. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  4134. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  4135. }
  4136. vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
  4137. return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
  4138. }
  4139. mat3 transposeMat3( const in mat3 m ) {
  4140. mat3 tmp;
  4141. tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
  4142. tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
  4143. tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
  4144. return tmp;
  4145. }
  4146. float luminance( const in vec3 rgb ) {
  4147. const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );
  4148. return dot( weights, rgb );
  4149. }
  4150. bool isPerspectiveMatrix( mat4 m ) {
  4151. return m[ 2 ][ 3 ] == - 1.0;
  4152. }
  4153. vec2 equirectUv( in vec3 dir ) {
  4154. float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
  4155. float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
  4156. return vec2( u, v );
  4157. }
  4158. vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
  4159. return RECIPROCAL_PI * diffuseColor;
  4160. }
  4161. vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
  4162. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4163. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4164. }
  4165. float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
  4166. float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
  4167. return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
  4168. } // validated`,M1e=`#ifdef ENVMAP_TYPE_CUBE_UV
  4169. #define cubeUV_minMipLevel 4.0
  4170. #define cubeUV_minTileSize 16.0
  4171. float getFace( vec3 direction ) {
  4172. vec3 absDirection = abs( direction );
  4173. float face = - 1.0;
  4174. if ( absDirection.x > absDirection.z ) {
  4175. if ( absDirection.x > absDirection.y )
  4176. face = direction.x > 0.0 ? 0.0 : 3.0;
  4177. else
  4178. face = direction.y > 0.0 ? 1.0 : 4.0;
  4179. } else {
  4180. if ( absDirection.z > absDirection.y )
  4181. face = direction.z > 0.0 ? 2.0 : 5.0;
  4182. else
  4183. face = direction.y > 0.0 ? 1.0 : 4.0;
  4184. }
  4185. return face;
  4186. }
  4187. vec2 getUV( vec3 direction, float face ) {
  4188. vec2 uv;
  4189. if ( face == 0.0 ) {
  4190. uv = vec2( direction.z, direction.y ) / abs( direction.x );
  4191. } else if ( face == 1.0 ) {
  4192. uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
  4193. } else if ( face == 2.0 ) {
  4194. uv = vec2( - direction.x, direction.y ) / abs( direction.z );
  4195. } else if ( face == 3.0 ) {
  4196. uv = vec2( - direction.z, direction.y ) / abs( direction.x );
  4197. } else if ( face == 4.0 ) {
  4198. uv = vec2( - direction.x, direction.z ) / abs( direction.y );
  4199. } else {
  4200. uv = vec2( direction.x, direction.y ) / abs( direction.z );
  4201. }
  4202. return 0.5 * ( uv + 1.0 );
  4203. }
  4204. vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
  4205. float face = getFace( direction );
  4206. float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
  4207. mipInt = max( mipInt, cubeUV_minMipLevel );
  4208. float faceSize = exp2( mipInt );
  4209. highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
  4210. if ( face > 2.0 ) {
  4211. uv.y += faceSize;
  4212. face -= 3.0;
  4213. }
  4214. uv.x += face * faceSize;
  4215. uv.x += filterInt * 3.0 * cubeUV_minTileSize;
  4216. uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
  4217. uv.x *= CUBEUV_TEXEL_WIDTH;
  4218. uv.y *= CUBEUV_TEXEL_HEIGHT;
  4219. #ifdef texture2DGradEXT
  4220. return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
  4221. #else
  4222. return texture2D( envMap, uv ).rgb;
  4223. #endif
  4224. }
  4225. #define cubeUV_r0 1.0
  4226. #define cubeUV_v0 0.339
  4227. #define cubeUV_m0 - 2.0
  4228. #define cubeUV_r1 0.8
  4229. #define cubeUV_v1 0.276
  4230. #define cubeUV_m1 - 1.0
  4231. #define cubeUV_r4 0.4
  4232. #define cubeUV_v4 0.046
  4233. #define cubeUV_m4 2.0
  4234. #define cubeUV_r5 0.305
  4235. #define cubeUV_v5 0.016
  4236. #define cubeUV_m5 3.0
  4237. #define cubeUV_r6 0.21
  4238. #define cubeUV_v6 0.0038
  4239. #define cubeUV_m6 4.0
  4240. float roughnessToMip( float roughness ) {
  4241. float mip = 0.0;
  4242. if ( roughness >= cubeUV_r1 ) {
  4243. mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
  4244. } else if ( roughness >= cubeUV_r4 ) {
  4245. mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
  4246. } else if ( roughness >= cubeUV_r5 ) {
  4247. mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
  4248. } else if ( roughness >= cubeUV_r6 ) {
  4249. mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
  4250. } else {
  4251. mip = - 2.0 * log2( 1.16 * roughness ); }
  4252. return mip;
  4253. }
  4254. vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
  4255. float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  4256. float mipF = fract( mip );
  4257. float mipInt = floor( mip );
  4258. vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
  4259. if ( mipF == 0.0 ) {
  4260. return vec4( color0, 1.0 );
  4261. } else {
  4262. vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
  4263. return vec4( mix( color0, color1, mipF ), 1.0 );
  4264. }
  4265. }
  4266. #endif`,P1e=`vec3 transformedNormal = objectNormal;
  4267. #ifdef USE_TANGENT
  4268. vec3 transformedTangent = objectTangent;
  4269. #endif
  4270. #ifdef USE_BATCHING
  4271. mat3 bm = mat3( batchingMatrix );
  4272. transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
  4273. transformedNormal = bm * transformedNormal;
  4274. #ifdef USE_TANGENT
  4275. transformedTangent = bm * transformedTangent;
  4276. #endif
  4277. #endif
  4278. #ifdef USE_INSTANCING
  4279. mat3 im = mat3( instanceMatrix );
  4280. transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
  4281. transformedNormal = im * transformedNormal;
  4282. #ifdef USE_TANGENT
  4283. transformedTangent = im * transformedTangent;
  4284. #endif
  4285. #endif
  4286. transformedNormal = normalMatrix * transformedNormal;
  4287. #ifdef FLIP_SIDED
  4288. transformedNormal = - transformedNormal;
  4289. #endif
  4290. #ifdef USE_TANGENT
  4291. transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
  4292. #ifdef FLIP_SIDED
  4293. transformedTangent = - transformedTangent;
  4294. #endif
  4295. #endif`,E1e=`#ifdef USE_DISPLACEMENTMAP
  4296. uniform sampler2D displacementMap;
  4297. uniform float displacementScale;
  4298. uniform float displacementBias;
  4299. #endif`,j1e=`#ifdef USE_DISPLACEMENTMAP
  4300. transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
  4301. #endif`,D1e=`#ifdef USE_EMISSIVEMAP
  4302. vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
  4303. totalEmissiveRadiance *= emissiveColor.rgb;
  4304. #endif`,R1e=`#ifdef USE_EMISSIVEMAP
  4305. uniform sampler2D emissiveMap;
  4306. #endif`,F1e="gl_FragColor = linearToOutputTexel( gl_FragColor );",L1e=`
  4307. const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
  4308. vec3( 0.8224621, 0.177538, 0.0 ),
  4309. vec3( 0.0331941, 0.9668058, 0.0 ),
  4310. vec3( 0.0170827, 0.0723974, 0.9105199 )
  4311. );
  4312. const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
  4313. vec3( 1.2249401, - 0.2249404, 0.0 ),
  4314. vec3( - 0.0420569, 1.0420571, 0.0 ),
  4315. vec3( - 0.0196376, - 0.0786361, 1.0982735 )
  4316. );
  4317. vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
  4318. return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
  4319. }
  4320. vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
  4321. return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
  4322. }
  4323. vec4 LinearTransferOETF( in vec4 value ) {
  4324. return value;
  4325. }
  4326. vec4 sRGBTransferOETF( in vec4 value ) {
  4327. return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
  4328. }
  4329. vec4 LinearToLinear( in vec4 value ) {
  4330. return value;
  4331. }
  4332. vec4 LinearTosRGB( in vec4 value ) {
  4333. return sRGBTransferOETF( value );
  4334. }`,O1e=`#ifdef USE_ENVMAP
  4335. #ifdef ENV_WORLDPOS
  4336. vec3 cameraToFrag;
  4337. if ( isOrthographic ) {
  4338. cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4339. } else {
  4340. cameraToFrag = normalize( vWorldPosition - cameraPosition );
  4341. }
  4342. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4343. #ifdef ENVMAP_MODE_REFLECTION
  4344. vec3 reflectVec = reflect( cameraToFrag, worldNormal );
  4345. #else
  4346. vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
  4347. #endif
  4348. #else
  4349. vec3 reflectVec = vReflect;
  4350. #endif
  4351. #ifdef ENVMAP_TYPE_CUBE
  4352. vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
  4353. #else
  4354. vec4 envColor = vec4( 0.0 );
  4355. #endif
  4356. #ifdef ENVMAP_BLENDING_MULTIPLY
  4357. outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
  4358. #elif defined( ENVMAP_BLENDING_MIX )
  4359. outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
  4360. #elif defined( ENVMAP_BLENDING_ADD )
  4361. outgoingLight += envColor.xyz * specularStrength * reflectivity;
  4362. #endif
  4363. #endif`,I1e=`#ifdef USE_ENVMAP
  4364. uniform float envMapIntensity;
  4365. uniform float flipEnvMap;
  4366. #ifdef ENVMAP_TYPE_CUBE
  4367. uniform samplerCube envMap;
  4368. #else
  4369. uniform sampler2D envMap;
  4370. #endif
  4371. #endif`,z1e=`#ifdef USE_ENVMAP
  4372. uniform float reflectivity;
  4373. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4374. #define ENV_WORLDPOS
  4375. #endif
  4376. #ifdef ENV_WORLDPOS
  4377. varying vec3 vWorldPosition;
  4378. uniform float refractionRatio;
  4379. #else
  4380. varying vec3 vReflect;
  4381. #endif
  4382. #endif`,U1e=`#ifdef USE_ENVMAP
  4383. #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
  4384. #define ENV_WORLDPOS
  4385. #endif
  4386. #ifdef ENV_WORLDPOS
  4387. varying vec3 vWorldPosition;
  4388. #else
  4389. varying vec3 vReflect;
  4390. uniform float refractionRatio;
  4391. #endif
  4392. #endif`,B1e=`#ifdef USE_ENVMAP
  4393. #ifdef ENV_WORLDPOS
  4394. vWorldPosition = worldPosition.xyz;
  4395. #else
  4396. vec3 cameraToVertex;
  4397. if ( isOrthographic ) {
  4398. cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
  4399. } else {
  4400. cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
  4401. }
  4402. vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  4403. #ifdef ENVMAP_MODE_REFLECTION
  4404. vReflect = reflect( cameraToVertex, worldNormal );
  4405. #else
  4406. vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
  4407. #endif
  4408. #endif
  4409. #endif`,H1e=`#ifdef USE_FOG
  4410. vFogDepth = - mvPosition.z;
  4411. #endif`,$1e=`#ifdef USE_FOG
  4412. varying float vFogDepth;
  4413. #endif`,V1e=`#ifdef USE_FOG
  4414. #ifdef FOG_EXP2
  4415. float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
  4416. #else
  4417. float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
  4418. #endif
  4419. gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
  4420. #endif`,q1e=`#ifdef USE_FOG
  4421. uniform vec3 fogColor;
  4422. varying float vFogDepth;
  4423. #ifdef FOG_EXP2
  4424. uniform float fogDensity;
  4425. #else
  4426. uniform float fogNear;
  4427. uniform float fogFar;
  4428. #endif
  4429. #endif`,G1e=`#ifdef USE_GRADIENTMAP
  4430. uniform sampler2D gradientMap;
  4431. #endif
  4432. vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
  4433. float dotNL = dot( normal, lightDirection );
  4434. vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
  4435. #ifdef USE_GRADIENTMAP
  4436. return vec3( texture2D( gradientMap, coord ).r );
  4437. #else
  4438. vec2 fw = fwidth( coord ) * 0.5;
  4439. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
  4440. #endif
  4441. }`,W1e=`#ifdef USE_LIGHTMAP
  4442. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  4443. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  4444. reflectedLight.indirectDiffuse += lightMapIrradiance;
  4445. #endif`,K1e=`#ifdef USE_LIGHTMAP
  4446. uniform sampler2D lightMap;
  4447. uniform float lightMapIntensity;
  4448. #endif`,X1e=`LambertMaterial material;
  4449. material.diffuseColor = diffuseColor.rgb;
  4450. material.specularStrength = specularStrength;`,Y1e=`varying vec3 vViewPosition;
  4451. struct LambertMaterial {
  4452. vec3 diffuseColor;
  4453. float specularStrength;
  4454. };
  4455. void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
  4456. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4457. vec3 irradiance = dotNL * directLight.color;
  4458. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4459. }
  4460. void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
  4461. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4462. }
  4463. #define RE_Direct RE_Direct_Lambert
  4464. #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Q1e=`uniform bool receiveShadow;
  4465. uniform vec3 ambientLightColor;
  4466. #if defined( USE_LIGHT_PROBES )
  4467. uniform vec3 lightProbe[ 9 ];
  4468. #endif
  4469. vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
  4470. float x = normal.x, y = normal.y, z = normal.z;
  4471. vec3 result = shCoefficients[ 0 ] * 0.886227;
  4472. result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
  4473. result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
  4474. result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
  4475. result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
  4476. result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
  4477. result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
  4478. result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
  4479. result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
  4480. return result;
  4481. }
  4482. vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
  4483. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4484. vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
  4485. return irradiance;
  4486. }
  4487. vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
  4488. vec3 irradiance = ambientLightColor;
  4489. return irradiance;
  4490. }
  4491. float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
  4492. #if defined ( LEGACY_LIGHTS )
  4493. if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {
  4494. return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );
  4495. }
  4496. return 1.0;
  4497. #else
  4498. float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
  4499. if ( cutoffDistance > 0.0 ) {
  4500. distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
  4501. }
  4502. return distanceFalloff;
  4503. #endif
  4504. }
  4505. float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
  4506. return smoothstep( coneCosine, penumbraCosine, angleCosine );
  4507. }
  4508. #if NUM_DIR_LIGHTS > 0
  4509. struct DirectionalLight {
  4510. vec3 direction;
  4511. vec3 color;
  4512. };
  4513. uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
  4514. void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
  4515. light.color = directionalLight.color;
  4516. light.direction = directionalLight.direction;
  4517. light.visible = true;
  4518. }
  4519. #endif
  4520. #if NUM_POINT_LIGHTS > 0
  4521. struct PointLight {
  4522. vec3 position;
  4523. vec3 color;
  4524. float distance;
  4525. float decay;
  4526. };
  4527. uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
  4528. void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4529. vec3 lVector = pointLight.position - geometryPosition;
  4530. light.direction = normalize( lVector );
  4531. float lightDistance = length( lVector );
  4532. light.color = pointLight.color;
  4533. light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
  4534. light.visible = ( light.color != vec3( 0.0 ) );
  4535. }
  4536. #endif
  4537. #if NUM_SPOT_LIGHTS > 0
  4538. struct SpotLight {
  4539. vec3 position;
  4540. vec3 direction;
  4541. vec3 color;
  4542. float distance;
  4543. float decay;
  4544. float coneCos;
  4545. float penumbraCos;
  4546. };
  4547. uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
  4548. void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
  4549. vec3 lVector = spotLight.position - geometryPosition;
  4550. light.direction = normalize( lVector );
  4551. float angleCos = dot( light.direction, spotLight.direction );
  4552. float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
  4553. if ( spotAttenuation > 0.0 ) {
  4554. float lightDistance = length( lVector );
  4555. light.color = spotLight.color * spotAttenuation;
  4556. light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
  4557. light.visible = ( light.color != vec3( 0.0 ) );
  4558. } else {
  4559. light.color = vec3( 0.0 );
  4560. light.visible = false;
  4561. }
  4562. }
  4563. #endif
  4564. #if NUM_RECT_AREA_LIGHTS > 0
  4565. struct RectAreaLight {
  4566. vec3 color;
  4567. vec3 position;
  4568. vec3 halfWidth;
  4569. vec3 halfHeight;
  4570. };
  4571. uniform sampler2D ltc_1; uniform sampler2D ltc_2;
  4572. uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
  4573. #endif
  4574. #if NUM_HEMI_LIGHTS > 0
  4575. struct HemisphereLight {
  4576. vec3 direction;
  4577. vec3 skyColor;
  4578. vec3 groundColor;
  4579. };
  4580. uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
  4581. vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
  4582. float dotNL = dot( normal, hemiLight.direction );
  4583. float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
  4584. vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
  4585. return irradiance;
  4586. }
  4587. #endif`,Z1e=`#ifdef USE_ENVMAP
  4588. vec3 getIBLIrradiance( const in vec3 normal ) {
  4589. #ifdef ENVMAP_TYPE_CUBE_UV
  4590. vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
  4591. vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );
  4592. return PI * envMapColor.rgb * envMapIntensity;
  4593. #else
  4594. return vec3( 0.0 );
  4595. #endif
  4596. }
  4597. vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
  4598. #ifdef ENVMAP_TYPE_CUBE_UV
  4599. vec3 reflectVec = reflect( - viewDir, normal );
  4600. reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
  4601. reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
  4602. vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );
  4603. return envMapColor.rgb * envMapIntensity;
  4604. #else
  4605. return vec3( 0.0 );
  4606. #endif
  4607. }
  4608. #ifdef USE_ANISOTROPY
  4609. vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
  4610. #ifdef ENVMAP_TYPE_CUBE_UV
  4611. vec3 bentNormal = cross( bitangent, viewDir );
  4612. bentNormal = normalize( cross( bentNormal, bitangent ) );
  4613. bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
  4614. return getIBLRadiance( viewDir, bentNormal, roughness );
  4615. #else
  4616. return vec3( 0.0 );
  4617. #endif
  4618. }
  4619. #endif
  4620. #endif`,J1e=`ToonMaterial material;
  4621. material.diffuseColor = diffuseColor.rgb;`,eNe=`varying vec3 vViewPosition;
  4622. struct ToonMaterial {
  4623. vec3 diffuseColor;
  4624. };
  4625. void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
  4626. vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
  4627. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4628. }
  4629. void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
  4630. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4631. }
  4632. #define RE_Direct RE_Direct_Toon
  4633. #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,tNe=`BlinnPhongMaterial material;
  4634. material.diffuseColor = diffuseColor.rgb;
  4635. material.specularColor = specular;
  4636. material.specularShininess = shininess;
  4637. material.specularStrength = specularStrength;`,nNe=`varying vec3 vViewPosition;
  4638. struct BlinnPhongMaterial {
  4639. vec3 diffuseColor;
  4640. vec3 specularColor;
  4641. float specularShininess;
  4642. float specularStrength;
  4643. };
  4644. void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
  4645. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4646. vec3 irradiance = dotNL * directLight.color;
  4647. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4648. reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
  4649. }
  4650. void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
  4651. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  4652. }
  4653. #define RE_Direct RE_Direct_BlinnPhong
  4654. #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,rNe=`PhysicalMaterial material;
  4655. material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
  4656. vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
  4657. float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
  4658. material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
  4659. material.roughness = min( material.roughness, 1.0 );
  4660. #ifdef IOR
  4661. material.ior = ior;
  4662. #ifdef USE_SPECULAR
  4663. float specularIntensityFactor = specularIntensity;
  4664. vec3 specularColorFactor = specularColor;
  4665. #ifdef USE_SPECULAR_COLORMAP
  4666. specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
  4667. #endif
  4668. #ifdef USE_SPECULAR_INTENSITYMAP
  4669. specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
  4670. #endif
  4671. material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
  4672. #else
  4673. float specularIntensityFactor = 1.0;
  4674. vec3 specularColorFactor = vec3( 1.0 );
  4675. material.specularF90 = 1.0;
  4676. #endif
  4677. material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
  4678. #else
  4679. material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
  4680. material.specularF90 = 1.0;
  4681. #endif
  4682. #ifdef USE_CLEARCOAT
  4683. material.clearcoat = clearcoat;
  4684. material.clearcoatRoughness = clearcoatRoughness;
  4685. material.clearcoatF0 = vec3( 0.04 );
  4686. material.clearcoatF90 = 1.0;
  4687. #ifdef USE_CLEARCOATMAP
  4688. material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
  4689. #endif
  4690. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  4691. material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
  4692. #endif
  4693. material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
  4694. material.clearcoatRoughness += geometryRoughness;
  4695. material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
  4696. #endif
  4697. #ifdef USE_IRIDESCENCE
  4698. material.iridescence = iridescence;
  4699. material.iridescenceIOR = iridescenceIOR;
  4700. #ifdef USE_IRIDESCENCEMAP
  4701. material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
  4702. #endif
  4703. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  4704. material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
  4705. #else
  4706. material.iridescenceThickness = iridescenceThicknessMaximum;
  4707. #endif
  4708. #endif
  4709. #ifdef USE_SHEEN
  4710. material.sheenColor = sheenColor;
  4711. #ifdef USE_SHEEN_COLORMAP
  4712. material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
  4713. #endif
  4714. material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
  4715. #ifdef USE_SHEEN_ROUGHNESSMAP
  4716. material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
  4717. #endif
  4718. #endif
  4719. #ifdef USE_ANISOTROPY
  4720. #ifdef USE_ANISOTROPYMAP
  4721. mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
  4722. vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
  4723. vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
  4724. #else
  4725. vec2 anisotropyV = anisotropyVector;
  4726. #endif
  4727. material.anisotropy = length( anisotropyV );
  4728. if( material.anisotropy == 0.0 ) {
  4729. anisotropyV = vec2( 1.0, 0.0 );
  4730. } else {
  4731. anisotropyV /= material.anisotropy;
  4732. material.anisotropy = saturate( material.anisotropy );
  4733. }
  4734. material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
  4735. material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
  4736. material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
  4737. #endif`,aNe=`struct PhysicalMaterial {
  4738. vec3 diffuseColor;
  4739. float roughness;
  4740. vec3 specularColor;
  4741. float specularF90;
  4742. #ifdef USE_CLEARCOAT
  4743. float clearcoat;
  4744. float clearcoatRoughness;
  4745. vec3 clearcoatF0;
  4746. float clearcoatF90;
  4747. #endif
  4748. #ifdef USE_IRIDESCENCE
  4749. float iridescence;
  4750. float iridescenceIOR;
  4751. float iridescenceThickness;
  4752. vec3 iridescenceFresnel;
  4753. vec3 iridescenceF0;
  4754. #endif
  4755. #ifdef USE_SHEEN
  4756. vec3 sheenColor;
  4757. float sheenRoughness;
  4758. #endif
  4759. #ifdef IOR
  4760. float ior;
  4761. #endif
  4762. #ifdef USE_TRANSMISSION
  4763. float transmission;
  4764. float transmissionAlpha;
  4765. float thickness;
  4766. float attenuationDistance;
  4767. vec3 attenuationColor;
  4768. #endif
  4769. #ifdef USE_ANISOTROPY
  4770. float anisotropy;
  4771. float alphaT;
  4772. vec3 anisotropyT;
  4773. vec3 anisotropyB;
  4774. #endif
  4775. };
  4776. vec3 clearcoatSpecularDirect = vec3( 0.0 );
  4777. vec3 clearcoatSpecularIndirect = vec3( 0.0 );
  4778. vec3 sheenSpecularDirect = vec3( 0.0 );
  4779. vec3 sheenSpecularIndirect = vec3(0.0 );
  4780. vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
  4781. float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
  4782. float x2 = x * x;
  4783. float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
  4784. return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
  4785. }
  4786. float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
  4787. float a2 = pow2( alpha );
  4788. float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
  4789. float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
  4790. return 0.5 / max( gv + gl, EPSILON );
  4791. }
  4792. float D_GGX( const in float alpha, const in float dotNH ) {
  4793. float a2 = pow2( alpha );
  4794. float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
  4795. return RECIPROCAL_PI * a2 / pow2( denom );
  4796. }
  4797. #ifdef USE_ANISOTROPY
  4798. float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
  4799. float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
  4800. float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
  4801. float v = 0.5 / ( gv + gl );
  4802. return saturate(v);
  4803. }
  4804. float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
  4805. float a2 = alphaT * alphaB;
  4806. highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
  4807. highp float v2 = dot( v, v );
  4808. float w2 = a2 / v2;
  4809. return RECIPROCAL_PI * a2 * pow2 ( w2 );
  4810. }
  4811. #endif
  4812. #ifdef USE_CLEARCOAT
  4813. vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
  4814. vec3 f0 = material.clearcoatF0;
  4815. float f90 = material.clearcoatF90;
  4816. float roughness = material.clearcoatRoughness;
  4817. float alpha = pow2( roughness );
  4818. vec3 halfDir = normalize( lightDir + viewDir );
  4819. float dotNL = saturate( dot( normal, lightDir ) );
  4820. float dotNV = saturate( dot( normal, viewDir ) );
  4821. float dotNH = saturate( dot( normal, halfDir ) );
  4822. float dotVH = saturate( dot( viewDir, halfDir ) );
  4823. vec3 F = F_Schlick( f0, f90, dotVH );
  4824. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4825. float D = D_GGX( alpha, dotNH );
  4826. return F * ( V * D );
  4827. }
  4828. #endif
  4829. vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
  4830. vec3 f0 = material.specularColor;
  4831. float f90 = material.specularF90;
  4832. float roughness = material.roughness;
  4833. float alpha = pow2( roughness );
  4834. vec3 halfDir = normalize( lightDir + viewDir );
  4835. float dotNL = saturate( dot( normal, lightDir ) );
  4836. float dotNV = saturate( dot( normal, viewDir ) );
  4837. float dotNH = saturate( dot( normal, halfDir ) );
  4838. float dotVH = saturate( dot( viewDir, halfDir ) );
  4839. vec3 F = F_Schlick( f0, f90, dotVH );
  4840. #ifdef USE_IRIDESCENCE
  4841. F = mix( F, material.iridescenceFresnel, material.iridescence );
  4842. #endif
  4843. #ifdef USE_ANISOTROPY
  4844. float dotTL = dot( material.anisotropyT, lightDir );
  4845. float dotTV = dot( material.anisotropyT, viewDir );
  4846. float dotTH = dot( material.anisotropyT, halfDir );
  4847. float dotBL = dot( material.anisotropyB, lightDir );
  4848. float dotBV = dot( material.anisotropyB, viewDir );
  4849. float dotBH = dot( material.anisotropyB, halfDir );
  4850. float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
  4851. float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
  4852. #else
  4853. float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
  4854. float D = D_GGX( alpha, dotNH );
  4855. #endif
  4856. return F * ( V * D );
  4857. }
  4858. vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
  4859. const float LUT_SIZE = 64.0;
  4860. const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  4861. const float LUT_BIAS = 0.5 / LUT_SIZE;
  4862. float dotNV = saturate( dot( N, V ) );
  4863. vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
  4864. uv = uv * LUT_SCALE + LUT_BIAS;
  4865. return uv;
  4866. }
  4867. float LTC_ClippedSphereFormFactor( const in vec3 f ) {
  4868. float l = length( f );
  4869. return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
  4870. }
  4871. vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
  4872. float x = dot( v1, v2 );
  4873. float y = abs( x );
  4874. float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
  4875. float b = 3.4175940 + ( 4.1616724 + y ) * y;
  4876. float v = a / b;
  4877. float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
  4878. return cross( v1, v2 ) * theta_sintheta;
  4879. }
  4880. vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
  4881. vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
  4882. vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
  4883. vec3 lightNormal = cross( v1, v2 );
  4884. if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
  4885. vec3 T1, T2;
  4886. T1 = normalize( V - N * dot( V, N ) );
  4887. T2 = - cross( N, T1 );
  4888. mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
  4889. vec3 coords[ 4 ];
  4890. coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
  4891. coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
  4892. coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
  4893. coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
  4894. coords[ 0 ] = normalize( coords[ 0 ] );
  4895. coords[ 1 ] = normalize( coords[ 1 ] );
  4896. coords[ 2 ] = normalize( coords[ 2 ] );
  4897. coords[ 3 ] = normalize( coords[ 3 ] );
  4898. vec3 vectorFormFactor = vec3( 0.0 );
  4899. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
  4900. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
  4901. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
  4902. vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
  4903. float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
  4904. return vec3( result );
  4905. }
  4906. #if defined( USE_SHEEN )
  4907. float D_Charlie( float roughness, float dotNH ) {
  4908. float alpha = pow2( roughness );
  4909. float invAlpha = 1.0 / alpha;
  4910. float cos2h = dotNH * dotNH;
  4911. float sin2h = max( 1.0 - cos2h, 0.0078125 );
  4912. return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
  4913. }
  4914. float V_Neubelt( float dotNV, float dotNL ) {
  4915. return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
  4916. }
  4917. vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
  4918. vec3 halfDir = normalize( lightDir + viewDir );
  4919. float dotNL = saturate( dot( normal, lightDir ) );
  4920. float dotNV = saturate( dot( normal, viewDir ) );
  4921. float dotNH = saturate( dot( normal, halfDir ) );
  4922. float D = D_Charlie( sheenRoughness, dotNH );
  4923. float V = V_Neubelt( dotNV, dotNL );
  4924. return sheenColor * ( D * V );
  4925. }
  4926. #endif
  4927. float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4928. float dotNV = saturate( dot( normal, viewDir ) );
  4929. float r2 = roughness * roughness;
  4930. float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
  4931. float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
  4932. float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
  4933. return saturate( DG * RECIPROCAL_PI );
  4934. }
  4935. vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
  4936. float dotNV = saturate( dot( normal, viewDir ) );
  4937. const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  4938. const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  4939. vec4 r = roughness * c0 + c1;
  4940. float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
  4941. vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
  4942. return fab;
  4943. }
  4944. vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
  4945. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4946. return specularColor * fab.x + specularF90 * fab.y;
  4947. }
  4948. #ifdef USE_IRIDESCENCE
  4949. void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
  4950. #else
  4951. void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
  4952. #endif
  4953. vec2 fab = DFGApprox( normal, viewDir, roughness );
  4954. #ifdef USE_IRIDESCENCE
  4955. vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
  4956. #else
  4957. vec3 Fr = specularColor;
  4958. #endif
  4959. vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
  4960. float Ess = fab.x + fab.y;
  4961. float Ems = 1.0 - Ess;
  4962. vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
  4963. singleScatter += FssEss;
  4964. multiScatter += Fms * Ems;
  4965. }
  4966. #if NUM_RECT_AREA_LIGHTS > 0
  4967. void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  4968. vec3 normal = geometryNormal;
  4969. vec3 viewDir = geometryViewDir;
  4970. vec3 position = geometryPosition;
  4971. vec3 lightPos = rectAreaLight.position;
  4972. vec3 halfWidth = rectAreaLight.halfWidth;
  4973. vec3 halfHeight = rectAreaLight.halfHeight;
  4974. vec3 lightColor = rectAreaLight.color;
  4975. float roughness = material.roughness;
  4976. vec3 rectCoords[ 4 ];
  4977. rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
  4978. rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
  4979. rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
  4980. vec2 uv = LTC_Uv( normal, viewDir, roughness );
  4981. vec4 t1 = texture2D( ltc_1, uv );
  4982. vec4 t2 = texture2D( ltc_2, uv );
  4983. mat3 mInv = mat3(
  4984. vec3( t1.x, 0, t1.y ),
  4985. vec3( 0, 1, 0 ),
  4986. vec3( t1.z, 0, t1.w )
  4987. );
  4988. vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
  4989. reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
  4990. reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
  4991. }
  4992. #endif
  4993. void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  4994. float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
  4995. vec3 irradiance = dotNL * directLight.color;
  4996. #ifdef USE_CLEARCOAT
  4997. float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
  4998. vec3 ccIrradiance = dotNLcc * directLight.color;
  4999. clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
  5000. #endif
  5001. #ifdef USE_SHEEN
  5002. sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
  5003. #endif
  5004. reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
  5005. reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5006. }
  5007. void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
  5008. reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
  5009. }
  5010. void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
  5011. #ifdef USE_CLEARCOAT
  5012. clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
  5013. #endif
  5014. #ifdef USE_SHEEN
  5015. sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
  5016. #endif
  5017. vec3 singleScattering = vec3( 0.0 );
  5018. vec3 multiScattering = vec3( 0.0 );
  5019. vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
  5020. #ifdef USE_IRIDESCENCE
  5021. computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
  5022. #else
  5023. computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
  5024. #endif
  5025. vec3 totalScattering = singleScattering + multiScattering;
  5026. vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
  5027. reflectedLight.indirectSpecular += radiance * singleScattering;
  5028. reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
  5029. reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
  5030. }
  5031. #define RE_Direct RE_Direct_Physical
  5032. #define RE_Direct_RectArea RE_Direct_RectArea_Physical
  5033. #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
  5034. #define RE_IndirectSpecular RE_IndirectSpecular_Physical
  5035. float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
  5036. return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
  5037. }`,iNe=`
  5038. vec3 geometryPosition = - vViewPosition;
  5039. vec3 geometryNormal = normal;
  5040. vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
  5041. vec3 geometryClearcoatNormal = vec3( 0.0 );
  5042. #ifdef USE_CLEARCOAT
  5043. geometryClearcoatNormal = clearcoatNormal;
  5044. #endif
  5045. #ifdef USE_IRIDESCENCE
  5046. float dotNVi = saturate( dot( normal, geometryViewDir ) );
  5047. if ( material.iridescenceThickness == 0.0 ) {
  5048. material.iridescence = 0.0;
  5049. } else {
  5050. material.iridescence = saturate( material.iridescence );
  5051. }
  5052. if ( material.iridescence > 0.0 ) {
  5053. material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
  5054. material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
  5055. }
  5056. #endif
  5057. IncidentLight directLight;
  5058. #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
  5059. PointLight pointLight;
  5060. #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
  5061. PointLightShadow pointLightShadow;
  5062. #endif
  5063. #pragma unroll_loop_start
  5064. for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
  5065. pointLight = pointLights[ i ];
  5066. getPointLightInfo( pointLight, geometryPosition, directLight );
  5067. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
  5068. pointLightShadow = pointLightShadows[ i ];
  5069. directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
  5070. #endif
  5071. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5072. }
  5073. #pragma unroll_loop_end
  5074. #endif
  5075. #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
  5076. SpotLight spotLight;
  5077. vec4 spotColor;
  5078. vec3 spotLightCoord;
  5079. bool inSpotLightMap;
  5080. #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
  5081. SpotLightShadow spotLightShadow;
  5082. #endif
  5083. #pragma unroll_loop_start
  5084. for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
  5085. spotLight = spotLights[ i ];
  5086. getSpotLightInfo( spotLight, geometryPosition, directLight );
  5087. #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5088. #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
  5089. #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5090. #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
  5091. #else
  5092. #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
  5093. #endif
  5094. #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
  5095. spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
  5096. inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
  5097. spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
  5098. directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
  5099. #endif
  5100. #undef SPOT_LIGHT_MAP_INDEX
  5101. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5102. spotLightShadow = spotLightShadows[ i ];
  5103. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5104. #endif
  5105. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5106. }
  5107. #pragma unroll_loop_end
  5108. #endif
  5109. #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
  5110. DirectionalLight directionalLight;
  5111. #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
  5112. DirectionalLightShadow directionalLightShadow;
  5113. #endif
  5114. #pragma unroll_loop_start
  5115. for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
  5116. directionalLight = directionalLights[ i ];
  5117. getDirectionalLightInfo( directionalLight, directLight );
  5118. #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
  5119. directionalLightShadow = directionalLightShadows[ i ];
  5120. directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5121. #endif
  5122. RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5123. }
  5124. #pragma unroll_loop_end
  5125. #endif
  5126. #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
  5127. RectAreaLight rectAreaLight;
  5128. #pragma unroll_loop_start
  5129. for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
  5130. rectAreaLight = rectAreaLights[ i ];
  5131. RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5132. }
  5133. #pragma unroll_loop_end
  5134. #endif
  5135. #if defined( RE_IndirectDiffuse )
  5136. vec3 iblIrradiance = vec3( 0.0 );
  5137. vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
  5138. #if defined( USE_LIGHT_PROBES )
  5139. irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
  5140. #endif
  5141. #if ( NUM_HEMI_LIGHTS > 0 )
  5142. #pragma unroll_loop_start
  5143. for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
  5144. irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
  5145. }
  5146. #pragma unroll_loop_end
  5147. #endif
  5148. #endif
  5149. #if defined( RE_IndirectSpecular )
  5150. vec3 radiance = vec3( 0.0 );
  5151. vec3 clearcoatRadiance = vec3( 0.0 );
  5152. #endif`,sNe=`#if defined( RE_IndirectDiffuse )
  5153. #ifdef USE_LIGHTMAP
  5154. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  5155. vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
  5156. irradiance += lightMapIrradiance;
  5157. #endif
  5158. #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
  5159. iblIrradiance += getIBLIrradiance( geometryNormal );
  5160. #endif
  5161. #endif
  5162. #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
  5163. #ifdef USE_ANISOTROPY
  5164. radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
  5165. #else
  5166. radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
  5167. #endif
  5168. #ifdef USE_CLEARCOAT
  5169. clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
  5170. #endif
  5171. #endif`,oNe=`#if defined( RE_IndirectDiffuse )
  5172. RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5173. #endif
  5174. #if defined( RE_IndirectSpecular )
  5175. RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
  5176. #endif`,lNe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5177. gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
  5178. #endif`,cNe=`#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )
  5179. uniform float logDepthBufFC;
  5180. varying float vFragDepth;
  5181. varying float vIsPerspective;
  5182. #endif`,uNe=`#ifdef USE_LOGDEPTHBUF
  5183. #ifdef USE_LOGDEPTHBUF_EXT
  5184. varying float vFragDepth;
  5185. varying float vIsPerspective;
  5186. #else
  5187. uniform float logDepthBufFC;
  5188. #endif
  5189. #endif`,dNe=`#ifdef USE_LOGDEPTHBUF
  5190. #ifdef USE_LOGDEPTHBUF_EXT
  5191. vFragDepth = 1.0 + gl_Position.w;
  5192. vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
  5193. #else
  5194. if ( isPerspectiveMatrix( projectionMatrix ) ) {
  5195. gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;
  5196. gl_Position.z *= gl_Position.w;
  5197. }
  5198. #endif
  5199. #endif`,hNe=`#ifdef USE_MAP
  5200. vec4 sampledDiffuseColor = texture2D( map, vMapUv );
  5201. #ifdef DECODE_VIDEO_TEXTURE
  5202. sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
  5203. #endif
  5204. diffuseColor *= sampledDiffuseColor;
  5205. #endif`,mNe=`#ifdef USE_MAP
  5206. uniform sampler2D map;
  5207. #endif`,fNe=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5208. #if defined( USE_POINTS_UV )
  5209. vec2 uv = vUv;
  5210. #else
  5211. vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
  5212. #endif
  5213. #endif
  5214. #ifdef USE_MAP
  5215. diffuseColor *= texture2D( map, uv );
  5216. #endif
  5217. #ifdef USE_ALPHAMAP
  5218. diffuseColor.a *= texture2D( alphaMap, uv ).g;
  5219. #endif`,pNe=`#if defined( USE_POINTS_UV )
  5220. varying vec2 vUv;
  5221. #else
  5222. #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
  5223. uniform mat3 uvTransform;
  5224. #endif
  5225. #endif
  5226. #ifdef USE_MAP
  5227. uniform sampler2D map;
  5228. #endif
  5229. #ifdef USE_ALPHAMAP
  5230. uniform sampler2D alphaMap;
  5231. #endif`,gNe=`float metalnessFactor = metalness;
  5232. #ifdef USE_METALNESSMAP
  5233. vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
  5234. metalnessFactor *= texelMetalness.b;
  5235. #endif`,bNe=`#ifdef USE_METALNESSMAP
  5236. uniform sampler2D metalnessMap;
  5237. #endif`,xNe=`#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )
  5238. vColor *= morphTargetBaseInfluence;
  5239. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5240. #if defined( USE_COLOR_ALPHA )
  5241. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
  5242. #elif defined( USE_COLOR )
  5243. if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
  5244. #endif
  5245. }
  5246. #endif`,yNe=`#ifdef USE_MORPHNORMALS
  5247. objectNormal *= morphTargetBaseInfluence;
  5248. #ifdef MORPHTARGETS_TEXTURE
  5249. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5250. if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
  5251. }
  5252. #else
  5253. objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];
  5254. objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];
  5255. objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];
  5256. objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];
  5257. #endif
  5258. #endif`,vNe=`#ifdef USE_MORPHTARGETS
  5259. uniform float morphTargetBaseInfluence;
  5260. #ifdef MORPHTARGETS_TEXTURE
  5261. uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
  5262. uniform sampler2DArray morphTargetsTexture;
  5263. uniform ivec2 morphTargetsTextureSize;
  5264. vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
  5265. int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
  5266. int y = texelIndex / morphTargetsTextureSize.x;
  5267. int x = texelIndex - y * morphTargetsTextureSize.x;
  5268. ivec3 morphUV = ivec3( x, y, morphTargetIndex );
  5269. return texelFetch( morphTargetsTexture, morphUV, 0 );
  5270. }
  5271. #else
  5272. #ifndef USE_MORPHNORMALS
  5273. uniform float morphTargetInfluences[ 8 ];
  5274. #else
  5275. uniform float morphTargetInfluences[ 4 ];
  5276. #endif
  5277. #endif
  5278. #endif`,wNe=`#ifdef USE_MORPHTARGETS
  5279. transformed *= morphTargetBaseInfluence;
  5280. #ifdef MORPHTARGETS_TEXTURE
  5281. for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
  5282. if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
  5283. }
  5284. #else
  5285. transformed += morphTarget0 * morphTargetInfluences[ 0 ];
  5286. transformed += morphTarget1 * morphTargetInfluences[ 1 ];
  5287. transformed += morphTarget2 * morphTargetInfluences[ 2 ];
  5288. transformed += morphTarget3 * morphTargetInfluences[ 3 ];
  5289. #ifndef USE_MORPHNORMALS
  5290. transformed += morphTarget4 * morphTargetInfluences[ 4 ];
  5291. transformed += morphTarget5 * morphTargetInfluences[ 5 ];
  5292. transformed += morphTarget6 * morphTargetInfluences[ 6 ];
  5293. transformed += morphTarget7 * morphTargetInfluences[ 7 ];
  5294. #endif
  5295. #endif
  5296. #endif`,SNe=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
  5297. #ifdef FLAT_SHADED
  5298. vec3 fdx = dFdx( vViewPosition );
  5299. vec3 fdy = dFdy( vViewPosition );
  5300. vec3 normal = normalize( cross( fdx, fdy ) );
  5301. #else
  5302. vec3 normal = normalize( vNormal );
  5303. #ifdef DOUBLE_SIDED
  5304. normal *= faceDirection;
  5305. #endif
  5306. #endif
  5307. #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
  5308. #ifdef USE_TANGENT
  5309. mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5310. #else
  5311. mat3 tbn = getTangentFrame( - vViewPosition, normal,
  5312. #if defined( USE_NORMALMAP )
  5313. vNormalMapUv
  5314. #elif defined( USE_CLEARCOAT_NORMALMAP )
  5315. vClearcoatNormalMapUv
  5316. #else
  5317. vUv
  5318. #endif
  5319. );
  5320. #endif
  5321. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5322. tbn[0] *= faceDirection;
  5323. tbn[1] *= faceDirection;
  5324. #endif
  5325. #endif
  5326. #ifdef USE_CLEARCOAT_NORMALMAP
  5327. #ifdef USE_TANGENT
  5328. mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
  5329. #else
  5330. mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
  5331. #endif
  5332. #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
  5333. tbn2[0] *= faceDirection;
  5334. tbn2[1] *= faceDirection;
  5335. #endif
  5336. #endif
  5337. vec3 nonPerturbedNormal = normal;`,_Ne=`#ifdef USE_NORMALMAP_OBJECTSPACE
  5338. normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5339. #ifdef FLIP_SIDED
  5340. normal = - normal;
  5341. #endif
  5342. #ifdef DOUBLE_SIDED
  5343. normal = normal * faceDirection;
  5344. #endif
  5345. normal = normalize( normalMatrix * normal );
  5346. #elif defined( USE_NORMALMAP_TANGENTSPACE )
  5347. vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
  5348. mapN.xy *= normalScale;
  5349. normal = normalize( tbn * mapN );
  5350. #elif defined( USE_BUMPMAP )
  5351. normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
  5352. #endif`,NNe=`#ifndef FLAT_SHADED
  5353. varying vec3 vNormal;
  5354. #ifdef USE_TANGENT
  5355. varying vec3 vTangent;
  5356. varying vec3 vBitangent;
  5357. #endif
  5358. #endif`,CNe=`#ifndef FLAT_SHADED
  5359. varying vec3 vNormal;
  5360. #ifdef USE_TANGENT
  5361. varying vec3 vTangent;
  5362. varying vec3 vBitangent;
  5363. #endif
  5364. #endif`,kNe=`#ifndef FLAT_SHADED
  5365. vNormal = normalize( transformedNormal );
  5366. #ifdef USE_TANGENT
  5367. vTangent = normalize( transformedTangent );
  5368. vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
  5369. #endif
  5370. #endif`,ANe=`#ifdef USE_NORMALMAP
  5371. uniform sampler2D normalMap;
  5372. uniform vec2 normalScale;
  5373. #endif
  5374. #ifdef USE_NORMALMAP_OBJECTSPACE
  5375. uniform mat3 normalMatrix;
  5376. #endif
  5377. #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
  5378. mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
  5379. vec3 q0 = dFdx( eye_pos.xyz );
  5380. vec3 q1 = dFdy( eye_pos.xyz );
  5381. vec2 st0 = dFdx( uv.st );
  5382. vec2 st1 = dFdy( uv.st );
  5383. vec3 N = surf_norm;
  5384. vec3 q1perp = cross( q1, N );
  5385. vec3 q0perp = cross( N, q0 );
  5386. vec3 T = q1perp * st0.x + q0perp * st1.x;
  5387. vec3 B = q1perp * st0.y + q0perp * st1.y;
  5388. float det = max( dot( T, T ), dot( B, B ) );
  5389. float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
  5390. return mat3( T * scale, B * scale, N );
  5391. }
  5392. #endif`,TNe=`#ifdef USE_CLEARCOAT
  5393. vec3 clearcoatNormal = nonPerturbedNormal;
  5394. #endif`,MNe=`#ifdef USE_CLEARCOAT_NORMALMAP
  5395. vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
  5396. clearcoatMapN.xy *= clearcoatNormalScale;
  5397. clearcoatNormal = normalize( tbn2 * clearcoatMapN );
  5398. #endif`,PNe=`#ifdef USE_CLEARCOATMAP
  5399. uniform sampler2D clearcoatMap;
  5400. #endif
  5401. #ifdef USE_CLEARCOAT_NORMALMAP
  5402. uniform sampler2D clearcoatNormalMap;
  5403. uniform vec2 clearcoatNormalScale;
  5404. #endif
  5405. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  5406. uniform sampler2D clearcoatRoughnessMap;
  5407. #endif`,ENe=`#ifdef USE_IRIDESCENCEMAP
  5408. uniform sampler2D iridescenceMap;
  5409. #endif
  5410. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  5411. uniform sampler2D iridescenceThicknessMap;
  5412. #endif`,jNe=`#ifdef OPAQUE
  5413. diffuseColor.a = 1.0;
  5414. #endif
  5415. #ifdef USE_TRANSMISSION
  5416. diffuseColor.a *= material.transmissionAlpha;
  5417. #endif
  5418. gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,DNe=`vec3 packNormalToRGB( const in vec3 normal ) {
  5419. return normalize( normal ) * 0.5 + 0.5;
  5420. }
  5421. vec3 unpackRGBToNormal( const in vec3 rgb ) {
  5422. return 2.0 * rgb.xyz - 1.0;
  5423. }
  5424. const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;
  5425. const vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );
  5426. const vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );
  5427. const float ShiftRight8 = 1. / 256.;
  5428. vec4 packDepthToRGBA( const in float v ) {
  5429. vec4 r = vec4( fract( v * PackFactors ), v );
  5430. r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;
  5431. }
  5432. float unpackRGBAToDepth( const in vec4 v ) {
  5433. return dot( v, UnpackFactors );
  5434. }
  5435. vec2 packDepthToRG( in highp float v ) {
  5436. return packDepthToRGBA( v ).yx;
  5437. }
  5438. float unpackRGToDepth( const in highp vec2 v ) {
  5439. return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );
  5440. }
  5441. vec4 pack2HalfToRGBA( vec2 v ) {
  5442. vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
  5443. return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
  5444. }
  5445. vec2 unpackRGBATo2Half( vec4 v ) {
  5446. return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
  5447. }
  5448. float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
  5449. return ( viewZ + near ) / ( near - far );
  5450. }
  5451. float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5452. return depth * ( near - far ) - near;
  5453. }
  5454. float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
  5455. return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
  5456. }
  5457. float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
  5458. return ( near * far ) / ( ( far - near ) * depth - far );
  5459. }`,RNe=`#ifdef PREMULTIPLIED_ALPHA
  5460. gl_FragColor.rgb *= gl_FragColor.a;
  5461. #endif`,FNe=`vec4 mvPosition = vec4( transformed, 1.0 );
  5462. #ifdef USE_BATCHING
  5463. mvPosition = batchingMatrix * mvPosition;
  5464. #endif
  5465. #ifdef USE_INSTANCING
  5466. mvPosition = instanceMatrix * mvPosition;
  5467. #endif
  5468. mvPosition = modelViewMatrix * mvPosition;
  5469. gl_Position = projectionMatrix * mvPosition;`,LNe=`#ifdef DITHERING
  5470. gl_FragColor.rgb = dithering( gl_FragColor.rgb );
  5471. #endif`,ONe=`#ifdef DITHERING
  5472. vec3 dithering( vec3 color ) {
  5473. float grid_position = rand( gl_FragCoord.xy );
  5474. vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
  5475. dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
  5476. return color + dither_shift_RGB;
  5477. }
  5478. #endif`,INe=`float roughnessFactor = roughness;
  5479. #ifdef USE_ROUGHNESSMAP
  5480. vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
  5481. roughnessFactor *= texelRoughness.g;
  5482. #endif`,zNe=`#ifdef USE_ROUGHNESSMAP
  5483. uniform sampler2D roughnessMap;
  5484. #endif`,UNe=`#if NUM_SPOT_LIGHT_COORDS > 0
  5485. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5486. #endif
  5487. #if NUM_SPOT_LIGHT_MAPS > 0
  5488. uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
  5489. #endif
  5490. #ifdef USE_SHADOWMAP
  5491. #if NUM_DIR_LIGHT_SHADOWS > 0
  5492. uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
  5493. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5494. struct DirectionalLightShadow {
  5495. float shadowBias;
  5496. float shadowNormalBias;
  5497. float shadowRadius;
  5498. vec2 shadowMapSize;
  5499. };
  5500. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5501. #endif
  5502. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5503. uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
  5504. struct SpotLightShadow {
  5505. float shadowBias;
  5506. float shadowNormalBias;
  5507. float shadowRadius;
  5508. vec2 shadowMapSize;
  5509. };
  5510. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5511. #endif
  5512. #if NUM_POINT_LIGHT_SHADOWS > 0
  5513. uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
  5514. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5515. struct PointLightShadow {
  5516. float shadowBias;
  5517. float shadowNormalBias;
  5518. float shadowRadius;
  5519. vec2 shadowMapSize;
  5520. float shadowCameraNear;
  5521. float shadowCameraFar;
  5522. };
  5523. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5524. #endif
  5525. float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
  5526. return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
  5527. }
  5528. vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
  5529. return unpackRGBATo2Half( texture2D( shadow, uv ) );
  5530. }
  5531. float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
  5532. float occlusion = 1.0;
  5533. vec2 distribution = texture2DDistribution( shadow, uv );
  5534. float hard_shadow = step( compare , distribution.x );
  5535. if (hard_shadow != 1.0 ) {
  5536. float distance = compare - distribution.x ;
  5537. float variance = max( 0.00000, distribution.y * distribution.y );
  5538. float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
  5539. }
  5540. return occlusion;
  5541. }
  5542. float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
  5543. float shadow = 1.0;
  5544. shadowCoord.xyz /= shadowCoord.w;
  5545. shadowCoord.z += shadowBias;
  5546. bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
  5547. bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
  5548. if ( frustumTest ) {
  5549. #if defined( SHADOWMAP_TYPE_PCF )
  5550. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5551. float dx0 = - texelSize.x * shadowRadius;
  5552. float dy0 = - texelSize.y * shadowRadius;
  5553. float dx1 = + texelSize.x * shadowRadius;
  5554. float dy1 = + texelSize.y * shadowRadius;
  5555. float dx2 = dx0 / 2.0;
  5556. float dy2 = dy0 / 2.0;
  5557. float dx3 = dx1 / 2.0;
  5558. float dy3 = dy1 / 2.0;
  5559. shadow = (
  5560. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
  5561. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
  5562. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
  5563. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
  5564. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
  5565. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
  5566. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
  5567. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
  5568. texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
  5569. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
  5570. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
  5571. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
  5572. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
  5573. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
  5574. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
  5575. texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
  5576. texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
  5577. ) * ( 1.0 / 17.0 );
  5578. #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
  5579. vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
  5580. float dx = texelSize.x;
  5581. float dy = texelSize.y;
  5582. vec2 uv = shadowCoord.xy;
  5583. vec2 f = fract( uv * shadowMapSize + 0.5 );
  5584. uv -= f * texelSize;
  5585. shadow = (
  5586. texture2DCompare( shadowMap, uv, shadowCoord.z ) +
  5587. texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
  5588. texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
  5589. texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
  5590. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
  5591. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
  5592. f.x ) +
  5593. mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
  5594. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
  5595. f.x ) +
  5596. mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
  5597. texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
  5598. f.y ) +
  5599. mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
  5600. texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
  5601. f.y ) +
  5602. mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
  5603. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
  5604. f.x ),
  5605. mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
  5606. texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
  5607. f.x ),
  5608. f.y )
  5609. ) * ( 1.0 / 9.0 );
  5610. #elif defined( SHADOWMAP_TYPE_VSM )
  5611. shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
  5612. #else
  5613. shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
  5614. #endif
  5615. }
  5616. return shadow;
  5617. }
  5618. vec2 cubeToUV( vec3 v, float texelSizeY ) {
  5619. vec3 absV = abs( v );
  5620. float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
  5621. absV *= scaleToCube;
  5622. v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
  5623. vec2 planar = v.xy;
  5624. float almostATexel = 1.5 * texelSizeY;
  5625. float almostOne = 1.0 - almostATexel;
  5626. if ( absV.z >= almostOne ) {
  5627. if ( v.z > 0.0 )
  5628. planar.x = 4.0 - v.x;
  5629. } else if ( absV.x >= almostOne ) {
  5630. float signX = sign( v.x );
  5631. planar.x = v.z * signX + 2.0 * signX;
  5632. } else if ( absV.y >= almostOne ) {
  5633. float signY = sign( v.y );
  5634. planar.x = v.x + 2.0 * signY + 2.0;
  5635. planar.y = v.z * signY - 2.0;
  5636. }
  5637. return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
  5638. }
  5639. float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
  5640. vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
  5641. vec3 lightToPosition = shadowCoord.xyz;
  5642. float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
  5643. vec3 bd3D = normalize( lightToPosition );
  5644. #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
  5645. vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
  5646. return (
  5647. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
  5648. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
  5649. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
  5650. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
  5651. texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
  5652. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
  5653. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
  5654. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
  5655. texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
  5656. ) * ( 1.0 / 9.0 );
  5657. #else
  5658. return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
  5659. #endif
  5660. }
  5661. #endif`,BNe=`#if NUM_SPOT_LIGHT_COORDS > 0
  5662. uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
  5663. varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
  5664. #endif
  5665. #ifdef USE_SHADOWMAP
  5666. #if NUM_DIR_LIGHT_SHADOWS > 0
  5667. uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
  5668. varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
  5669. struct DirectionalLightShadow {
  5670. float shadowBias;
  5671. float shadowNormalBias;
  5672. float shadowRadius;
  5673. vec2 shadowMapSize;
  5674. };
  5675. uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
  5676. #endif
  5677. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5678. struct SpotLightShadow {
  5679. float shadowBias;
  5680. float shadowNormalBias;
  5681. float shadowRadius;
  5682. vec2 shadowMapSize;
  5683. };
  5684. uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
  5685. #endif
  5686. #if NUM_POINT_LIGHT_SHADOWS > 0
  5687. uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
  5688. varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
  5689. struct PointLightShadow {
  5690. float shadowBias;
  5691. float shadowNormalBias;
  5692. float shadowRadius;
  5693. vec2 shadowMapSize;
  5694. float shadowCameraNear;
  5695. float shadowCameraFar;
  5696. };
  5697. uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
  5698. #endif
  5699. #endif`,HNe=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
  5700. vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
  5701. vec4 shadowWorldPosition;
  5702. #endif
  5703. #if defined( USE_SHADOWMAP )
  5704. #if NUM_DIR_LIGHT_SHADOWS > 0
  5705. #pragma unroll_loop_start
  5706. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5707. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
  5708. vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
  5709. }
  5710. #pragma unroll_loop_end
  5711. #endif
  5712. #if NUM_POINT_LIGHT_SHADOWS > 0
  5713. #pragma unroll_loop_start
  5714. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5715. shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
  5716. vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
  5717. }
  5718. #pragma unroll_loop_end
  5719. #endif
  5720. #endif
  5721. #if NUM_SPOT_LIGHT_COORDS > 0
  5722. #pragma unroll_loop_start
  5723. for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
  5724. shadowWorldPosition = worldPosition;
  5725. #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
  5726. shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
  5727. #endif
  5728. vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
  5729. }
  5730. #pragma unroll_loop_end
  5731. #endif`,$Ne=`float getShadowMask() {
  5732. float shadow = 1.0;
  5733. #ifdef USE_SHADOWMAP
  5734. #if NUM_DIR_LIGHT_SHADOWS > 0
  5735. DirectionalLightShadow directionalLight;
  5736. #pragma unroll_loop_start
  5737. for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
  5738. directionalLight = directionalLightShadows[ i ];
  5739. shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
  5740. }
  5741. #pragma unroll_loop_end
  5742. #endif
  5743. #if NUM_SPOT_LIGHT_SHADOWS > 0
  5744. SpotLightShadow spotLight;
  5745. #pragma unroll_loop_start
  5746. for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
  5747. spotLight = spotLightShadows[ i ];
  5748. shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
  5749. }
  5750. #pragma unroll_loop_end
  5751. #endif
  5752. #if NUM_POINT_LIGHT_SHADOWS > 0
  5753. PointLightShadow pointLight;
  5754. #pragma unroll_loop_start
  5755. for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
  5756. pointLight = pointLightShadows[ i ];
  5757. shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
  5758. }
  5759. #pragma unroll_loop_end
  5760. #endif
  5761. #endif
  5762. return shadow;
  5763. }`,VNe=`#ifdef USE_SKINNING
  5764. mat4 boneMatX = getBoneMatrix( skinIndex.x );
  5765. mat4 boneMatY = getBoneMatrix( skinIndex.y );
  5766. mat4 boneMatZ = getBoneMatrix( skinIndex.z );
  5767. mat4 boneMatW = getBoneMatrix( skinIndex.w );
  5768. #endif`,qNe=`#ifdef USE_SKINNING
  5769. uniform mat4 bindMatrix;
  5770. uniform mat4 bindMatrixInverse;
  5771. uniform highp sampler2D boneTexture;
  5772. mat4 getBoneMatrix( const in float i ) {
  5773. int size = textureSize( boneTexture, 0 ).x;
  5774. int j = int( i ) * 4;
  5775. int x = j % size;
  5776. int y = j / size;
  5777. vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
  5778. vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
  5779. vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
  5780. vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
  5781. return mat4( v1, v2, v3, v4 );
  5782. }
  5783. #endif`,GNe=`#ifdef USE_SKINNING
  5784. vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
  5785. vec4 skinned = vec4( 0.0 );
  5786. skinned += boneMatX * skinVertex * skinWeight.x;
  5787. skinned += boneMatY * skinVertex * skinWeight.y;
  5788. skinned += boneMatZ * skinVertex * skinWeight.z;
  5789. skinned += boneMatW * skinVertex * skinWeight.w;
  5790. transformed = ( bindMatrixInverse * skinned ).xyz;
  5791. #endif`,WNe=`#ifdef USE_SKINNING
  5792. mat4 skinMatrix = mat4( 0.0 );
  5793. skinMatrix += skinWeight.x * boneMatX;
  5794. skinMatrix += skinWeight.y * boneMatY;
  5795. skinMatrix += skinWeight.z * boneMatZ;
  5796. skinMatrix += skinWeight.w * boneMatW;
  5797. skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
  5798. objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  5799. #ifdef USE_TANGENT
  5800. objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  5801. #endif
  5802. #endif`,KNe=`float specularStrength;
  5803. #ifdef USE_SPECULARMAP
  5804. vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
  5805. specularStrength = texelSpecular.r;
  5806. #else
  5807. specularStrength = 1.0;
  5808. #endif`,XNe=`#ifdef USE_SPECULARMAP
  5809. uniform sampler2D specularMap;
  5810. #endif`,YNe=`#if defined( TONE_MAPPING )
  5811. gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
  5812. #endif`,QNe=`#ifndef saturate
  5813. #define saturate( a ) clamp( a, 0.0, 1.0 )
  5814. #endif
  5815. uniform float toneMappingExposure;
  5816. vec3 LinearToneMapping( vec3 color ) {
  5817. return saturate( toneMappingExposure * color );
  5818. }
  5819. vec3 ReinhardToneMapping( vec3 color ) {
  5820. color *= toneMappingExposure;
  5821. return saturate( color / ( vec3( 1.0 ) + color ) );
  5822. }
  5823. vec3 OptimizedCineonToneMapping( vec3 color ) {
  5824. color *= toneMappingExposure;
  5825. color = max( vec3( 0.0 ), color - 0.004 );
  5826. return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
  5827. }
  5828. vec3 RRTAndODTFit( vec3 v ) {
  5829. vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
  5830. vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
  5831. return a / b;
  5832. }
  5833. vec3 ACESFilmicToneMapping( vec3 color ) {
  5834. const mat3 ACESInputMat = mat3(
  5835. vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
  5836. vec3( 0.04823, 0.01566, 0.83777 )
  5837. );
  5838. const mat3 ACESOutputMat = mat3(
  5839. vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
  5840. vec3( -0.07367, -0.00605, 1.07602 )
  5841. );
  5842. color *= toneMappingExposure / 0.6;
  5843. color = ACESInputMat * color;
  5844. color = RRTAndODTFit( color );
  5845. color = ACESOutputMat * color;
  5846. return saturate( color );
  5847. }
  5848. vec3 CustomToneMapping( vec3 color ) { return color; }`,ZNe=`#ifdef USE_TRANSMISSION
  5849. material.transmission = transmission;
  5850. material.transmissionAlpha = 1.0;
  5851. material.thickness = thickness;
  5852. material.attenuationDistance = attenuationDistance;
  5853. material.attenuationColor = attenuationColor;
  5854. #ifdef USE_TRANSMISSIONMAP
  5855. material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
  5856. #endif
  5857. #ifdef USE_THICKNESSMAP
  5858. material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
  5859. #endif
  5860. vec3 pos = vWorldPosition;
  5861. vec3 v = normalize( cameraPosition - pos );
  5862. vec3 n = inverseTransformDirection( normal, viewMatrix );
  5863. vec4 transmitted = getIBLVolumeRefraction(
  5864. n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
  5865. pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,
  5866. material.attenuationColor, material.attenuationDistance );
  5867. material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
  5868. totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
  5869. #endif`,JNe=`#ifdef USE_TRANSMISSION
  5870. uniform float transmission;
  5871. uniform float thickness;
  5872. uniform float attenuationDistance;
  5873. uniform vec3 attenuationColor;
  5874. #ifdef USE_TRANSMISSIONMAP
  5875. uniform sampler2D transmissionMap;
  5876. #endif
  5877. #ifdef USE_THICKNESSMAP
  5878. uniform sampler2D thicknessMap;
  5879. #endif
  5880. uniform vec2 transmissionSamplerSize;
  5881. uniform sampler2D transmissionSamplerMap;
  5882. uniform mat4 modelMatrix;
  5883. uniform mat4 projectionMatrix;
  5884. varying vec3 vWorldPosition;
  5885. float w0( float a ) {
  5886. return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
  5887. }
  5888. float w1( float a ) {
  5889. return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
  5890. }
  5891. float w2( float a ){
  5892. return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
  5893. }
  5894. float w3( float a ) {
  5895. return ( 1.0 / 6.0 ) * ( a * a * a );
  5896. }
  5897. float g0( float a ) {
  5898. return w0( a ) + w1( a );
  5899. }
  5900. float g1( float a ) {
  5901. return w2( a ) + w3( a );
  5902. }
  5903. float h0( float a ) {
  5904. return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
  5905. }
  5906. float h1( float a ) {
  5907. return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
  5908. }
  5909. vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
  5910. uv = uv * texelSize.zw + 0.5;
  5911. vec2 iuv = floor( uv );
  5912. vec2 fuv = fract( uv );
  5913. float g0x = g0( fuv.x );
  5914. float g1x = g1( fuv.x );
  5915. float h0x = h0( fuv.x );
  5916. float h1x = h1( fuv.x );
  5917. float h0y = h0( fuv.y );
  5918. float h1y = h1( fuv.y );
  5919. vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5920. vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
  5921. vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5922. vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
  5923. return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
  5924. g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
  5925. }
  5926. vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
  5927. vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
  5928. vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
  5929. vec2 fLodSizeInv = 1.0 / fLodSize;
  5930. vec2 cLodSizeInv = 1.0 / cLodSize;
  5931. vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
  5932. vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
  5933. return mix( fSample, cSample, fract( lod ) );
  5934. }
  5935. vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
  5936. vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
  5937. vec3 modelScale;
  5938. modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
  5939. modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
  5940. modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
  5941. return normalize( refractionVector ) * thickness * modelScale;
  5942. }
  5943. float applyIorToRoughness( const in float roughness, const in float ior ) {
  5944. return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
  5945. }
  5946. vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
  5947. float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
  5948. return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
  5949. }
  5950. vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
  5951. if ( isinf( attenuationDistance ) ) {
  5952. return vec3( 1.0 );
  5953. } else {
  5954. vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
  5955. vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
  5956. }
  5957. }
  5958. vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
  5959. const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
  5960. const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,
  5961. const in vec3 attenuationColor, const in float attenuationDistance ) {
  5962. vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  5963. vec3 refractedRayExit = position + transmissionRay;
  5964. vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
  5965. vec2 refractionCoords = ndcPos.xy / ndcPos.w;
  5966. refractionCoords += 1.0;
  5967. refractionCoords /= 2.0;
  5968. vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  5969. vec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
  5970. vec3 attenuatedColor = transmittance * transmittedLight.rgb;
  5971. vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
  5972. float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
  5973. return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
  5974. }
  5975. #endif`,eCe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  5976. varying vec2 vUv;
  5977. #endif
  5978. #ifdef USE_MAP
  5979. varying vec2 vMapUv;
  5980. #endif
  5981. #ifdef USE_ALPHAMAP
  5982. varying vec2 vAlphaMapUv;
  5983. #endif
  5984. #ifdef USE_LIGHTMAP
  5985. varying vec2 vLightMapUv;
  5986. #endif
  5987. #ifdef USE_AOMAP
  5988. varying vec2 vAoMapUv;
  5989. #endif
  5990. #ifdef USE_BUMPMAP
  5991. varying vec2 vBumpMapUv;
  5992. #endif
  5993. #ifdef USE_NORMALMAP
  5994. varying vec2 vNormalMapUv;
  5995. #endif
  5996. #ifdef USE_EMISSIVEMAP
  5997. varying vec2 vEmissiveMapUv;
  5998. #endif
  5999. #ifdef USE_METALNESSMAP
  6000. varying vec2 vMetalnessMapUv;
  6001. #endif
  6002. #ifdef USE_ROUGHNESSMAP
  6003. varying vec2 vRoughnessMapUv;
  6004. #endif
  6005. #ifdef USE_ANISOTROPYMAP
  6006. varying vec2 vAnisotropyMapUv;
  6007. #endif
  6008. #ifdef USE_CLEARCOATMAP
  6009. varying vec2 vClearcoatMapUv;
  6010. #endif
  6011. #ifdef USE_CLEARCOAT_NORMALMAP
  6012. varying vec2 vClearcoatNormalMapUv;
  6013. #endif
  6014. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6015. varying vec2 vClearcoatRoughnessMapUv;
  6016. #endif
  6017. #ifdef USE_IRIDESCENCEMAP
  6018. varying vec2 vIridescenceMapUv;
  6019. #endif
  6020. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6021. varying vec2 vIridescenceThicknessMapUv;
  6022. #endif
  6023. #ifdef USE_SHEEN_COLORMAP
  6024. varying vec2 vSheenColorMapUv;
  6025. #endif
  6026. #ifdef USE_SHEEN_ROUGHNESSMAP
  6027. varying vec2 vSheenRoughnessMapUv;
  6028. #endif
  6029. #ifdef USE_SPECULARMAP
  6030. varying vec2 vSpecularMapUv;
  6031. #endif
  6032. #ifdef USE_SPECULAR_COLORMAP
  6033. varying vec2 vSpecularColorMapUv;
  6034. #endif
  6035. #ifdef USE_SPECULAR_INTENSITYMAP
  6036. varying vec2 vSpecularIntensityMapUv;
  6037. #endif
  6038. #ifdef USE_TRANSMISSIONMAP
  6039. uniform mat3 transmissionMapTransform;
  6040. varying vec2 vTransmissionMapUv;
  6041. #endif
  6042. #ifdef USE_THICKNESSMAP
  6043. uniform mat3 thicknessMapTransform;
  6044. varying vec2 vThicknessMapUv;
  6045. #endif`,tCe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6046. varying vec2 vUv;
  6047. #endif
  6048. #ifdef USE_MAP
  6049. uniform mat3 mapTransform;
  6050. varying vec2 vMapUv;
  6051. #endif
  6052. #ifdef USE_ALPHAMAP
  6053. uniform mat3 alphaMapTransform;
  6054. varying vec2 vAlphaMapUv;
  6055. #endif
  6056. #ifdef USE_LIGHTMAP
  6057. uniform mat3 lightMapTransform;
  6058. varying vec2 vLightMapUv;
  6059. #endif
  6060. #ifdef USE_AOMAP
  6061. uniform mat3 aoMapTransform;
  6062. varying vec2 vAoMapUv;
  6063. #endif
  6064. #ifdef USE_BUMPMAP
  6065. uniform mat3 bumpMapTransform;
  6066. varying vec2 vBumpMapUv;
  6067. #endif
  6068. #ifdef USE_NORMALMAP
  6069. uniform mat3 normalMapTransform;
  6070. varying vec2 vNormalMapUv;
  6071. #endif
  6072. #ifdef USE_DISPLACEMENTMAP
  6073. uniform mat3 displacementMapTransform;
  6074. varying vec2 vDisplacementMapUv;
  6075. #endif
  6076. #ifdef USE_EMISSIVEMAP
  6077. uniform mat3 emissiveMapTransform;
  6078. varying vec2 vEmissiveMapUv;
  6079. #endif
  6080. #ifdef USE_METALNESSMAP
  6081. uniform mat3 metalnessMapTransform;
  6082. varying vec2 vMetalnessMapUv;
  6083. #endif
  6084. #ifdef USE_ROUGHNESSMAP
  6085. uniform mat3 roughnessMapTransform;
  6086. varying vec2 vRoughnessMapUv;
  6087. #endif
  6088. #ifdef USE_ANISOTROPYMAP
  6089. uniform mat3 anisotropyMapTransform;
  6090. varying vec2 vAnisotropyMapUv;
  6091. #endif
  6092. #ifdef USE_CLEARCOATMAP
  6093. uniform mat3 clearcoatMapTransform;
  6094. varying vec2 vClearcoatMapUv;
  6095. #endif
  6096. #ifdef USE_CLEARCOAT_NORMALMAP
  6097. uniform mat3 clearcoatNormalMapTransform;
  6098. varying vec2 vClearcoatNormalMapUv;
  6099. #endif
  6100. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6101. uniform mat3 clearcoatRoughnessMapTransform;
  6102. varying vec2 vClearcoatRoughnessMapUv;
  6103. #endif
  6104. #ifdef USE_SHEEN_COLORMAP
  6105. uniform mat3 sheenColorMapTransform;
  6106. varying vec2 vSheenColorMapUv;
  6107. #endif
  6108. #ifdef USE_SHEEN_ROUGHNESSMAP
  6109. uniform mat3 sheenRoughnessMapTransform;
  6110. varying vec2 vSheenRoughnessMapUv;
  6111. #endif
  6112. #ifdef USE_IRIDESCENCEMAP
  6113. uniform mat3 iridescenceMapTransform;
  6114. varying vec2 vIridescenceMapUv;
  6115. #endif
  6116. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6117. uniform mat3 iridescenceThicknessMapTransform;
  6118. varying vec2 vIridescenceThicknessMapUv;
  6119. #endif
  6120. #ifdef USE_SPECULARMAP
  6121. uniform mat3 specularMapTransform;
  6122. varying vec2 vSpecularMapUv;
  6123. #endif
  6124. #ifdef USE_SPECULAR_COLORMAP
  6125. uniform mat3 specularColorMapTransform;
  6126. varying vec2 vSpecularColorMapUv;
  6127. #endif
  6128. #ifdef USE_SPECULAR_INTENSITYMAP
  6129. uniform mat3 specularIntensityMapTransform;
  6130. varying vec2 vSpecularIntensityMapUv;
  6131. #endif
  6132. #ifdef USE_TRANSMISSIONMAP
  6133. uniform mat3 transmissionMapTransform;
  6134. varying vec2 vTransmissionMapUv;
  6135. #endif
  6136. #ifdef USE_THICKNESSMAP
  6137. uniform mat3 thicknessMapTransform;
  6138. varying vec2 vThicknessMapUv;
  6139. #endif`,nCe=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
  6140. vUv = vec3( uv, 1 ).xy;
  6141. #endif
  6142. #ifdef USE_MAP
  6143. vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
  6144. #endif
  6145. #ifdef USE_ALPHAMAP
  6146. vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
  6147. #endif
  6148. #ifdef USE_LIGHTMAP
  6149. vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
  6150. #endif
  6151. #ifdef USE_AOMAP
  6152. vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
  6153. #endif
  6154. #ifdef USE_BUMPMAP
  6155. vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
  6156. #endif
  6157. #ifdef USE_NORMALMAP
  6158. vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
  6159. #endif
  6160. #ifdef USE_DISPLACEMENTMAP
  6161. vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
  6162. #endif
  6163. #ifdef USE_EMISSIVEMAP
  6164. vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
  6165. #endif
  6166. #ifdef USE_METALNESSMAP
  6167. vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
  6168. #endif
  6169. #ifdef USE_ROUGHNESSMAP
  6170. vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
  6171. #endif
  6172. #ifdef USE_ANISOTROPYMAP
  6173. vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
  6174. #endif
  6175. #ifdef USE_CLEARCOATMAP
  6176. vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
  6177. #endif
  6178. #ifdef USE_CLEARCOAT_NORMALMAP
  6179. vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
  6180. #endif
  6181. #ifdef USE_CLEARCOAT_ROUGHNESSMAP
  6182. vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
  6183. #endif
  6184. #ifdef USE_IRIDESCENCEMAP
  6185. vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
  6186. #endif
  6187. #ifdef USE_IRIDESCENCE_THICKNESSMAP
  6188. vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
  6189. #endif
  6190. #ifdef USE_SHEEN_COLORMAP
  6191. vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
  6192. #endif
  6193. #ifdef USE_SHEEN_ROUGHNESSMAP
  6194. vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
  6195. #endif
  6196. #ifdef USE_SPECULARMAP
  6197. vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
  6198. #endif
  6199. #ifdef USE_SPECULAR_COLORMAP
  6200. vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
  6201. #endif
  6202. #ifdef USE_SPECULAR_INTENSITYMAP
  6203. vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
  6204. #endif
  6205. #ifdef USE_TRANSMISSIONMAP
  6206. vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
  6207. #endif
  6208. #ifdef USE_THICKNESSMAP
  6209. vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
  6210. #endif`,rCe=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
  6211. vec4 worldPosition = vec4( transformed, 1.0 );
  6212. #ifdef USE_BATCHING
  6213. worldPosition = batchingMatrix * worldPosition;
  6214. #endif
  6215. #ifdef USE_INSTANCING
  6216. worldPosition = instanceMatrix * worldPosition;
  6217. #endif
  6218. worldPosition = modelMatrix * worldPosition;
  6219. #endif`;const aCe=`varying vec2 vUv;
  6220. uniform mat3 uvTransform;
  6221. void main() {
  6222. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  6223. gl_Position = vec4( position.xy, 1.0, 1.0 );
  6224. }`,iCe=`uniform sampler2D t2D;
  6225. uniform float backgroundIntensity;
  6226. varying vec2 vUv;
  6227. void main() {
  6228. vec4 texColor = texture2D( t2D, vUv );
  6229. #ifdef DECODE_VIDEO_TEXTURE
  6230. texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
  6231. #endif
  6232. texColor.rgb *= backgroundIntensity;
  6233. gl_FragColor = texColor;
  6234. #include <tonemapping_fragment>
  6235. #include <colorspace_fragment>
  6236. }`,sCe=`varying vec3 vWorldDirection;
  6237. #include <common>
  6238. void main() {
  6239. vWorldDirection = transformDirection( position, modelMatrix );
  6240. #include <begin_vertex>
  6241. #include <project_vertex>
  6242. gl_Position.z = gl_Position.w;
  6243. }`,oCe=`#ifdef ENVMAP_TYPE_CUBE
  6244. uniform samplerCube envMap;
  6245. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6246. uniform sampler2D envMap;
  6247. #endif
  6248. uniform float flipEnvMap;
  6249. uniform float backgroundBlurriness;
  6250. uniform float backgroundIntensity;
  6251. varying vec3 vWorldDirection;
  6252. #include <cube_uv_reflection_fragment>
  6253. void main() {
  6254. #ifdef ENVMAP_TYPE_CUBE
  6255. vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
  6256. #elif defined( ENVMAP_TYPE_CUBE_UV )
  6257. vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );
  6258. #else
  6259. vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  6260. #endif
  6261. texColor.rgb *= backgroundIntensity;
  6262. gl_FragColor = texColor;
  6263. #include <tonemapping_fragment>
  6264. #include <colorspace_fragment>
  6265. }`,lCe=`varying vec3 vWorldDirection;
  6266. #include <common>
  6267. void main() {
  6268. vWorldDirection = transformDirection( position, modelMatrix );
  6269. #include <begin_vertex>
  6270. #include <project_vertex>
  6271. gl_Position.z = gl_Position.w;
  6272. }`,cCe=`uniform samplerCube tCube;
  6273. uniform float tFlip;
  6274. uniform float opacity;
  6275. varying vec3 vWorldDirection;
  6276. void main() {
  6277. vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
  6278. gl_FragColor = texColor;
  6279. gl_FragColor.a *= opacity;
  6280. #include <tonemapping_fragment>
  6281. #include <colorspace_fragment>
  6282. }`,uCe=`#include <common>
  6283. #include <batching_pars_vertex>
  6284. #include <uv_pars_vertex>
  6285. #include <displacementmap_pars_vertex>
  6286. #include <morphtarget_pars_vertex>
  6287. #include <skinning_pars_vertex>
  6288. #include <logdepthbuf_pars_vertex>
  6289. #include <clipping_planes_pars_vertex>
  6290. varying vec2 vHighPrecisionZW;
  6291. void main() {
  6292. #include <uv_vertex>
  6293. #include <batching_vertex>
  6294. #include <skinbase_vertex>
  6295. #ifdef USE_DISPLACEMENTMAP
  6296. #include <beginnormal_vertex>
  6297. #include <morphnormal_vertex>
  6298. #include <skinnormal_vertex>
  6299. #endif
  6300. #include <begin_vertex>
  6301. #include <morphtarget_vertex>
  6302. #include <skinning_vertex>
  6303. #include <displacementmap_vertex>
  6304. #include <project_vertex>
  6305. #include <logdepthbuf_vertex>
  6306. #include <clipping_planes_vertex>
  6307. vHighPrecisionZW = gl_Position.zw;
  6308. }`,dCe=`#if DEPTH_PACKING == 3200
  6309. uniform float opacity;
  6310. #endif
  6311. #include <common>
  6312. #include <packing>
  6313. #include <uv_pars_fragment>
  6314. #include <map_pars_fragment>
  6315. #include <alphamap_pars_fragment>
  6316. #include <alphatest_pars_fragment>
  6317. #include <alphahash_pars_fragment>
  6318. #include <logdepthbuf_pars_fragment>
  6319. #include <clipping_planes_pars_fragment>
  6320. varying vec2 vHighPrecisionZW;
  6321. void main() {
  6322. #include <clipping_planes_fragment>
  6323. vec4 diffuseColor = vec4( 1.0 );
  6324. #if DEPTH_PACKING == 3200
  6325. diffuseColor.a = opacity;
  6326. #endif
  6327. #include <map_fragment>
  6328. #include <alphamap_fragment>
  6329. #include <alphatest_fragment>
  6330. #include <alphahash_fragment>
  6331. #include <logdepthbuf_fragment>
  6332. float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
  6333. #if DEPTH_PACKING == 3200
  6334. gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
  6335. #elif DEPTH_PACKING == 3201
  6336. gl_FragColor = packDepthToRGBA( fragCoordZ );
  6337. #endif
  6338. }`,hCe=`#define DISTANCE
  6339. varying vec3 vWorldPosition;
  6340. #include <common>
  6341. #include <batching_pars_vertex>
  6342. #include <uv_pars_vertex>
  6343. #include <displacementmap_pars_vertex>
  6344. #include <morphtarget_pars_vertex>
  6345. #include <skinning_pars_vertex>
  6346. #include <clipping_planes_pars_vertex>
  6347. void main() {
  6348. #include <uv_vertex>
  6349. #include <batching_vertex>
  6350. #include <skinbase_vertex>
  6351. #ifdef USE_DISPLACEMENTMAP
  6352. #include <beginnormal_vertex>
  6353. #include <morphnormal_vertex>
  6354. #include <skinnormal_vertex>
  6355. #endif
  6356. #include <begin_vertex>
  6357. #include <morphtarget_vertex>
  6358. #include <skinning_vertex>
  6359. #include <displacementmap_vertex>
  6360. #include <project_vertex>
  6361. #include <worldpos_vertex>
  6362. #include <clipping_planes_vertex>
  6363. vWorldPosition = worldPosition.xyz;
  6364. }`,mCe=`#define DISTANCE
  6365. uniform vec3 referencePosition;
  6366. uniform float nearDistance;
  6367. uniform float farDistance;
  6368. varying vec3 vWorldPosition;
  6369. #include <common>
  6370. #include <packing>
  6371. #include <uv_pars_fragment>
  6372. #include <map_pars_fragment>
  6373. #include <alphamap_pars_fragment>
  6374. #include <alphatest_pars_fragment>
  6375. #include <alphahash_pars_fragment>
  6376. #include <clipping_planes_pars_fragment>
  6377. void main () {
  6378. #include <clipping_planes_fragment>
  6379. vec4 diffuseColor = vec4( 1.0 );
  6380. #include <map_fragment>
  6381. #include <alphamap_fragment>
  6382. #include <alphatest_fragment>
  6383. #include <alphahash_fragment>
  6384. float dist = length( vWorldPosition - referencePosition );
  6385. dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
  6386. dist = saturate( dist );
  6387. gl_FragColor = packDepthToRGBA( dist );
  6388. }`,fCe=`varying vec3 vWorldDirection;
  6389. #include <common>
  6390. void main() {
  6391. vWorldDirection = transformDirection( position, modelMatrix );
  6392. #include <begin_vertex>
  6393. #include <project_vertex>
  6394. }`,pCe=`uniform sampler2D tEquirect;
  6395. varying vec3 vWorldDirection;
  6396. #include <common>
  6397. void main() {
  6398. vec3 direction = normalize( vWorldDirection );
  6399. vec2 sampleUV = equirectUv( direction );
  6400. gl_FragColor = texture2D( tEquirect, sampleUV );
  6401. #include <tonemapping_fragment>
  6402. #include <colorspace_fragment>
  6403. }`,gCe=`uniform float scale;
  6404. attribute float lineDistance;
  6405. varying float vLineDistance;
  6406. #include <common>
  6407. #include <uv_pars_vertex>
  6408. #include <color_pars_vertex>
  6409. #include <fog_pars_vertex>
  6410. #include <morphtarget_pars_vertex>
  6411. #include <logdepthbuf_pars_vertex>
  6412. #include <clipping_planes_pars_vertex>
  6413. void main() {
  6414. vLineDistance = scale * lineDistance;
  6415. #include <uv_vertex>
  6416. #include <color_vertex>
  6417. #include <morphcolor_vertex>
  6418. #include <begin_vertex>
  6419. #include <morphtarget_vertex>
  6420. #include <project_vertex>
  6421. #include <logdepthbuf_vertex>
  6422. #include <clipping_planes_vertex>
  6423. #include <fog_vertex>
  6424. }`,bCe=`uniform vec3 diffuse;
  6425. uniform float opacity;
  6426. uniform float dashSize;
  6427. uniform float totalSize;
  6428. varying float vLineDistance;
  6429. #include <common>
  6430. #include <color_pars_fragment>
  6431. #include <uv_pars_fragment>
  6432. #include <map_pars_fragment>
  6433. #include <fog_pars_fragment>
  6434. #include <logdepthbuf_pars_fragment>
  6435. #include <clipping_planes_pars_fragment>
  6436. void main() {
  6437. #include <clipping_planes_fragment>
  6438. if ( mod( vLineDistance, totalSize ) > dashSize ) {
  6439. discard;
  6440. }
  6441. vec3 outgoingLight = vec3( 0.0 );
  6442. vec4 diffuseColor = vec4( diffuse, opacity );
  6443. #include <logdepthbuf_fragment>
  6444. #include <map_fragment>
  6445. #include <color_fragment>
  6446. outgoingLight = diffuseColor.rgb;
  6447. #include <opaque_fragment>
  6448. #include <tonemapping_fragment>
  6449. #include <colorspace_fragment>
  6450. #include <fog_fragment>
  6451. #include <premultiplied_alpha_fragment>
  6452. }`,xCe=`#include <common>
  6453. #include <batching_pars_vertex>
  6454. #include <uv_pars_vertex>
  6455. #include <envmap_pars_vertex>
  6456. #include <color_pars_vertex>
  6457. #include <fog_pars_vertex>
  6458. #include <morphtarget_pars_vertex>
  6459. #include <skinning_pars_vertex>
  6460. #include <logdepthbuf_pars_vertex>
  6461. #include <clipping_planes_pars_vertex>
  6462. void main() {
  6463. #include <uv_vertex>
  6464. #include <color_vertex>
  6465. #include <morphcolor_vertex>
  6466. #include <batching_vertex>
  6467. #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
  6468. #include <beginnormal_vertex>
  6469. #include <morphnormal_vertex>
  6470. #include <skinbase_vertex>
  6471. #include <skinnormal_vertex>
  6472. #include <defaultnormal_vertex>
  6473. #endif
  6474. #include <begin_vertex>
  6475. #include <morphtarget_vertex>
  6476. #include <skinning_vertex>
  6477. #include <project_vertex>
  6478. #include <logdepthbuf_vertex>
  6479. #include <clipping_planes_vertex>
  6480. #include <worldpos_vertex>
  6481. #include <envmap_vertex>
  6482. #include <fog_vertex>
  6483. }`,yCe=`uniform vec3 diffuse;
  6484. uniform float opacity;
  6485. #ifndef FLAT_SHADED
  6486. varying vec3 vNormal;
  6487. #endif
  6488. #include <common>
  6489. #include <dithering_pars_fragment>
  6490. #include <color_pars_fragment>
  6491. #include <uv_pars_fragment>
  6492. #include <map_pars_fragment>
  6493. #include <alphamap_pars_fragment>
  6494. #include <alphatest_pars_fragment>
  6495. #include <alphahash_pars_fragment>
  6496. #include <aomap_pars_fragment>
  6497. #include <lightmap_pars_fragment>
  6498. #include <envmap_common_pars_fragment>
  6499. #include <envmap_pars_fragment>
  6500. #include <fog_pars_fragment>
  6501. #include <specularmap_pars_fragment>
  6502. #include <logdepthbuf_pars_fragment>
  6503. #include <clipping_planes_pars_fragment>
  6504. void main() {
  6505. #include <clipping_planes_fragment>
  6506. vec4 diffuseColor = vec4( diffuse, opacity );
  6507. #include <logdepthbuf_fragment>
  6508. #include <map_fragment>
  6509. #include <color_fragment>
  6510. #include <alphamap_fragment>
  6511. #include <alphatest_fragment>
  6512. #include <alphahash_fragment>
  6513. #include <specularmap_fragment>
  6514. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6515. #ifdef USE_LIGHTMAP
  6516. vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
  6517. reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
  6518. #else
  6519. reflectedLight.indirectDiffuse += vec3( 1.0 );
  6520. #endif
  6521. #include <aomap_fragment>
  6522. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  6523. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  6524. #include <envmap_fragment>
  6525. #include <opaque_fragment>
  6526. #include <tonemapping_fragment>
  6527. #include <colorspace_fragment>
  6528. #include <fog_fragment>
  6529. #include <premultiplied_alpha_fragment>
  6530. #include <dithering_fragment>
  6531. }`,vCe=`#define LAMBERT
  6532. varying vec3 vViewPosition;
  6533. #include <common>
  6534. #include <batching_pars_vertex>
  6535. #include <uv_pars_vertex>
  6536. #include <displacementmap_pars_vertex>
  6537. #include <envmap_pars_vertex>
  6538. #include <color_pars_vertex>
  6539. #include <fog_pars_vertex>
  6540. #include <normal_pars_vertex>
  6541. #include <morphtarget_pars_vertex>
  6542. #include <skinning_pars_vertex>
  6543. #include <shadowmap_pars_vertex>
  6544. #include <logdepthbuf_pars_vertex>
  6545. #include <clipping_planes_pars_vertex>
  6546. void main() {
  6547. #include <uv_vertex>
  6548. #include <color_vertex>
  6549. #include <morphcolor_vertex>
  6550. #include <batching_vertex>
  6551. #include <beginnormal_vertex>
  6552. #include <morphnormal_vertex>
  6553. #include <skinbase_vertex>
  6554. #include <skinnormal_vertex>
  6555. #include <defaultnormal_vertex>
  6556. #include <normal_vertex>
  6557. #include <begin_vertex>
  6558. #include <morphtarget_vertex>
  6559. #include <skinning_vertex>
  6560. #include <displacementmap_vertex>
  6561. #include <project_vertex>
  6562. #include <logdepthbuf_vertex>
  6563. #include <clipping_planes_vertex>
  6564. vViewPosition = - mvPosition.xyz;
  6565. #include <worldpos_vertex>
  6566. #include <envmap_vertex>
  6567. #include <shadowmap_vertex>
  6568. #include <fog_vertex>
  6569. }`,wCe=`#define LAMBERT
  6570. uniform vec3 diffuse;
  6571. uniform vec3 emissive;
  6572. uniform float opacity;
  6573. #include <common>
  6574. #include <packing>
  6575. #include <dithering_pars_fragment>
  6576. #include <color_pars_fragment>
  6577. #include <uv_pars_fragment>
  6578. #include <map_pars_fragment>
  6579. #include <alphamap_pars_fragment>
  6580. #include <alphatest_pars_fragment>
  6581. #include <alphahash_pars_fragment>
  6582. #include <aomap_pars_fragment>
  6583. #include <lightmap_pars_fragment>
  6584. #include <emissivemap_pars_fragment>
  6585. #include <envmap_common_pars_fragment>
  6586. #include <envmap_pars_fragment>
  6587. #include <fog_pars_fragment>
  6588. #include <bsdfs>
  6589. #include <lights_pars_begin>
  6590. #include <normal_pars_fragment>
  6591. #include <lights_lambert_pars_fragment>
  6592. #include <shadowmap_pars_fragment>
  6593. #include <bumpmap_pars_fragment>
  6594. #include <normalmap_pars_fragment>
  6595. #include <specularmap_pars_fragment>
  6596. #include <logdepthbuf_pars_fragment>
  6597. #include <clipping_planes_pars_fragment>
  6598. void main() {
  6599. #include <clipping_planes_fragment>
  6600. vec4 diffuseColor = vec4( diffuse, opacity );
  6601. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6602. vec3 totalEmissiveRadiance = emissive;
  6603. #include <logdepthbuf_fragment>
  6604. #include <map_fragment>
  6605. #include <color_fragment>
  6606. #include <alphamap_fragment>
  6607. #include <alphatest_fragment>
  6608. #include <alphahash_fragment>
  6609. #include <specularmap_fragment>
  6610. #include <normal_fragment_begin>
  6611. #include <normal_fragment_maps>
  6612. #include <emissivemap_fragment>
  6613. #include <lights_lambert_fragment>
  6614. #include <lights_fragment_begin>
  6615. #include <lights_fragment_maps>
  6616. #include <lights_fragment_end>
  6617. #include <aomap_fragment>
  6618. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  6619. #include <envmap_fragment>
  6620. #include <opaque_fragment>
  6621. #include <tonemapping_fragment>
  6622. #include <colorspace_fragment>
  6623. #include <fog_fragment>
  6624. #include <premultiplied_alpha_fragment>
  6625. #include <dithering_fragment>
  6626. }`,SCe=`#define MATCAP
  6627. varying vec3 vViewPosition;
  6628. #include <common>
  6629. #include <batching_pars_vertex>
  6630. #include <uv_pars_vertex>
  6631. #include <color_pars_vertex>
  6632. #include <displacementmap_pars_vertex>
  6633. #include <fog_pars_vertex>
  6634. #include <normal_pars_vertex>
  6635. #include <morphtarget_pars_vertex>
  6636. #include <skinning_pars_vertex>
  6637. #include <logdepthbuf_pars_vertex>
  6638. #include <clipping_planes_pars_vertex>
  6639. void main() {
  6640. #include <uv_vertex>
  6641. #include <color_vertex>
  6642. #include <morphcolor_vertex>
  6643. #include <batching_vertex>
  6644. #include <beginnormal_vertex>
  6645. #include <morphnormal_vertex>
  6646. #include <skinbase_vertex>
  6647. #include <skinnormal_vertex>
  6648. #include <defaultnormal_vertex>
  6649. #include <normal_vertex>
  6650. #include <begin_vertex>
  6651. #include <morphtarget_vertex>
  6652. #include <skinning_vertex>
  6653. #include <displacementmap_vertex>
  6654. #include <project_vertex>
  6655. #include <logdepthbuf_vertex>
  6656. #include <clipping_planes_vertex>
  6657. #include <fog_vertex>
  6658. vViewPosition = - mvPosition.xyz;
  6659. }`,_Ce=`#define MATCAP
  6660. uniform vec3 diffuse;
  6661. uniform float opacity;
  6662. uniform sampler2D matcap;
  6663. varying vec3 vViewPosition;
  6664. #include <common>
  6665. #include <dithering_pars_fragment>
  6666. #include <color_pars_fragment>
  6667. #include <uv_pars_fragment>
  6668. #include <map_pars_fragment>
  6669. #include <alphamap_pars_fragment>
  6670. #include <alphatest_pars_fragment>
  6671. #include <alphahash_pars_fragment>
  6672. #include <fog_pars_fragment>
  6673. #include <normal_pars_fragment>
  6674. #include <bumpmap_pars_fragment>
  6675. #include <normalmap_pars_fragment>
  6676. #include <logdepthbuf_pars_fragment>
  6677. #include <clipping_planes_pars_fragment>
  6678. void main() {
  6679. #include <clipping_planes_fragment>
  6680. vec4 diffuseColor = vec4( diffuse, opacity );
  6681. #include <logdepthbuf_fragment>
  6682. #include <map_fragment>
  6683. #include <color_fragment>
  6684. #include <alphamap_fragment>
  6685. #include <alphatest_fragment>
  6686. #include <alphahash_fragment>
  6687. #include <normal_fragment_begin>
  6688. #include <normal_fragment_maps>
  6689. vec3 viewDir = normalize( vViewPosition );
  6690. vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
  6691. vec3 y = cross( viewDir, x );
  6692. vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
  6693. #ifdef USE_MATCAP
  6694. vec4 matcapColor = texture2D( matcap, uv );
  6695. #else
  6696. vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
  6697. #endif
  6698. vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
  6699. #include <opaque_fragment>
  6700. #include <tonemapping_fragment>
  6701. #include <colorspace_fragment>
  6702. #include <fog_fragment>
  6703. #include <premultiplied_alpha_fragment>
  6704. #include <dithering_fragment>
  6705. }`,NCe=`#define NORMAL
  6706. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6707. varying vec3 vViewPosition;
  6708. #endif
  6709. #include <common>
  6710. #include <batching_pars_vertex>
  6711. #include <uv_pars_vertex>
  6712. #include <displacementmap_pars_vertex>
  6713. #include <normal_pars_vertex>
  6714. #include <morphtarget_pars_vertex>
  6715. #include <skinning_pars_vertex>
  6716. #include <logdepthbuf_pars_vertex>
  6717. #include <clipping_planes_pars_vertex>
  6718. void main() {
  6719. #include <uv_vertex>
  6720. #include <batching_vertex>
  6721. #include <beginnormal_vertex>
  6722. #include <morphnormal_vertex>
  6723. #include <skinbase_vertex>
  6724. #include <skinnormal_vertex>
  6725. #include <defaultnormal_vertex>
  6726. #include <normal_vertex>
  6727. #include <begin_vertex>
  6728. #include <morphtarget_vertex>
  6729. #include <skinning_vertex>
  6730. #include <displacementmap_vertex>
  6731. #include <project_vertex>
  6732. #include <logdepthbuf_vertex>
  6733. #include <clipping_planes_vertex>
  6734. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6735. vViewPosition = - mvPosition.xyz;
  6736. #endif
  6737. }`,CCe=`#define NORMAL
  6738. uniform float opacity;
  6739. #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
  6740. varying vec3 vViewPosition;
  6741. #endif
  6742. #include <packing>
  6743. #include <uv_pars_fragment>
  6744. #include <normal_pars_fragment>
  6745. #include <bumpmap_pars_fragment>
  6746. #include <normalmap_pars_fragment>
  6747. #include <logdepthbuf_pars_fragment>
  6748. #include <clipping_planes_pars_fragment>
  6749. void main() {
  6750. #include <clipping_planes_fragment>
  6751. #include <logdepthbuf_fragment>
  6752. #include <normal_fragment_begin>
  6753. #include <normal_fragment_maps>
  6754. gl_FragColor = vec4( packNormalToRGB( normal ), opacity );
  6755. #ifdef OPAQUE
  6756. gl_FragColor.a = 1.0;
  6757. #endif
  6758. }`,kCe=`#define PHONG
  6759. varying vec3 vViewPosition;
  6760. #include <common>
  6761. #include <batching_pars_vertex>
  6762. #include <uv_pars_vertex>
  6763. #include <displacementmap_pars_vertex>
  6764. #include <envmap_pars_vertex>
  6765. #include <color_pars_vertex>
  6766. #include <fog_pars_vertex>
  6767. #include <normal_pars_vertex>
  6768. #include <morphtarget_pars_vertex>
  6769. #include <skinning_pars_vertex>
  6770. #include <shadowmap_pars_vertex>
  6771. #include <logdepthbuf_pars_vertex>
  6772. #include <clipping_planes_pars_vertex>
  6773. void main() {
  6774. #include <uv_vertex>
  6775. #include <color_vertex>
  6776. #include <morphcolor_vertex>
  6777. #include <batching_vertex>
  6778. #include <beginnormal_vertex>
  6779. #include <morphnormal_vertex>
  6780. #include <skinbase_vertex>
  6781. #include <skinnormal_vertex>
  6782. #include <defaultnormal_vertex>
  6783. #include <normal_vertex>
  6784. #include <begin_vertex>
  6785. #include <morphtarget_vertex>
  6786. #include <skinning_vertex>
  6787. #include <displacementmap_vertex>
  6788. #include <project_vertex>
  6789. #include <logdepthbuf_vertex>
  6790. #include <clipping_planes_vertex>
  6791. vViewPosition = - mvPosition.xyz;
  6792. #include <worldpos_vertex>
  6793. #include <envmap_vertex>
  6794. #include <shadowmap_vertex>
  6795. #include <fog_vertex>
  6796. }`,ACe=`#define PHONG
  6797. uniform vec3 diffuse;
  6798. uniform vec3 emissive;
  6799. uniform vec3 specular;
  6800. uniform float shininess;
  6801. uniform float opacity;
  6802. #include <common>
  6803. #include <packing>
  6804. #include <dithering_pars_fragment>
  6805. #include <color_pars_fragment>
  6806. #include <uv_pars_fragment>
  6807. #include <map_pars_fragment>
  6808. #include <alphamap_pars_fragment>
  6809. #include <alphatest_pars_fragment>
  6810. #include <alphahash_pars_fragment>
  6811. #include <aomap_pars_fragment>
  6812. #include <lightmap_pars_fragment>
  6813. #include <emissivemap_pars_fragment>
  6814. #include <envmap_common_pars_fragment>
  6815. #include <envmap_pars_fragment>
  6816. #include <fog_pars_fragment>
  6817. #include <bsdfs>
  6818. #include <lights_pars_begin>
  6819. #include <normal_pars_fragment>
  6820. #include <lights_phong_pars_fragment>
  6821. #include <shadowmap_pars_fragment>
  6822. #include <bumpmap_pars_fragment>
  6823. #include <normalmap_pars_fragment>
  6824. #include <specularmap_pars_fragment>
  6825. #include <logdepthbuf_pars_fragment>
  6826. #include <clipping_planes_pars_fragment>
  6827. void main() {
  6828. #include <clipping_planes_fragment>
  6829. vec4 diffuseColor = vec4( diffuse, opacity );
  6830. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6831. vec3 totalEmissiveRadiance = emissive;
  6832. #include <logdepthbuf_fragment>
  6833. #include <map_fragment>
  6834. #include <color_fragment>
  6835. #include <alphamap_fragment>
  6836. #include <alphatest_fragment>
  6837. #include <alphahash_fragment>
  6838. #include <specularmap_fragment>
  6839. #include <normal_fragment_begin>
  6840. #include <normal_fragment_maps>
  6841. #include <emissivemap_fragment>
  6842. #include <lights_phong_fragment>
  6843. #include <lights_fragment_begin>
  6844. #include <lights_fragment_maps>
  6845. #include <lights_fragment_end>
  6846. #include <aomap_fragment>
  6847. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
  6848. #include <envmap_fragment>
  6849. #include <opaque_fragment>
  6850. #include <tonemapping_fragment>
  6851. #include <colorspace_fragment>
  6852. #include <fog_fragment>
  6853. #include <premultiplied_alpha_fragment>
  6854. #include <dithering_fragment>
  6855. }`,TCe=`#define STANDARD
  6856. varying vec3 vViewPosition;
  6857. #ifdef USE_TRANSMISSION
  6858. varying vec3 vWorldPosition;
  6859. #endif
  6860. #include <common>
  6861. #include <batching_pars_vertex>
  6862. #include <uv_pars_vertex>
  6863. #include <displacementmap_pars_vertex>
  6864. #include <color_pars_vertex>
  6865. #include <fog_pars_vertex>
  6866. #include <normal_pars_vertex>
  6867. #include <morphtarget_pars_vertex>
  6868. #include <skinning_pars_vertex>
  6869. #include <shadowmap_pars_vertex>
  6870. #include <logdepthbuf_pars_vertex>
  6871. #include <clipping_planes_pars_vertex>
  6872. void main() {
  6873. #include <uv_vertex>
  6874. #include <color_vertex>
  6875. #include <morphcolor_vertex>
  6876. #include <batching_vertex>
  6877. #include <beginnormal_vertex>
  6878. #include <morphnormal_vertex>
  6879. #include <skinbase_vertex>
  6880. #include <skinnormal_vertex>
  6881. #include <defaultnormal_vertex>
  6882. #include <normal_vertex>
  6883. #include <begin_vertex>
  6884. #include <morphtarget_vertex>
  6885. #include <skinning_vertex>
  6886. #include <displacementmap_vertex>
  6887. #include <project_vertex>
  6888. #include <logdepthbuf_vertex>
  6889. #include <clipping_planes_vertex>
  6890. vViewPosition = - mvPosition.xyz;
  6891. #include <worldpos_vertex>
  6892. #include <shadowmap_vertex>
  6893. #include <fog_vertex>
  6894. #ifdef USE_TRANSMISSION
  6895. vWorldPosition = worldPosition.xyz;
  6896. #endif
  6897. }`,MCe=`#define STANDARD
  6898. #ifdef PHYSICAL
  6899. #define IOR
  6900. #define USE_SPECULAR
  6901. #endif
  6902. uniform vec3 diffuse;
  6903. uniform vec3 emissive;
  6904. uniform float roughness;
  6905. uniform float metalness;
  6906. uniform float opacity;
  6907. #ifdef IOR
  6908. uniform float ior;
  6909. #endif
  6910. #ifdef USE_SPECULAR
  6911. uniform float specularIntensity;
  6912. uniform vec3 specularColor;
  6913. #ifdef USE_SPECULAR_COLORMAP
  6914. uniform sampler2D specularColorMap;
  6915. #endif
  6916. #ifdef USE_SPECULAR_INTENSITYMAP
  6917. uniform sampler2D specularIntensityMap;
  6918. #endif
  6919. #endif
  6920. #ifdef USE_CLEARCOAT
  6921. uniform float clearcoat;
  6922. uniform float clearcoatRoughness;
  6923. #endif
  6924. #ifdef USE_IRIDESCENCE
  6925. uniform float iridescence;
  6926. uniform float iridescenceIOR;
  6927. uniform float iridescenceThicknessMinimum;
  6928. uniform float iridescenceThicknessMaximum;
  6929. #endif
  6930. #ifdef USE_SHEEN
  6931. uniform vec3 sheenColor;
  6932. uniform float sheenRoughness;
  6933. #ifdef USE_SHEEN_COLORMAP
  6934. uniform sampler2D sheenColorMap;
  6935. #endif
  6936. #ifdef USE_SHEEN_ROUGHNESSMAP
  6937. uniform sampler2D sheenRoughnessMap;
  6938. #endif
  6939. #endif
  6940. #ifdef USE_ANISOTROPY
  6941. uniform vec2 anisotropyVector;
  6942. #ifdef USE_ANISOTROPYMAP
  6943. uniform sampler2D anisotropyMap;
  6944. #endif
  6945. #endif
  6946. varying vec3 vViewPosition;
  6947. #include <common>
  6948. #include <packing>
  6949. #include <dithering_pars_fragment>
  6950. #include <color_pars_fragment>
  6951. #include <uv_pars_fragment>
  6952. #include <map_pars_fragment>
  6953. #include <alphamap_pars_fragment>
  6954. #include <alphatest_pars_fragment>
  6955. #include <alphahash_pars_fragment>
  6956. #include <aomap_pars_fragment>
  6957. #include <lightmap_pars_fragment>
  6958. #include <emissivemap_pars_fragment>
  6959. #include <iridescence_fragment>
  6960. #include <cube_uv_reflection_fragment>
  6961. #include <envmap_common_pars_fragment>
  6962. #include <envmap_physical_pars_fragment>
  6963. #include <fog_pars_fragment>
  6964. #include <lights_pars_begin>
  6965. #include <normal_pars_fragment>
  6966. #include <lights_physical_pars_fragment>
  6967. #include <transmission_pars_fragment>
  6968. #include <shadowmap_pars_fragment>
  6969. #include <bumpmap_pars_fragment>
  6970. #include <normalmap_pars_fragment>
  6971. #include <clearcoat_pars_fragment>
  6972. #include <iridescence_pars_fragment>
  6973. #include <roughnessmap_pars_fragment>
  6974. #include <metalnessmap_pars_fragment>
  6975. #include <logdepthbuf_pars_fragment>
  6976. #include <clipping_planes_pars_fragment>
  6977. void main() {
  6978. #include <clipping_planes_fragment>
  6979. vec4 diffuseColor = vec4( diffuse, opacity );
  6980. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  6981. vec3 totalEmissiveRadiance = emissive;
  6982. #include <logdepthbuf_fragment>
  6983. #include <map_fragment>
  6984. #include <color_fragment>
  6985. #include <alphamap_fragment>
  6986. #include <alphatest_fragment>
  6987. #include <alphahash_fragment>
  6988. #include <roughnessmap_fragment>
  6989. #include <metalnessmap_fragment>
  6990. #include <normal_fragment_begin>
  6991. #include <normal_fragment_maps>
  6992. #include <clearcoat_normal_fragment_begin>
  6993. #include <clearcoat_normal_fragment_maps>
  6994. #include <emissivemap_fragment>
  6995. #include <lights_physical_fragment>
  6996. #include <lights_fragment_begin>
  6997. #include <lights_fragment_maps>
  6998. #include <lights_fragment_end>
  6999. #include <aomap_fragment>
  7000. vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
  7001. vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
  7002. #include <transmission_fragment>
  7003. vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
  7004. #ifdef USE_SHEEN
  7005. float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
  7006. outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
  7007. #endif
  7008. #ifdef USE_CLEARCOAT
  7009. float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
  7010. vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
  7011. outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
  7012. #endif
  7013. #include <opaque_fragment>
  7014. #include <tonemapping_fragment>
  7015. #include <colorspace_fragment>
  7016. #include <fog_fragment>
  7017. #include <premultiplied_alpha_fragment>
  7018. #include <dithering_fragment>
  7019. }`,PCe=`#define TOON
  7020. varying vec3 vViewPosition;
  7021. #include <common>
  7022. #include <batching_pars_vertex>
  7023. #include <uv_pars_vertex>
  7024. #include <displacementmap_pars_vertex>
  7025. #include <color_pars_vertex>
  7026. #include <fog_pars_vertex>
  7027. #include <normal_pars_vertex>
  7028. #include <morphtarget_pars_vertex>
  7029. #include <skinning_pars_vertex>
  7030. #include <shadowmap_pars_vertex>
  7031. #include <logdepthbuf_pars_vertex>
  7032. #include <clipping_planes_pars_vertex>
  7033. void main() {
  7034. #include <uv_vertex>
  7035. #include <color_vertex>
  7036. #include <morphcolor_vertex>
  7037. #include <batching_vertex>
  7038. #include <beginnormal_vertex>
  7039. #include <morphnormal_vertex>
  7040. #include <skinbase_vertex>
  7041. #include <skinnormal_vertex>
  7042. #include <defaultnormal_vertex>
  7043. #include <normal_vertex>
  7044. #include <begin_vertex>
  7045. #include <morphtarget_vertex>
  7046. #include <skinning_vertex>
  7047. #include <displacementmap_vertex>
  7048. #include <project_vertex>
  7049. #include <logdepthbuf_vertex>
  7050. #include <clipping_planes_vertex>
  7051. vViewPosition = - mvPosition.xyz;
  7052. #include <worldpos_vertex>
  7053. #include <shadowmap_vertex>
  7054. #include <fog_vertex>
  7055. }`,ECe=`#define TOON
  7056. uniform vec3 diffuse;
  7057. uniform vec3 emissive;
  7058. uniform float opacity;
  7059. #include <common>
  7060. #include <packing>
  7061. #include <dithering_pars_fragment>
  7062. #include <color_pars_fragment>
  7063. #include <uv_pars_fragment>
  7064. #include <map_pars_fragment>
  7065. #include <alphamap_pars_fragment>
  7066. #include <alphatest_pars_fragment>
  7067. #include <alphahash_pars_fragment>
  7068. #include <aomap_pars_fragment>
  7069. #include <lightmap_pars_fragment>
  7070. #include <emissivemap_pars_fragment>
  7071. #include <gradientmap_pars_fragment>
  7072. #include <fog_pars_fragment>
  7073. #include <bsdfs>
  7074. #include <lights_pars_begin>
  7075. #include <normal_pars_fragment>
  7076. #include <lights_toon_pars_fragment>
  7077. #include <shadowmap_pars_fragment>
  7078. #include <bumpmap_pars_fragment>
  7079. #include <normalmap_pars_fragment>
  7080. #include <logdepthbuf_pars_fragment>
  7081. #include <clipping_planes_pars_fragment>
  7082. void main() {
  7083. #include <clipping_planes_fragment>
  7084. vec4 diffuseColor = vec4( diffuse, opacity );
  7085. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  7086. vec3 totalEmissiveRadiance = emissive;
  7087. #include <logdepthbuf_fragment>
  7088. #include <map_fragment>
  7089. #include <color_fragment>
  7090. #include <alphamap_fragment>
  7091. #include <alphatest_fragment>
  7092. #include <alphahash_fragment>
  7093. #include <normal_fragment_begin>
  7094. #include <normal_fragment_maps>
  7095. #include <emissivemap_fragment>
  7096. #include <lights_toon_fragment>
  7097. #include <lights_fragment_begin>
  7098. #include <lights_fragment_maps>
  7099. #include <lights_fragment_end>
  7100. #include <aomap_fragment>
  7101. vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
  7102. #include <opaque_fragment>
  7103. #include <tonemapping_fragment>
  7104. #include <colorspace_fragment>
  7105. #include <fog_fragment>
  7106. #include <premultiplied_alpha_fragment>
  7107. #include <dithering_fragment>
  7108. }`,jCe=`uniform float size;
  7109. uniform float scale;
  7110. #include <common>
  7111. #include <color_pars_vertex>
  7112. #include <fog_pars_vertex>
  7113. #include <morphtarget_pars_vertex>
  7114. #include <logdepthbuf_pars_vertex>
  7115. #include <clipping_planes_pars_vertex>
  7116. #ifdef USE_POINTS_UV
  7117. varying vec2 vUv;
  7118. uniform mat3 uvTransform;
  7119. #endif
  7120. void main() {
  7121. #ifdef USE_POINTS_UV
  7122. vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
  7123. #endif
  7124. #include <color_vertex>
  7125. #include <morphcolor_vertex>
  7126. #include <begin_vertex>
  7127. #include <morphtarget_vertex>
  7128. #include <project_vertex>
  7129. gl_PointSize = size;
  7130. #ifdef USE_SIZEATTENUATION
  7131. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7132. if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
  7133. #endif
  7134. #include <logdepthbuf_vertex>
  7135. #include <clipping_planes_vertex>
  7136. #include <worldpos_vertex>
  7137. #include <fog_vertex>
  7138. }`,DCe=`uniform vec3 diffuse;
  7139. uniform float opacity;
  7140. #include <common>
  7141. #include <color_pars_fragment>
  7142. #include <map_particle_pars_fragment>
  7143. #include <alphatest_pars_fragment>
  7144. #include <alphahash_pars_fragment>
  7145. #include <fog_pars_fragment>
  7146. #include <logdepthbuf_pars_fragment>
  7147. #include <clipping_planes_pars_fragment>
  7148. void main() {
  7149. #include <clipping_planes_fragment>
  7150. vec3 outgoingLight = vec3( 0.0 );
  7151. vec4 diffuseColor = vec4( diffuse, opacity );
  7152. #include <logdepthbuf_fragment>
  7153. #include <map_particle_fragment>
  7154. #include <color_fragment>
  7155. #include <alphatest_fragment>
  7156. #include <alphahash_fragment>
  7157. outgoingLight = diffuseColor.rgb;
  7158. #include <opaque_fragment>
  7159. #include <tonemapping_fragment>
  7160. #include <colorspace_fragment>
  7161. #include <fog_fragment>
  7162. #include <premultiplied_alpha_fragment>
  7163. }`,RCe=`#include <common>
  7164. #include <batching_pars_vertex>
  7165. #include <fog_pars_vertex>
  7166. #include <morphtarget_pars_vertex>
  7167. #include <skinning_pars_vertex>
  7168. #include <logdepthbuf_pars_vertex>
  7169. #include <shadowmap_pars_vertex>
  7170. void main() {
  7171. #include <batching_vertex>
  7172. #include <beginnormal_vertex>
  7173. #include <morphnormal_vertex>
  7174. #include <skinbase_vertex>
  7175. #include <skinnormal_vertex>
  7176. #include <defaultnormal_vertex>
  7177. #include <begin_vertex>
  7178. #include <morphtarget_vertex>
  7179. #include <skinning_vertex>
  7180. #include <project_vertex>
  7181. #include <logdepthbuf_vertex>
  7182. #include <worldpos_vertex>
  7183. #include <shadowmap_vertex>
  7184. #include <fog_vertex>
  7185. }`,FCe=`uniform vec3 color;
  7186. uniform float opacity;
  7187. #include <common>
  7188. #include <packing>
  7189. #include <fog_pars_fragment>
  7190. #include <bsdfs>
  7191. #include <lights_pars_begin>
  7192. #include <logdepthbuf_pars_fragment>
  7193. #include <shadowmap_pars_fragment>
  7194. #include <shadowmask_pars_fragment>
  7195. void main() {
  7196. #include <logdepthbuf_fragment>
  7197. gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
  7198. #include <tonemapping_fragment>
  7199. #include <colorspace_fragment>
  7200. #include <fog_fragment>
  7201. }`,LCe=`uniform float rotation;
  7202. uniform vec2 center;
  7203. #include <common>
  7204. #include <uv_pars_vertex>
  7205. #include <fog_pars_vertex>
  7206. #include <logdepthbuf_pars_vertex>
  7207. #include <clipping_planes_pars_vertex>
  7208. void main() {
  7209. #include <uv_vertex>
  7210. vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
  7211. vec2 scale;
  7212. scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
  7213. scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
  7214. #ifndef USE_SIZEATTENUATION
  7215. bool isPerspective = isPerspectiveMatrix( projectionMatrix );
  7216. if ( isPerspective ) scale *= - mvPosition.z;
  7217. #endif
  7218. vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
  7219. vec2 rotatedPosition;
  7220. rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
  7221. rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
  7222. mvPosition.xy += rotatedPosition;
  7223. gl_Position = projectionMatrix * mvPosition;
  7224. #include <logdepthbuf_vertex>
  7225. #include <clipping_planes_vertex>
  7226. #include <fog_vertex>
  7227. }`,OCe=`uniform vec3 diffuse;
  7228. uniform float opacity;
  7229. #include <common>
  7230. #include <uv_pars_fragment>
  7231. #include <map_pars_fragment>
  7232. #include <alphamap_pars_fragment>
  7233. #include <alphatest_pars_fragment>
  7234. #include <alphahash_pars_fragment>
  7235. #include <fog_pars_fragment>
  7236. #include <logdepthbuf_pars_fragment>
  7237. #include <clipping_planes_pars_fragment>
  7238. void main() {
  7239. #include <clipping_planes_fragment>
  7240. vec3 outgoingLight = vec3( 0.0 );
  7241. vec4 diffuseColor = vec4( diffuse, opacity );
  7242. #include <logdepthbuf_fragment>
  7243. #include <map_fragment>
  7244. #include <alphamap_fragment>
  7245. #include <alphatest_fragment>
  7246. #include <alphahash_fragment>
  7247. outgoingLight = diffuseColor.rgb;
  7248. #include <opaque_fragment>
  7249. #include <tonemapping_fragment>
  7250. #include <colorspace_fragment>
  7251. #include <fog_fragment>
  7252. }`,On={alphahash_fragment:i1e,alphahash_pars_fragment:s1e,alphamap_fragment:o1e,alphamap_pars_fragment:l1e,alphatest_fragment:c1e,alphatest_pars_fragment:u1e,aomap_fragment:d1e,aomap_pars_fragment:h1e,batching_pars_vertex:m1e,batching_vertex:f1e,begin_vertex:p1e,beginnormal_vertex:g1e,bsdfs:b1e,iridescence_fragment:x1e,bumpmap_pars_fragment:y1e,clipping_planes_fragment:v1e,clipping_planes_pars_fragment:w1e,clipping_planes_pars_vertex:S1e,clipping_planes_vertex:_1e,color_fragment:N1e,color_pars_fragment:C1e,color_pars_vertex:k1e,color_vertex:A1e,common:T1e,cube_uv_reflection_fragment:M1e,defaultnormal_vertex:P1e,displacementmap_pars_vertex:E1e,displacementmap_vertex:j1e,emissivemap_fragment:D1e,emissivemap_pars_fragment:R1e,colorspace_fragment:F1e,colorspace_pars_fragment:L1e,envmap_fragment:O1e,envmap_common_pars_fragment:I1e,envmap_pars_fragment:z1e,envmap_pars_vertex:U1e,envmap_physical_pars_fragment:Z1e,envmap_vertex:B1e,fog_vertex:H1e,fog_pars_vertex:$1e,fog_fragment:V1e,fog_pars_fragment:q1e,gradientmap_pars_fragment:G1e,lightmap_fragment:W1e,lightmap_pars_fragment:K1e,lights_lambert_fragment:X1e,lights_lambert_pars_fragment:Y1e,lights_pars_begin:Q1e,lights_toon_fragment:J1e,lights_toon_pars_fragment:eNe,lights_phong_fragment:tNe,lights_phong_pars_fragment:nNe,lights_physical_fragment:rNe,lights_physical_pars_fragment:aNe,lights_fragment_begin:iNe,lights_fragment_maps:sNe,lights_fragment_end:oNe,logdepthbuf_fragment:lNe,logdepthbuf_pars_fragment:cNe,logdepthbuf_pars_vertex:uNe,logdepthbuf_vertex:dNe,map_fragment:hNe,map_pars_fragment:mNe,map_particle_fragment:fNe,map_particle_pars_fragment:pNe,metalnessmap_fragment:gNe,metalnessmap_pars_fragment:bNe,morphcolor_vertex:xNe,morphnormal_vertex:yNe,morphtarget_pars_vertex:vNe,morphtarget_vertex:wNe,normal_fragment_begin:SNe,normal_fragment_maps:_Ne,normal_pars_fragment:NNe,normal_pars_vertex:CNe,normal_vertex:kNe,normalmap_pars_fragment:ANe,clearcoat_normal_fragment_begin:TNe,clearcoat_normal_fragment_maps:MNe,clearcoat_pars_fragment:PNe,iridescence_pars_fragment:ENe,opaque_fragment:jNe,packing:DNe,premultiplied_alpha_fragment:RNe,project_vertex:FNe,dithering_fragment:LNe,dithering_pars_fragment:ONe,roughnessmap_fragment:INe,roughnessmap_pars_fragment:zNe,shadowmap_pars_fragment:UNe,shadowmap_pars_vertex:BNe,shadowmap_vertex:HNe,shadowmask_pars_fragment:$Ne,skinbase_vertex:VNe,skinning_pars_vertex:qNe,skinning_vertex:GNe,skinnormal_vertex:WNe,specularmap_fragment:KNe,specularmap_pars_fragment:XNe,tonemapping_fragment:YNe,tonemapping_pars_fragment:QNe,transmission_fragment:ZNe,transmission_pars_fragment:JNe,uv_pars_fragment:eCe,uv_pars_vertex:tCe,uv_vertex:nCe,worldpos_vertex:rCe,background_vert:aCe,background_frag:iCe,backgroundCube_vert:sCe,backgroundCube_frag:oCe,cube_vert:lCe,cube_frag:cCe,depth_vert:uCe,depth_frag:dCe,distanceRGBA_vert:hCe,distanceRGBA_frag:mCe,equirect_vert:fCe,equirect_frag:pCe,linedashed_vert:gCe,linedashed_frag:bCe,meshbasic_vert:xCe,meshbasic_frag:yCe,meshlambert_vert:vCe,meshlambert_frag:wCe,meshmatcap_vert:SCe,meshmatcap_frag:_Ce,meshnormal_vert:NCe,meshnormal_frag:CCe,meshphong_vert:kCe,meshphong_frag:ACe,meshphysical_vert:TCe,meshphysical_frag:MCe,meshtoon_vert:PCe,meshtoon_frag:ECe,points_vert:jCe,points_frag:DCe,shadow_vert:RCe,shadow_frag:FCe,sprite_vert:LCe,sprite_frag:OCe},Ut={common:{diffuse:{value:new dn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new qn},alphaMap:{value:null},alphaMapTransform:{value:new qn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new qn}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new qn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new qn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new qn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new qn},normalScale:{value:new _n(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new qn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new qn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new qn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new qn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new dn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new dn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new qn},alphaTest:{value:0},uvTransform:{value:new qn}},sprite:{diffuse:{value:new dn(16777215)},opacity:{value:1},center:{value:new _n(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new qn},alphaMap:{value:null},alphaMapTransform:{value:new qn},alphaTest:{value:0}}},Xs={basic:{uniforms:As([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.fog]),vertexShader:On.meshbasic_vert,fragmentShader:On.meshbasic_frag},lambert:{uniforms:As([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,Ut.lights,{emissive:{value:new dn(0)}}]),vertexShader:On.meshlambert_vert,fragmentShader:On.meshlambert_frag},phong:{uniforms:As([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,Ut.lights,{emissive:{value:new dn(0)},specular:{value:new dn(1118481)},shininess:{value:30}}]),vertexShader:On.meshphong_vert,fragmentShader:On.meshphong_frag},standard:{uniforms:As([Ut.common,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.roughnessmap,Ut.metalnessmap,Ut.fog,Ut.lights,{emissive:{value:new dn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:On.meshphysical_vert,fragmentShader:On.meshphysical_frag},toon:{uniforms:As([Ut.common,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.gradientmap,Ut.fog,Ut.lights,{emissive:{value:new dn(0)}}]),vertexShader:On.meshtoon_vert,fragmentShader:On.meshtoon_frag},matcap:{uniforms:As([Ut.common,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,{matcap:{value:null}}]),vertexShader:On.meshmatcap_vert,fragmentShader:On.meshmatcap_frag},points:{uniforms:As([Ut.points,Ut.fog]),vertexShader:On.points_vert,fragmentShader:On.points_frag},dashed:{uniforms:As([Ut.common,Ut.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:On.linedashed_vert,fragmentShader:On.linedashed_frag},depth:{uniforms:As([Ut.common,Ut.displacementmap]),vertexShader:On.depth_vert,fragmentShader:On.depth_frag},normal:{uniforms:As([Ut.common,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,{opacity:{value:1}}]),vertexShader:On.meshnormal_vert,fragmentShader:On.meshnormal_frag},sprite:{uniforms:As([Ut.sprite,Ut.fog]),vertexShader:On.sprite_vert,fragmentShader:On.sprite_frag},background:{uniforms:{uvTransform:{value:new qn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:On.background_vert,fragmentShader:On.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1}},vertexShader:On.backgroundCube_vert,fragmentShader:On.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:On.cube_vert,fragmentShader:On.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:On.equirect_vert,fragmentShader:On.equirect_frag},distanceRGBA:{uniforms:As([Ut.common,Ut.displacementmap,{referencePosition:{value:new Ze},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:On.distanceRGBA_vert,fragmentShader:On.distanceRGBA_frag},shadow:{uniforms:As([Ut.lights,Ut.fog,{color:{value:new dn(0)},opacity:{value:1}}]),vertexShader:On.shadow_vert,fragmentShader:On.shadow_frag}};Xs.physical={uniforms:As([Xs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new qn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new qn},clearcoatNormalScale:{value:new _n(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new qn},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new qn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new qn},sheen:{value:0},sheenColor:{value:new dn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new qn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new qn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new qn},transmissionSamplerSize:{value:new _n},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new qn},attenuationDistance:{value:0},attenuationColor:{value:new dn(0)},specularColor:{value:new dn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new qn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new qn},anisotropyVector:{value:new _n},anisotropyMap:{value:null},anisotropyMapTransform:{value:new qn}}]),vertexShader:On.meshphysical_vert,fragmentShader:On.meshphysical_frag};const XS={r:0,b:0,g:0};function ICe(t,e,n,r,a,s,o){const l=new dn(0);let c=s===!0?0:1,u,d,h=null,f=0,p=null;function x(g,y){let _=!1,N=y.isScene===!0?y.background:null;N&&N.isTexture&&(N=(y.backgroundBlurriness>0?n:e).get(N)),N===null?v(l,c):N&&N.isColor&&(v(N,1),_=!0);const k=t.xr.getEnvironmentBlendMode();k==="additive"?r.buffers.color.setClear(0,0,0,1,o):k==="alpha-blend"&&r.buffers.color.setClear(0,0,0,0,o),(t.autoClear||_)&&t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil),N&&(N.isCubeTexture||N.mapping===ok)?(d===void 0&&(d=new Gl(new b0(1,1,1),new Kh({name:"BackgroundCubeMaterial",uniforms:Sb(Xs.backgroundCube.uniforms),vertexShader:Xs.backgroundCube.vertexShader,fragmentShader:Xs.backgroundCube.fragmentShader,side:no,depthTest:!1,depthWrite:!1,fog:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(A,M,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),a.update(d)),d.material.uniforms.envMap.value=N,d.material.uniforms.flipEnvMap.value=N.isCubeTexture&&N.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=y.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,d.material.toneMapped=Fr.getTransfer(N.colorSpace)!==ea,(h!==N||f!==N.version||p!==t.toneMapping)&&(d.material.needsUpdate=!0,h=N,f=N.version,p=t.toneMapping),d.layers.enableAll(),g.unshift(d,d.geometry,d.material,0,0,null)):N&&N.isTexture&&(u===void 0&&(u=new Gl(new rL(2,2),new Kh({name:"BackgroundMaterial",uniforms:Sb(Xs.background.uniforms),vertexShader:Xs.background.vertexShader,fragmentShader:Xs.background.fragmentShader,side:Wh,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),Object.defineProperty(u.material,"map",{get:function(){return this.uniforms.t2D.value}}),a.update(u)),u.material.uniforms.t2D.value=N,u.material.uniforms.backgroundIntensity.value=y.backgroundIntensity,u.material.toneMapped=Fr.getTransfer(N.colorSpace)!==ea,N.matrixAutoUpdate===!0&&N.updateMatrix(),u.material.uniforms.uvTransform.value.copy(N.matrix),(h!==N||f!==N.version||p!==t.toneMapping)&&(u.material.needsUpdate=!0,h=N,f=N.version,p=t.toneMapping),u.layers.enableAll(),g.unshift(u,u.geometry,u.material,0,0,null))}function v(g,y){g.getRGB(XS,BY(t)),r.buffers.color.setClear(XS.r,XS.g,XS.b,y,o)}return{getClearColor:function(){return l},setClearColor:function(g,y=1){l.set(g),c=y,v(l,c)},getClearAlpha:function(){return c},setClearAlpha:function(g){c=g,v(l,c)},render:x}}function zCe(t,e,n,r){const a=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=r.isWebGL2?null:e.get("OES_vertex_array_object"),o=r.isWebGL2||s!==null,l={},c=g(null);let u=c,d=!1;function h(D,$,G,z,W){let X=!1;if(o){const ae=v(z,G,$);u!==ae&&(u=ae,p(u.object)),X=y(D,z,G,W),X&&_(D,z,G,W)}else{const ae=$.wireframe===!0;(u.geometry!==z.id||u.program!==G.id||u.wireframe!==ae)&&(u.geometry=z.id,u.program=G.id,u.wireframe=ae,X=!0)}W!==null&&n.update(W,t.ELEMENT_ARRAY_BUFFER),(X||d)&&(d=!1,j(D,$,G,z),W!==null&&t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n.get(W).buffer))}function f(){return r.isWebGL2?t.createVertexArray():s.createVertexArrayOES()}function p(D){return r.isWebGL2?t.bindVertexArray(D):s.bindVertexArrayOES(D)}function x(D){return r.isWebGL2?t.deleteVertexArray(D):s.deleteVertexArrayOES(D)}function v(D,$,G){const z=G.wireframe===!0;let W=l[D.id];W===void 0&&(W={},l[D.id]=W);let X=W[$.id];X===void 0&&(X={},W[$.id]=X);let ae=X[z];return ae===void 0&&(ae=g(f()),X[z]=ae),ae}function g(D){const $=[],G=[],z=[];for(let W=0;W<a;W++)$[W]=0,G[W]=0,z[W]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:$,enabledAttributes:G,attributeDivisors:z,object:D,attributes:{},index:null}}function y(D,$,G,z){const W=u.attributes,X=$.attributes;let ae=0;const H=G.getAttributes();for(const K in H)if(H[K].location>=0){const Z=W[K];let ve=X[K];if(ve===void 0&&(K==="instanceMatrix"&&D.instanceMatrix&&(ve=D.instanceMatrix),K==="instanceColor"&&D.instanceColor&&(ve=D.instanceColor)),Z===void 0||Z.attribute!==ve||ve&&Z.data!==ve.data)return!0;ae++}return u.attributesNum!==ae||u.index!==z}function _(D,$,G,z){const W={},X=$.attributes;let ae=0;const H=G.getAttributes();for(const K in H)if(H[K].location>=0){let Z=X[K];Z===void 0&&(K==="instanceMatrix"&&D.instanceMatrix&&(Z=D.instanceMatrix),K==="instanceColor"&&D.instanceColor&&(Z=D.instanceColor));const ve={};ve.attribute=Z,Z&&Z.data&&(ve.data=Z.data),W[K]=ve,ae++}u.attributes=W,u.attributesNum=ae,u.index=z}function N(){const D=u.newAttributes;for(let $=0,G=D.length;$<G;$++)D[$]=0}function k(D){A(D,0)}function A(D,$){const G=u.newAttributes,z=u.enabledAttributes,W=u.attributeDivisors;G[D]=1,z[D]===0&&(t.enableVertexAttribArray(D),z[D]=1),W[D]!==$&&((r.isWebGL2?t:e.get("ANGLE_instanced_arrays"))[r.isWebGL2?"vertexAttribDivisor":"vertexAttribDivisorANGLE"](D,$),W[D]=$)}function M(){const D=u.newAttributes,$=u.enabledAttributes;for(let G=0,z=$.length;G<z;G++)$[G]!==D[G]&&(t.disableVertexAttribArray(G),$[G]=0)}function C(D,$,G,z,W,X,ae){ae===!0?t.vertexAttribIPointer(D,$,G,W,X):t.vertexAttribPointer(D,$,G,z,W,X)}function j(D,$,G,z){if(r.isWebGL2===!1&&(D.isInstancedMesh||z.isInstancedBufferGeometry)&&e.get("ANGLE_instanced_arrays")===null)return;N();const W=z.attributes,X=G.getAttributes(),ae=$.defaultAttributeValues;for(const H in X){const K=X[H];if(K.location>=0){let te=W[H];if(te===void 0&&(H==="instanceMatrix"&&D.instanceMatrix&&(te=D.instanceMatrix),H==="instanceColor"&&D.instanceColor&&(te=D.instanceColor)),te!==void 0){const Z=te.normalized,ve=te.itemSize,ce=n.get(te);if(ce===void 0)continue;const ee=ce.buffer,je=ce.type,he=ce.bytesPerElement,oe=r.isWebGL2===!0&&(je===t.INT||je===t.UNSIGNED_INT||te.gpuType===wY);if(te.isInterleavedBufferAttribute){const _e=te.data,ie=_e.stride,ze=te.offset;if(_e.isInstancedInterleavedBuffer){for(let V=0;V<K.locationSize;V++)A(K.location+V,_e.meshPerAttribute);D.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=_e.meshPerAttribute*_e.count)}else for(let V=0;V<K.locationSize;V++)k(K.location+V);t.bindBuffer(t.ARRAY_BUFFER,ee);for(let V=0;V<K.locationSize;V++)C(K.location+V,ve/K.locationSize,je,Z,ie*he,(ze+ve/K.locationSize*V)*he,oe)}else{if(te.isInstancedBufferAttribute){for(let _e=0;_e<K.locationSize;_e++)A(K.location+_e,te.meshPerAttribute);D.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=te.meshPerAttribute*te.count)}else for(let _e=0;_e<K.locationSize;_e++)k(K.location+_e);t.bindBuffer(t.ARRAY_BUFFER,ee);for(let _e=0;_e<K.locationSize;_e++)C(K.location+_e,ve/K.locationSize,je,Z,ve*he,ve/K.locationSize*_e*he,oe)}}else if(ae!==void 0){const Z=ae[H];if(Z!==void 0)switch(Z.length){case 2:t.vertexAttrib2fv(K.location,Z);break;case 3:t.vertexAttrib3fv(K.location,Z);break;case 4:t.vertexAttrib4fv(K.location,Z);break;default:t.vertexAttrib1fv(K.location,Z)}}}}M()}function P(){L();for(const D in l){const $=l[D];for(const G in $){const z=$[G];for(const W in z)x(z[W].object),delete z[W];delete $[G]}delete l[D]}}function E(D){if(l[D.id]===void 0)return;const $=l[D.id];for(const G in $){const z=$[G];for(const W in z)x(z[W].object),delete z[W];delete $[G]}delete l[D.id]}function U(D){for(const $ in l){const G=l[$];if(G[D.id]===void 0)continue;const z=G[D.id];for(const W in z)x(z[W].object),delete z[W];delete G[D.id]}}function L(){B(),d=!0,u!==c&&(u=c,p(u.object))}function B(){c.geometry=null,c.program=null,c.wireframe=!1}return{setup:h,reset:L,resetDefaultState:B,dispose:P,releaseStatesOfGeometry:E,releaseStatesOfProgram:U,initAttributes:N,enableAttribute:k,disableUnusedAttributes:M}}function UCe(t,e,n,r){const a=r.isWebGL2;let s;function o(d){s=d}function l(d,h){t.drawArrays(s,d,h),n.update(h,s,1)}function c(d,h,f){if(f===0)return;let p,x;if(a)p=t,x="drawArraysInstanced";else if(p=e.get("ANGLE_instanced_arrays"),x="drawArraysInstancedANGLE",p===null){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}p[x](s,d,h,f),n.update(h,s,f)}function u(d,h,f){if(f===0)return;const p=e.get("WEBGL_multi_draw");if(p===null)for(let x=0;x<f;x++)this.render(d[x],h[x]);else{p.multiDrawArraysWEBGL(s,d,0,h,0,f);let x=0;for(let v=0;v<f;v++)x+=h[v];n.update(x,s,1)}}this.setMode=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=u}function BCe(t,e,n){let r;function a(){if(r!==void 0)return r;if(e.has("EXT_texture_filter_anisotropic")===!0){const C=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r}function s(C){if(C==="highp"){if(t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}const o=typeof WebGL2RenderingContext<"u"&&t.constructor.name==="WebGL2RenderingContext";let l=n.precision!==void 0?n.precision:"highp";const c=s(l);c!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",c,"instead."),l=c);const u=o||e.has("WEBGL_draw_buffers"),d=n.logarithmicDepthBuffer===!0,h=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),f=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=t.getParameter(t.MAX_TEXTURE_SIZE),x=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),v=t.getParameter(t.MAX_VERTEX_ATTRIBS),g=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),y=t.getParameter(t.MAX_VARYING_VECTORS),_=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),N=f>0,k=o||e.has("OES_texture_float"),A=N&&k,M=o?t.getParameter(t.MAX_SAMPLES):0;return{isWebGL2:o,drawBuffers:u,getMaxAnisotropy:a,getMaxPrecision:s,precision:l,logarithmicDepthBuffer:d,maxTextures:h,maxVertexTextures:f,maxTextureSize:p,maxCubemapSize:x,maxAttributes:v,maxVertexUniforms:g,maxVaryings:y,maxFragmentUniforms:_,vertexTextures:N,floatFragmentTextures:k,floatVertexTextures:A,maxSamples:M}}function HCe(t){const e=this;let n=null,r=0,a=!1,s=!1;const o=new sh,l=new qn,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(h,f){const p=h.length!==0||f||r!==0||a;return a=f,r=h.length,p},this.beginShadows=function(){s=!0,d(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,f){n=d(h,f,0)},this.setState=function(h,f,p){const x=h.clippingPlanes,v=h.clipIntersection,g=h.clipShadows,y=t.get(h);if(!a||x===null||x.length===0||s&&!g)s?d(null):u();else{const _=s?0:r,N=_*4;let k=y.clippingState||null;c.value=k,k=d(x,f,N,p);for(let A=0;A!==N;++A)k[A]=n[A];y.clippingState=k,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=_}};function u(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),e.numPlanes=r,e.numIntersection=0}function d(h,f,p,x){const v=h!==null?h.length:0;let g=null;if(v!==0){if(g=c.value,x!==!0||g===null){const y=p+v*4,_=f.matrixWorldInverse;l.getNormalMatrix(_),(g===null||g.length<y)&&(g=new Float32Array(y));for(let N=0,k=p;N!==v;++N,k+=4)o.copy(h[N]).applyMatrix4(_,l),o.normal.toArray(g,k),g[k+3]=o.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,g}}function $Ce(t){let e=new WeakMap;function n(o,l){return l===aD?o.mapping=yb:l===iD&&(o.mapping=vb),o}function r(o){if(o&&o.isTexture){const l=o.mapping;if(l===aD||l===iD)if(e.has(o)){const c=e.get(o).texture;return n(c,o.mapping)}else{const c=o.image;if(c&&c.height>0){const u=new t1e(c.height/2);return u.fromEquirectangularTexture(t,o),e.set(o,u),o.addEventListener("dispose",a),n(u.texture,o.mapping)}else return null}}return o}function a(o){const l=o.target;l.removeEventListener("dispose",a);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function s(){e=new WeakMap}return{get:r,dispose:s}}class VCe extends HY{constructor(e=-1,n=1,r=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=n,this.top=r,this.bottom=a,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,n){return super.copy(e,n),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,n,r,a,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=n,this.view.offsetX=r,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),n=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=r-e,o=r+e,l=a+n,c=a-n;if(this.view!==null&&this.view.enabled){const u=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=u*this.view.offsetX,o=s+u*this.view.width,l-=d*this.view.offsetY,c=l-d*this.view.height}this.projectionMatrix.makeOrthographic(s,o,l,c,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const n=super.toJSON(e);return n.object.zoom=this.zoom,n.object.left=this.left,n.object.right=this.right,n.object.top=this.top,n.object.bottom=this.bottom,n.object.near=this.near,n.object.far=this.far,this.view!==null&&(n.object.view=Object.assign({},this.view)),n}}const Ug=4,J6=[.125,.215,.35,.446,.526,.582],Xm=20,VP=new VCe,eH=new dn;let qP=null,GP=0,WP=0;const Hm=(1+Math.sqrt(5))/2,yg=1/Hm,tH=[new Ze(1,1,1),new Ze(-1,1,1),new Ze(1,1,-1),new Ze(-1,1,-1),new Ze(0,Hm,yg),new Ze(0,Hm,-yg),new Ze(yg,0,Hm),new Ze(-yg,0,Hm),new Ze(Hm,yg,0),new Ze(-Hm,yg,0)];class nH{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,n=0,r=.1,a=100){qP=this._renderer.getRenderTarget(),GP=this._renderer.getActiveCubeFace(),WP=this._renderer.getActiveMipmapLevel(),this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,r,a,s),n>0&&this._blur(s,0,0,n),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,n=null){return this._fromTexture(e,n)}fromCubemap(e,n=null){return this._fromTexture(e,n)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=iH(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=aH(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(qP,GP,WP),e.scissorTest=!1,YS(e,0,0,e.width,e.height)}_fromTexture(e,n){e.mapping===yb||e.mapping===vb?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),qP=this._renderer.getRenderTarget(),GP=this._renderer.getActiveCubeFace(),WP=this._renderer.getActiveMipmapLevel();const r=n||this._allocateTargets();return this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),n=4*this._cubeSize,r={magFilter:ol,minFilter:ol,generateMipmaps:!1,type:kv,format:ll,colorSpace:id,depthBuffer:!1},a=rH(e,n,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==n){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=rH(e,n,r);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=qCe(s)),this._blurMaterial=GCe(s,e,n)}return a}_compileMaterial(e){const n=new Gl(this._lodPlanes[0],e);this._renderer.compile(n,VP)}_sceneToCubeUV(e,n,r,a){const l=new Ao(90,1,n,r),c=[1,-1,1,1,1,1],u=[1,1,1,-1,-1,-1],d=this._renderer,h=d.autoClear,f=d.toneMapping;d.getClearColor(eH),d.toneMapping=Lh,d.autoClear=!1;const p=new IY({name:"PMREM.Background",side:no,depthWrite:!1,depthTest:!1}),x=new Gl(new b0,p);let v=!1;const g=e.background;g?g.isColor&&(p.color.copy(g),e.background=null,v=!0):(p.color.copy(eH),v=!0);for(let y=0;y<6;y++){const _=y%3;_===0?(l.up.set(0,c[y],0),l.lookAt(u[y],0,0)):_===1?(l.up.set(0,0,c[y]),l.lookAt(0,u[y],0)):(l.up.set(0,c[y],0),l.lookAt(0,0,u[y]));const N=this._cubeSize;YS(a,_*N,y>2?N:0,N,N),d.setRenderTarget(a),v&&d.render(x,l),d.render(e,l)}x.geometry.dispose(),x.material.dispose(),d.toneMapping=f,d.autoClear=h,e.background=g}_textureToCubeUV(e,n){const r=this._renderer,a=e.mapping===yb||e.mapping===vb;a?(this._cubemapMaterial===null&&(this._cubemapMaterial=iH()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=aH());const s=a?this._cubemapMaterial:this._equirectMaterial,o=new Gl(this._lodPlanes[0],s),l=s.uniforms;l.envMap.value=e;const c=this._cubeSize;YS(n,0,0,3*c,2*c),r.setRenderTarget(n),r.render(o,VP)}_applyPMREM(e){const n=this._renderer,r=n.autoClear;n.autoClear=!1;for(let a=1;a<this._lodPlanes.length;a++){const s=Math.sqrt(this._sigmas[a]*this._sigmas[a]-this._sigmas[a-1]*this._sigmas[a-1]),o=tH[(a-1)%tH.length];this._blur(e,a-1,a,s,o)}n.autoClear=r}_blur(e,n,r,a,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,n,r,a,"latitudinal",s),this._halfBlur(o,e,r,r,a,"longitudinal",s)}_halfBlur(e,n,r,a,s,o,l){const c=this._renderer,u=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const d=3,h=new Gl(this._lodPlanes[a],u),f=u.uniforms,p=this._sizeLods[r]-1,x=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*Xm-1),v=s/x,g=isFinite(s)?1+Math.floor(d*v):Xm;g>Xm&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Xm}`);const y=[];let _=0;for(let C=0;C<Xm;++C){const j=C/v,P=Math.exp(-j*j/2);y.push(P),C===0?_+=P:C<g&&(_+=2*P)}for(let C=0;C<y.length;C++)y[C]=y[C]/_;f.envMap.value=e.texture,f.samples.value=g,f.weights.value=y,f.latitudinal.value=o==="latitudinal",l&&(f.poleAxis.value=l);const{_lodMax:N}=this;f.dTheta.value=x,f.mipInt.value=N-r;const k=this._sizeLods[a],A=3*k*(a>N-Ug?a-N+Ug:0),M=4*(this._cubeSize-k);YS(n,A,M,3*k,2*k),c.setRenderTarget(n),c.render(h,VP)}}function qCe(t){const e=[],n=[],r=[];let a=t;const s=t-Ug+1+J6.length;for(let o=0;o<s;o++){const l=Math.pow(2,a);n.push(l);let c=1/l;o>t-Ug?c=J6[o-t+Ug-1]:o===0&&(c=0),r.push(c);const u=1/(l-2),d=-u,h=1+u,f=[d,d,h,d,h,h,d,d,h,h,d,h],p=6,x=6,v=3,g=2,y=1,_=new Float32Array(v*x*p),N=new Float32Array(g*x*p),k=new Float32Array(y*x*p);for(let M=0;M<p;M++){const C=M%3*2/3-1,j=M>2?0:-1,P=[C,j,0,C+2/3,j,0,C+2/3,j+1,0,C,j,0,C+2/3,j+1,0,C,j+1,0];_.set(P,v*x*M),N.set(f,g*x*M);const E=[M,M,M,M,M,M];k.set(E,y*x*M)}const A=new ys;A.setAttribute("position",new Do(_,v)),A.setAttribute("uv",new Do(N,g)),A.setAttribute("faceIndex",new Do(k,y)),e.push(A),a>Ug&&a--}return{lodPlanes:e,sizeLods:n,sigmas:r}}function rH(t,e,n){const r=new If(t,e,n);return r.texture.mapping=ok,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function YS(t,e,n,r,a){t.viewport.set(e,n,r,a),t.scissor.set(e,n,r,a)}function GCe(t,e,n){const r=new Float32Array(Xm),a=new Ze(0,1,0);return new Kh({name:"SphericalGaussianBlur",defines:{n:Xm,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:a}},vertexShader:aL(),fragmentShader:`
  7253. precision mediump float;
  7254. precision mediump int;
  7255. varying vec3 vOutputDirection;
  7256. uniform sampler2D envMap;
  7257. uniform int samples;
  7258. uniform float weights[ n ];
  7259. uniform bool latitudinal;
  7260. uniform float dTheta;
  7261. uniform float mipInt;
  7262. uniform vec3 poleAxis;
  7263. #define ENVMAP_TYPE_CUBE_UV
  7264. #include <cube_uv_reflection_fragment>
  7265. vec3 getSample( float theta, vec3 axis ) {
  7266. float cosTheta = cos( theta );
  7267. // Rodrigues' axis-angle rotation
  7268. vec3 sampleDirection = vOutputDirection * cosTheta
  7269. + cross( axis, vOutputDirection ) * sin( theta )
  7270. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  7271. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  7272. }
  7273. void main() {
  7274. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  7275. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  7276. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  7277. }
  7278. axis = normalize( axis );
  7279. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  7280. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  7281. for ( int i = 1; i < n; i++ ) {
  7282. if ( i >= samples ) {
  7283. break;
  7284. }
  7285. float theta = dTheta * float( i );
  7286. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  7287. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  7288. }
  7289. }
  7290. `,blending:Fh,depthTest:!1,depthWrite:!1})}function aH(){return new Kh({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:aL(),fragmentShader:`
  7291. precision mediump float;
  7292. precision mediump int;
  7293. varying vec3 vOutputDirection;
  7294. uniform sampler2D envMap;
  7295. #include <common>
  7296. void main() {
  7297. vec3 outputDirection = normalize( vOutputDirection );
  7298. vec2 uv = equirectUv( outputDirection );
  7299. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  7300. }
  7301. `,blending:Fh,depthTest:!1,depthWrite:!1})}function iH(){return new Kh({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:aL(),fragmentShader:`
  7302. precision mediump float;
  7303. precision mediump int;
  7304. uniform float flipEnvMap;
  7305. varying vec3 vOutputDirection;
  7306. uniform samplerCube envMap;
  7307. void main() {
  7308. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  7309. }
  7310. `,blending:Fh,depthTest:!1,depthWrite:!1})}function aL(){return`
  7311. precision mediump float;
  7312. precision mediump int;
  7313. attribute float faceIndex;
  7314. varying vec3 vOutputDirection;
  7315. // RH coordinate system; PMREM face-indexing convention
  7316. vec3 getDirection( vec2 uv, float face ) {
  7317. uv = 2.0 * uv - 1.0;
  7318. vec3 direction = vec3( uv, 1.0 );
  7319. if ( face == 0.0 ) {
  7320. direction = direction.zyx; // ( 1, v, u ) pos x
  7321. } else if ( face == 1.0 ) {
  7322. direction = direction.xzy;
  7323. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  7324. } else if ( face == 2.0 ) {
  7325. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  7326. } else if ( face == 3.0 ) {
  7327. direction = direction.zyx;
  7328. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  7329. } else if ( face == 4.0 ) {
  7330. direction = direction.xzy;
  7331. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  7332. } else if ( face == 5.0 ) {
  7333. direction.z *= -1.0; // ( u, v, -1 ) neg z
  7334. }
  7335. return direction;
  7336. }
  7337. void main() {
  7338. vOutputDirection = getDirection( uv, faceIndex );
  7339. gl_Position = vec4( position, 1.0 );
  7340. }
  7341. `}function WCe(t){let e=new WeakMap,n=null;function r(l){if(l&&l.isTexture){const c=l.mapping,u=c===aD||c===iD,d=c===yb||c===vb;if(u||d)if(l.isRenderTargetTexture&&l.needsPMREMUpdate===!0){l.needsPMREMUpdate=!1;let h=e.get(l);return n===null&&(n=new nH(t)),h=u?n.fromEquirectangular(l,h):n.fromCubemap(l,h),e.set(l,h),h.texture}else{if(e.has(l))return e.get(l).texture;{const h=l.image;if(u&&h&&h.height>0||d&&h&&a(h)){n===null&&(n=new nH(t));const f=u?n.fromEquirectangular(l):n.fromCubemap(l);return e.set(l,f),l.addEventListener("dispose",s),f.texture}else return null}}}return l}function a(l){let c=0;const u=6;for(let d=0;d<u;d++)l[d]!==void 0&&c++;return c===u}function s(l){const c=l.target;c.removeEventListener("dispose",s);const u=e.get(c);u!==void 0&&(e.delete(c),u.dispose())}function o(){e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function KCe(t){const e={};function n(r){if(e[r]!==void 0)return e[r];let a;switch(r){case"WEBGL_depth_texture":a=t.getExtension("WEBGL_depth_texture")||t.getExtension("MOZ_WEBGL_depth_texture")||t.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":a=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":a=t.getExtension("WEBGL_compressed_texture_s3tc")||t.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":a=t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:a=t.getExtension(r)}return e[r]=a,a}return{has:function(r){return n(r)!==null},init:function(r){r.isWebGL2?n("EXT_color_buffer_float"):(n("WEBGL_depth_texture"),n("OES_texture_float"),n("OES_texture_half_float"),n("OES_texture_half_float_linear"),n("OES_standard_derivatives"),n("OES_element_index_uint"),n("OES_vertex_array_object"),n("ANGLE_instanced_arrays")),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture")},get:function(r){const a=n(r);return a===null&&console.warn("THREE.WebGLRenderer: "+r+" extension not supported."),a}}}function XCe(t,e,n,r){const a={},s=new WeakMap;function o(h){const f=h.target;f.index!==null&&e.remove(f.index);for(const x in f.attributes)e.remove(f.attributes[x]);for(const x in f.morphAttributes){const v=f.morphAttributes[x];for(let g=0,y=v.length;g<y;g++)e.remove(v[g])}f.removeEventListener("dispose",o),delete a[f.id];const p=s.get(f);p&&(e.remove(p),s.delete(f)),r.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0&&delete f._maxInstanceCount,n.memory.geometries--}function l(h,f){return a[f.id]===!0||(f.addEventListener("dispose",o),a[f.id]=!0,n.memory.geometries++),f}function c(h){const f=h.attributes;for(const x in f)e.update(f[x],t.ARRAY_BUFFER);const p=h.morphAttributes;for(const x in p){const v=p[x];for(let g=0,y=v.length;g<y;g++)e.update(v[g],t.ARRAY_BUFFER)}}function u(h){const f=[],p=h.index,x=h.attributes.position;let v=0;if(p!==null){const _=p.array;v=p.version;for(let N=0,k=_.length;N<k;N+=3){const A=_[N+0],M=_[N+1],C=_[N+2];f.push(A,M,M,C,C,A)}}else if(x!==void 0){const _=x.array;v=x.version;for(let N=0,k=_.length/3-1;N<k;N+=3){const A=N+0,M=N+1,C=N+2;f.push(A,M,M,C,C,A)}}else return;const g=new(jY(f)?UY:zY)(f,1);g.version=v;const y=s.get(h);y&&e.remove(y),s.set(h,g)}function d(h){const f=s.get(h);if(f){const p=h.index;p!==null&&f.version<p.version&&u(h)}else u(h);return s.get(h)}return{get:l,update:c,getWireframeAttribute:d}}function YCe(t,e,n,r){const a=r.isWebGL2;let s;function o(p){s=p}let l,c;function u(p){l=p.type,c=p.bytesPerElement}function d(p,x){t.drawElements(s,x,l,p*c),n.update(x,s,1)}function h(p,x,v){if(v===0)return;let g,y;if(a)g=t,y="drawElementsInstanced";else if(g=e.get("ANGLE_instanced_arrays"),y="drawElementsInstancedANGLE",g===null){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}g[y](s,x,l,p*c,v),n.update(x,s,v)}function f(p,x,v){if(v===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let y=0;y<v;y++)this.render(p[y]/c,x[y]);else{g.multiDrawElementsWEBGL(s,x,0,l,p,0,v);let y=0;for(let _=0;_<v;_++)y+=x[_];n.update(y,s,1)}}this.setMode=o,this.setIndex=u,this.render=d,this.renderInstances=h,this.renderMultiDraw=f}function QCe(t){const e={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(s,o,l){switch(n.calls++,o){case t.TRIANGLES:n.triangles+=l*(s/3);break;case t.LINES:n.lines+=l*(s/2);break;case t.LINE_STRIP:n.lines+=l*(s-1);break;case t.LINE_LOOP:n.lines+=l*s;break;case t.POINTS:n.points+=l*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",o);break}}function a(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:e,render:n,programs:null,autoReset:!0,reset:a,update:r}}function ZCe(t,e){return t[0]-e[0]}function JCe(t,e){return Math.abs(e[1])-Math.abs(t[1])}function eke(t,e,n){const r={},a=new Float32Array(8),s=new WeakMap,o=new Or,l=[];for(let u=0;u<8;u++)l[u]=[u,0];function c(u,d,h){const f=u.morphTargetInfluences;if(e.isWebGL2===!0){const x=d.morphAttributes.position||d.morphAttributes.normal||d.morphAttributes.color,v=x!==void 0?x.length:0;let g=s.get(d);if(g===void 0||g.count!==v){let $=function(){B.dispose(),s.delete(d),d.removeEventListener("dispose",$)};var p=$;g!==void 0&&g.texture.dispose();const N=d.morphAttributes.position!==void 0,k=d.morphAttributes.normal!==void 0,A=d.morphAttributes.color!==void 0,M=d.morphAttributes.position||[],C=d.morphAttributes.normal||[],j=d.morphAttributes.color||[];let P=0;N===!0&&(P=1),k===!0&&(P=2),A===!0&&(P=3);let E=d.attributes.position.count*P,U=1;E>e.maxTextureSize&&(U=Math.ceil(E/e.maxTextureSize),E=e.maxTextureSize);const L=new Float32Array(E*U*4*v),B=new FY(L,E,U,v);B.type=zu,B.needsUpdate=!0;const D=P*4;for(let G=0;G<v;G++){const z=M[G],W=C[G],X=j[G],ae=E*U*4*G;for(let H=0;H<z.count;H++){const K=H*D;N===!0&&(o.fromBufferAttribute(z,H),L[ae+K+0]=o.x,L[ae+K+1]=o.y,L[ae+K+2]=o.z,L[ae+K+3]=0),k===!0&&(o.fromBufferAttribute(W,H),L[ae+K+4]=o.x,L[ae+K+5]=o.y,L[ae+K+6]=o.z,L[ae+K+7]=0),A===!0&&(o.fromBufferAttribute(X,H),L[ae+K+8]=o.x,L[ae+K+9]=o.y,L[ae+K+10]=o.z,L[ae+K+11]=X.itemSize===4?o.w:1)}}g={count:v,texture:B,size:new _n(E,U)},s.set(d,g),d.addEventListener("dispose",$)}let y=0;for(let N=0;N<f.length;N++)y+=f[N];const _=d.morphTargetsRelative?1:1-y;h.getUniforms().setValue(t,"morphTargetBaseInfluence",_),h.getUniforms().setValue(t,"morphTargetInfluences",f),h.getUniforms().setValue(t,"morphTargetsTexture",g.texture,n),h.getUniforms().setValue(t,"morphTargetsTextureSize",g.size)}else{const x=f===void 0?0:f.length;let v=r[d.id];if(v===void 0||v.length!==x){v=[];for(let k=0;k<x;k++)v[k]=[k,0];r[d.id]=v}for(let k=0;k<x;k++){const A=v[k];A[0]=k,A[1]=f[k]}v.sort(JCe);for(let k=0;k<8;k++)k<x&&v[k][1]?(l[k][0]=v[k][0],l[k][1]=v[k][1]):(l[k][0]=Number.MAX_SAFE_INTEGER,l[k][1]=0);l.sort(ZCe);const g=d.morphAttributes.position,y=d.morphAttributes.normal;let _=0;for(let k=0;k<8;k++){const A=l[k],M=A[0],C=A[1];M!==Number.MAX_SAFE_INTEGER&&C?(g&&d.getAttribute("morphTarget"+k)!==g[M]&&d.setAttribute("morphTarget"+k,g[M]),y&&d.getAttribute("morphNormal"+k)!==y[M]&&d.setAttribute("morphNormal"+k,y[M]),a[k]=C,_+=C):(g&&d.hasAttribute("morphTarget"+k)===!0&&d.deleteAttribute("morphTarget"+k),y&&d.hasAttribute("morphNormal"+k)===!0&&d.deleteAttribute("morphNormal"+k),a[k]=0)}const N=d.morphTargetsRelative?1:1-_;h.getUniforms().setValue(t,"morphTargetBaseInfluence",N),h.getUniforms().setValue(t,"morphTargetInfluences",a)}}return{update:c}}function tke(t,e,n,r){let a=new WeakMap;function s(c){const u=r.render.frame,d=c.geometry,h=e.get(c,d);if(a.get(h)!==u&&(e.update(h),a.set(h,u)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),a.get(c)!==u&&(n.update(c.instanceMatrix,t.ARRAY_BUFFER),c.instanceColor!==null&&n.update(c.instanceColor,t.ARRAY_BUFFER),a.set(c,u))),c.isSkinnedMesh){const f=c.skeleton;a.get(f)!==u&&(f.update(),a.set(f,u))}return h}function o(){a=new WeakMap}function l(c){const u=c.target;u.removeEventListener("dispose",l),n.remove(u.instanceMatrix),u.instanceColor!==null&&n.remove(u.instanceColor)}return{update:s,dispose:o}}class qY extends ro{constructor(e,n,r,a,s,o,l,c,u,d){if(d=d!==void 0?d:ff,d!==ff&&d!==wb)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&d===ff&&(r=wh),r===void 0&&d===wb&&(r=mf),super(null,a,s,o,l,c,d,r,u),this.isDepthTexture=!0,this.image={width:e,height:n},this.magFilter=l!==void 0?l:Xi,this.minFilter=c!==void 0?c:Xi,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const n=super.toJSON(e);return this.compareFunction!==null&&(n.compareFunction=this.compareFunction),n}}const GY=new ro,WY=new qY(1,1);WY.compareFunction=PY;const KY=new FY,XY=new z_e,YY=new $Y,sH=[],oH=[],lH=new Float32Array(16),cH=new Float32Array(9),uH=new Float32Array(4);function Yb(t,e,n){const r=t[0];if(r<=0||r>0)return t;const a=e*n;let s=sH[a];if(s===void 0&&(s=new Float32Array(a),sH[a]=s),e!==0){r.toArray(s,0);for(let o=1,l=0;o!==e;++o)l+=n,t[o].toArray(s,l)}return s}function xi(t,e){if(t.length!==e.length)return!1;for(let n=0,r=t.length;n<r;n++)if(t[n]!==e[n])return!1;return!0}function yi(t,e){for(let n=0,r=e.length;n<r;n++)t[n]=e[n]}function uk(t,e){let n=oH[e];n===void 0&&(n=new Int32Array(e),oH[e]=n);for(let r=0;r!==e;++r)n[r]=t.allocateTextureUnit();return n}function nke(t,e){const n=this.cache;n[0]!==e&&(t.uniform1f(this.addr,e),n[0]=e)}function rke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2f(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(xi(n,e))return;t.uniform2fv(this.addr,e),yi(n,e)}}function ake(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3f(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else if(e.r!==void 0)(n[0]!==e.r||n[1]!==e.g||n[2]!==e.b)&&(t.uniform3f(this.addr,e.r,e.g,e.b),n[0]=e.r,n[1]=e.g,n[2]=e.b);else{if(xi(n,e))return;t.uniform3fv(this.addr,e),yi(n,e)}}function ike(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4f(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(xi(n,e))return;t.uniform4fv(this.addr,e),yi(n,e)}}function ske(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(xi(n,e))return;t.uniformMatrix2fv(this.addr,!1,e),yi(n,e)}else{if(xi(n,r))return;uH.set(r),t.uniformMatrix2fv(this.addr,!1,uH),yi(n,r)}}function oke(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(xi(n,e))return;t.uniformMatrix3fv(this.addr,!1,e),yi(n,e)}else{if(xi(n,r))return;cH.set(r),t.uniformMatrix3fv(this.addr,!1,cH),yi(n,r)}}function lke(t,e){const n=this.cache,r=e.elements;if(r===void 0){if(xi(n,e))return;t.uniformMatrix4fv(this.addr,!1,e),yi(n,e)}else{if(xi(n,r))return;lH.set(r),t.uniformMatrix4fv(this.addr,!1,lH),yi(n,r)}}function cke(t,e){const n=this.cache;n[0]!==e&&(t.uniform1i(this.addr,e),n[0]=e)}function uke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2i(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(xi(n,e))return;t.uniform2iv(this.addr,e),yi(n,e)}}function dke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3i(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(xi(n,e))return;t.uniform3iv(this.addr,e),yi(n,e)}}function hke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4i(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(xi(n,e))return;t.uniform4iv(this.addr,e),yi(n,e)}}function mke(t,e){const n=this.cache;n[0]!==e&&(t.uniform1ui(this.addr,e),n[0]=e)}function fke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y)&&(t.uniform2ui(this.addr,e.x,e.y),n[0]=e.x,n[1]=e.y);else{if(xi(n,e))return;t.uniform2uiv(this.addr,e),yi(n,e)}}function pke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z)&&(t.uniform3ui(this.addr,e.x,e.y,e.z),n[0]=e.x,n[1]=e.y,n[2]=e.z);else{if(xi(n,e))return;t.uniform3uiv(this.addr,e),yi(n,e)}}function gke(t,e){const n=this.cache;if(e.x!==void 0)(n[0]!==e.x||n[1]!==e.y||n[2]!==e.z||n[3]!==e.w)&&(t.uniform4ui(this.addr,e.x,e.y,e.z,e.w),n[0]=e.x,n[1]=e.y,n[2]=e.z,n[3]=e.w);else{if(xi(n,e))return;t.uniform4uiv(this.addr,e),yi(n,e)}}function bke(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a);const s=this.type===t.SAMPLER_2D_SHADOW?WY:GY;n.setTexture2D(e||s,a)}function xke(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTexture3D(e||XY,a)}function yke(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTextureCube(e||YY,a)}function vke(t,e,n){const r=this.cache,a=n.allocateTextureUnit();r[0]!==a&&(t.uniform1i(this.addr,a),r[0]=a),n.setTexture2DArray(e||KY,a)}function wke(t){switch(t){case 5126:return nke;case 35664:return rke;case 35665:return ake;case 35666:return ike;case 35674:return ske;case 35675:return oke;case 35676:return lke;case 5124:case 35670:return cke;case 35667:case 35671:return uke;case 35668:case 35672:return dke;case 35669:case 35673:return hke;case 5125:return mke;case 36294:return fke;case 36295:return pke;case 36296:return gke;case 35678:case 36198:case 36298:case 36306:case 35682:return bke;case 35679:case 36299:case 36307:return xke;case 35680:case 36300:case 36308:case 36293:return yke;case 36289:case 36303:case 36311:case 36292:return vke}}function Ske(t,e){t.uniform1fv(this.addr,e)}function _ke(t,e){const n=Yb(e,this.size,2);t.uniform2fv(this.addr,n)}function Nke(t,e){const n=Yb(e,this.size,3);t.uniform3fv(this.addr,n)}function Cke(t,e){const n=Yb(e,this.size,4);t.uniform4fv(this.addr,n)}function kke(t,e){const n=Yb(e,this.size,4);t.uniformMatrix2fv(this.addr,!1,n)}function Ake(t,e){const n=Yb(e,this.size,9);t.uniformMatrix3fv(this.addr,!1,n)}function Tke(t,e){const n=Yb(e,this.size,16);t.uniformMatrix4fv(this.addr,!1,n)}function Mke(t,e){t.uniform1iv(this.addr,e)}function Pke(t,e){t.uniform2iv(this.addr,e)}function Eke(t,e){t.uniform3iv(this.addr,e)}function jke(t,e){t.uniform4iv(this.addr,e)}function Dke(t,e){t.uniform1uiv(this.addr,e)}function Rke(t,e){t.uniform2uiv(this.addr,e)}function Fke(t,e){t.uniform3uiv(this.addr,e)}function Lke(t,e){t.uniform4uiv(this.addr,e)}function Oke(t,e,n){const r=this.cache,a=e.length,s=uk(n,a);xi(r,s)||(t.uniform1iv(this.addr,s),yi(r,s));for(let o=0;o!==a;++o)n.setTexture2D(e[o]||GY,s[o])}function Ike(t,e,n){const r=this.cache,a=e.length,s=uk(n,a);xi(r,s)||(t.uniform1iv(this.addr,s),yi(r,s));for(let o=0;o!==a;++o)n.setTexture3D(e[o]||XY,s[o])}function zke(t,e,n){const r=this.cache,a=e.length,s=uk(n,a);xi(r,s)||(t.uniform1iv(this.addr,s),yi(r,s));for(let o=0;o!==a;++o)n.setTextureCube(e[o]||YY,s[o])}function Uke(t,e,n){const r=this.cache,a=e.length,s=uk(n,a);xi(r,s)||(t.uniform1iv(this.addr,s),yi(r,s));for(let o=0;o!==a;++o)n.setTexture2DArray(e[o]||KY,s[o])}function Bke(t){switch(t){case 5126:return Ske;case 35664:return _ke;case 35665:return Nke;case 35666:return Cke;case 35674:return kke;case 35675:return Ake;case 35676:return Tke;case 5124:case 35670:return Mke;case 35667:case 35671:return Pke;case 35668:case 35672:return Eke;case 35669:case 35673:return jke;case 5125:return Dke;case 36294:return Rke;case 36295:return Fke;case 36296:return Lke;case 35678:case 36198:case 36298:case 36306:case 35682:return Oke;case 35679:case 36299:case 36307:return Ike;case 35680:case 36300:case 36308:case 36293:return zke;case 36289:case 36303:case 36311:case 36292:return Uke}}class Hke{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.setValue=wke(n.type)}}class $ke{constructor(e,n,r){this.id=e,this.addr=r,this.cache=[],this.type=n.type,this.size=n.size,this.setValue=Bke(n.type)}}class Vke{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,n,r){const a=this.seq;for(let s=0,o=a.length;s!==o;++s){const l=a[s];l.setValue(e,n[l.id],r)}}}const KP=/(\w+)(\])?(\[|\.)?/g;function dH(t,e){t.seq.push(e),t.map[e.id]=e}function qke(t,e,n){const r=t.name,a=r.length;for(KP.lastIndex=0;;){const s=KP.exec(r),o=KP.lastIndex;let l=s[1];const c=s[2]==="]",u=s[3];if(c&&(l=l|0),u===void 0||u==="["&&o+2===a){dH(n,u===void 0?new Hke(l,t,e):new $ke(l,t,e));break}else{let h=n.map[l];h===void 0&&(h=new Vke(l),dH(n,h)),n=h}}}class Z_{constructor(e,n){this.seq=[],this.map={};const r=e.getProgramParameter(n,e.ACTIVE_UNIFORMS);for(let a=0;a<r;++a){const s=e.getActiveUniform(n,a),o=e.getUniformLocation(n,s.name);qke(s,o,this)}}setValue(e,n,r,a){const s=this.map[n];s!==void 0&&s.setValue(e,r,a)}setOptional(e,n,r){const a=n[r];a!==void 0&&this.setValue(e,r,a)}static upload(e,n,r,a){for(let s=0,o=n.length;s!==o;++s){const l=n[s],c=r[l.id];c.needsUpdate!==!1&&l.setValue(e,c.value,a)}}static seqWithValue(e,n){const r=[];for(let a=0,s=e.length;a!==s;++a){const o=e[a];o.id in n&&r.push(o)}return r}}function hH(t,e,n){const r=t.createShader(e);return t.shaderSource(r,n),t.compileShader(r),r}const Gke=37297;let Wke=0;function Kke(t,e){const n=t.split(`
  7342. `),r=[],a=Math.max(e-6,0),s=Math.min(e+6,n.length);for(let o=a;o<s;o++){const l=o+1;r.push(`${l===e?">":" "} ${l}: ${n[o]}`)}return r.join(`
  7343. `)}function Xke(t){const e=Fr.getPrimaries(Fr.workingColorSpace),n=Fr.getPrimaries(t);let r;switch(e===n?r="":e===F1&&n===R1?r="LinearDisplayP3ToLinearSRGB":e===R1&&n===F1&&(r="LinearSRGBToLinearDisplayP3"),t){case id:case lk:return[r,"LinearTransferOETF"];case Yi:case JF:return[r,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[r,"LinearTransferOETF"]}}function mH(t,e,n){const r=t.getShaderParameter(e,t.COMPILE_STATUS),a=t.getShaderInfoLog(e).trim();if(r&&a==="")return"";const s=/ERROR: 0:(\d+)/.exec(a);if(s){const o=parseInt(s[1]);return n.toUpperCase()+`
  7344. `+a+`
  7345. `+Kke(t.getShaderSource(e),o)}else return a}function Yke(t,e){const n=Xke(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function Qke(t,e){let n;switch(e){case YSe:n="Linear";break;case QSe:n="Reinhard";break;case ZSe:n="OptimizedCineon";break;case JSe:n="ACESFilmic";break;case e_e:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}function Zke(t){return[t.extensionDerivatives||t.envMapCubeUVHeight||t.bumpMap||t.normalMapTangentSpace||t.clearcoatNormalMap||t.flatShading||t.shaderID==="physical"?"#extension GL_OES_standard_derivatives : enable":"",(t.extensionFragDepth||t.logarithmicDepthBuffer)&&t.rendererExtensionFragDepth?"#extension GL_EXT_frag_depth : enable":"",t.extensionDrawBuffers&&t.rendererExtensionDrawBuffers?"#extension GL_EXT_draw_buffers : require":"",(t.extensionShaderTextureLOD||t.envMap||t.transmission)&&t.rendererExtensionShaderTextureLod?"#extension GL_EXT_shader_texture_lod : enable":""].filter(Ty).join(`
  7346. `)}function Jke(t){const e=[];for(const n in t){const r=t[n];r!==!1&&e.push("#define "+n+" "+r)}return e.join(`
  7347. `)}function eAe(t,e){const n={},r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let a=0;a<r;a++){const s=t.getActiveAttrib(e,a),o=s.name;let l=1;s.type===t.FLOAT_MAT2&&(l=2),s.type===t.FLOAT_MAT3&&(l=3),s.type===t.FLOAT_MAT4&&(l=4),n[o]={type:s.type,location:t.getAttribLocation(e,o),locationSize:l}}return n}function Ty(t){return t!==""}function fH(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function pH(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const tAe=/^[ \t]*#include +<([\w\d./]+)>/gm;function dD(t){return t.replace(tAe,rAe)}const nAe=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function rAe(t,e){let n=On[e];if(n===void 0){const r=nAe.get(e);if(r!==void 0)n=On[r],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,r);else throw new Error("Can not resolve #include <"+e+">")}return dD(n)}const aAe=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function gH(t){return t.replace(aAe,iAe)}function iAe(t,e,n,r){let a="";for(let s=parseInt(e);s<parseInt(n);s++)a+=r.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return a}function bH(t){let e="precision "+t.precision+` float;
  7348. precision `+t.precision+" int;";return t.precision==="highp"?e+=`
  7349. #define HIGH_PRECISION`:t.precision==="mediump"?e+=`
  7350. #define MEDIUM_PRECISION`:t.precision==="lowp"&&(e+=`
  7351. #define LOW_PRECISION`),e}function sAe(t){let e="SHADOWMAP_TYPE_BASIC";return t.shadowMapType===yY?e="SHADOWMAP_TYPE_PCF":t.shadowMapType===NSe?e="SHADOWMAP_TYPE_PCF_SOFT":t.shadowMapType===Mu&&(e="SHADOWMAP_TYPE_VSM"),e}function oAe(t){let e="ENVMAP_TYPE_CUBE";if(t.envMap)switch(t.envMapMode){case yb:case vb:e="ENVMAP_TYPE_CUBE";break;case ok:e="ENVMAP_TYPE_CUBE_UV";break}return e}function lAe(t){let e="ENVMAP_MODE_REFLECTION";return t.envMap&&t.envMapMode===vb&&(e="ENVMAP_MODE_REFRACTION"),e}function cAe(t){let e="ENVMAP_BLENDING_NONE";if(t.envMap)switch(t.combine){case QF:e="ENVMAP_BLENDING_MULTIPLY";break;case KSe:e="ENVMAP_BLENDING_MIX";break;case XSe:e="ENVMAP_BLENDING_ADD";break}return e}function uAe(t){const e=t.envMapCubeUVHeight;if(e===null)return null;const n=Math.log2(e)-2,r=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:r,maxMip:n}}function dAe(t,e,n,r){const a=t.getContext(),s=n.defines;let o=n.vertexShader,l=n.fragmentShader;const c=sAe(n),u=oAe(n),d=lAe(n),h=cAe(n),f=uAe(n),p=n.isWebGL2?"":Zke(n),x=Jke(s),v=a.createProgram();let g,y,_=n.glslVersion?"#version "+n.glslVersion+`
  7352. `:"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Ty).join(`
  7353. `),g.length>0&&(g+=`
  7354. `),y=[p,"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x].filter(Ty).join(`
  7355. `),y.length>0&&(y+=`
  7356. `)):(g=[bH(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x,n.batching?"#define USE_BATCHING":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&n.flatShading===!1?"#define USE_MORPHNORMALS":"",n.morphColors&&n.isWebGL2?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE":"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0&&n.isWebGL2?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )"," attribute vec3 morphTarget0;"," attribute vec3 morphTarget1;"," attribute vec3 morphTarget2;"," attribute vec3 morphTarget3;"," #ifdef USE_MORPHNORMALS"," attribute vec3 morphNormal0;"," attribute vec3 morphNormal1;"," attribute vec3 morphNormal2;"," attribute vec3 morphNormal3;"," #else"," attribute vec3 morphTarget4;"," attribute vec3 morphTarget5;"," attribute vec3 morphTarget6;"," attribute vec3 morphTarget7;"," #endif","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",`
  7357. `].filter(Ty).join(`
  7358. `),y=[p,bH(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,x,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+d:"",n.envMap?"#define "+h:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&n.flatShading===!1?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+c:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.useLegacyLights?"#define LEGACY_LIGHTS":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.logarithmicDepthBuffer&&n.rendererExtensionFragDepth?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==Lh?"#define TONE_MAPPING":"",n.toneMapping!==Lh?On.tonemapping_pars_fragment:"",n.toneMapping!==Lh?Qke("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",On.colorspace_pars_fragment,Yke("linearToOutputTexel",n.outputColorSpace),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"",`
  7359. `].filter(Ty).join(`
  7360. `)),o=dD(o),o=fH(o,n),o=pH(o,n),l=dD(l),l=fH(l,n),l=pH(l,n),o=gH(o),l=gH(l),n.isWebGL2&&n.isRawShaderMaterial!==!0&&(_=`#version 300 es
  7361. `,g=["precision mediump sampler2DArray;","#define attribute in","#define varying out","#define texture2D texture"].join(`
  7362. `)+`
  7363. `+g,y=["precision mediump sampler2DArray;","#define varying in",n.glslVersion===F6?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===F6?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
  7364. `)+`
  7365. `+y);const N=_+g+o,k=_+y+l,A=hH(a,a.VERTEX_SHADER,N),M=hH(a,a.FRAGMENT_SHADER,k);a.attachShader(v,A),a.attachShader(v,M),n.index0AttributeName!==void 0?a.bindAttribLocation(v,0,n.index0AttributeName):n.morphTargets===!0&&a.bindAttribLocation(v,0,"position"),a.linkProgram(v);function C(U){if(t.debug.checkShaderErrors){const L=a.getProgramInfoLog(v).trim(),B=a.getShaderInfoLog(A).trim(),D=a.getShaderInfoLog(M).trim();let $=!0,G=!0;if(a.getProgramParameter(v,a.LINK_STATUS)===!1)if($=!1,typeof t.debug.onShaderError=="function")t.debug.onShaderError(a,v,A,M);else{const z=mH(a,A,"vertex"),W=mH(a,M,"fragment");console.error("THREE.WebGLProgram: Shader Error "+a.getError()+" - VALIDATE_STATUS "+a.getProgramParameter(v,a.VALIDATE_STATUS)+`
  7366. Program Info Log: `+L+`
  7367. `+z+`
  7368. `+W)}else L!==""?console.warn("THREE.WebGLProgram: Program Info Log:",L):(B===""||D==="")&&(G=!1);G&&(U.diagnostics={runnable:$,programLog:L,vertexShader:{log:B,prefix:g},fragmentShader:{log:D,prefix:y}})}a.deleteShader(A),a.deleteShader(M),j=new Z_(a,v),P=eAe(a,v)}let j;this.getUniforms=function(){return j===void 0&&C(this),j};let P;this.getAttributes=function(){return P===void 0&&C(this),P};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=a.getProgramParameter(v,Gke)),E},this.destroy=function(){r.releaseStatesOfProgram(this),a.deleteProgram(v),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Wke++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=A,this.fragmentShader=M,this}let hAe=0;class mAe{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const n=e.vertexShader,r=e.fragmentShader,a=this._getShaderStage(n),s=this._getShaderStage(r),o=this._getShaderCacheForMaterial(e);return o.has(a)===!1&&(o.add(a),a.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const n=this.materialCache.get(e);for(const r of n)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const n=this.materialCache;let r=n.get(e);return r===void 0&&(r=new Set,n.set(e,r)),r}_getShaderStage(e){const n=this.shaderCache;let r=n.get(e);return r===void 0&&(r=new fAe(e),n.set(e,r)),r}}class fAe{constructor(e){this.id=hAe++,this.code=e,this.usedTimes=0}}function pAe(t,e,n,r,a,s,o){const l=new LY,c=new mAe,u=[],d=a.isWebGL2,h=a.logarithmicDepthBuffer,f=a.vertexTextures;let p=a.precision;const x={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(P){return P===0?"uv":`uv${P}`}function g(P,E,U,L,B){const D=L.fog,$=B.geometry,G=P.isMeshStandardMaterial?L.environment:null,z=(P.isMeshStandardMaterial?n:e).get(P.envMap||G),W=z&&z.mapping===ok?z.image.height:null,X=x[P.type];P.precision!==null&&(p=a.getMaxPrecision(P.precision),p!==P.precision&&console.warn("THREE.WebGLProgram.getParameters:",P.precision,"not supported, using",p,"instead."));const ae=$.morphAttributes.position||$.morphAttributes.normal||$.morphAttributes.color,H=ae!==void 0?ae.length:0;let K=0;$.morphAttributes.position!==void 0&&(K=1),$.morphAttributes.normal!==void 0&&(K=2),$.morphAttributes.color!==void 0&&(K=3);let te,Z,ve,ce;if(X){const It=Xs[X];te=It.vertexShader,Z=It.fragmentShader}else te=P.vertexShader,Z=P.fragmentShader,c.update(P),ve=c.getVertexShaderID(P),ce=c.getFragmentShaderID(P);const ee=t.getRenderTarget(),je=B.isInstancedMesh===!0,he=B.isBatchedMesh===!0,oe=!!P.map,_e=!!P.matcap,ie=!!z,ze=!!P.aoMap,V=!!P.lightMap,Y=!!P.bumpMap,me=!!P.normalMap,Q=!!P.displacementMap,se=!!P.emissiveMap,de=!!P.metalnessMap,Le=!!P.roughnessMap,Ne=P.anisotropy>0,be=P.clearcoat>0,O=P.iridescence>0,R=P.sheen>0,q=P.transmission>0,J=Ne&&!!P.anisotropyMap,fe=be&&!!P.clearcoatMap,le=be&&!!P.clearcoatNormalMap,Be=be&&!!P.clearcoatRoughnessMap,Ie=O&&!!P.iridescenceMap,Ke=O&&!!P.iridescenceThicknessMap,Oe=R&&!!P.sheenColorMap,pe=R&&!!P.sheenRoughnessMap,xe=!!P.specularMap,ke=!!P.specularColorMap,ge=!!P.specularIntensityMap,we=q&&!!P.transmissionMap,qe=q&&!!P.thicknessMap,Ee=!!P.gradientMap,tt=!!P.alphaMap,De=P.alphaTest>0,We=!!P.alphaHash,Ae=!!P.extensions,Re=!!$.attributes.uv1,$e=!!$.attributes.uv2,ht=!!$.attributes.uv3;let At=Lh;return P.toneMapped&&(ee===null||ee.isXRRenderTarget===!0)&&(At=t.toneMapping),{isWebGL2:d,shaderID:X,shaderType:P.type,shaderName:P.name,vertexShader:te,fragmentShader:Z,defines:P.defines,customVertexShaderID:ve,customFragmentShaderID:ce,isRawShaderMaterial:P.isRawShaderMaterial===!0,glslVersion:P.glslVersion,precision:p,batching:he,instancing:je,instancingColor:je&&B.instanceColor!==null,supportsVertexTextures:f,outputColorSpace:ee===null?t.outputColorSpace:ee.isXRRenderTarget===!0?ee.texture.colorSpace:id,map:oe,matcap:_e,envMap:ie,envMapMode:ie&&z.mapping,envMapCubeUVHeight:W,aoMap:ze,lightMap:V,bumpMap:Y,normalMap:me,displacementMap:f&&Q,emissiveMap:se,normalMapObjectSpace:me&&P.normalMapType===h_e,normalMapTangentSpace:me&&P.normalMapType===MY,metalnessMap:de,roughnessMap:Le,anisotropy:Ne,anisotropyMap:J,clearcoat:be,clearcoatMap:fe,clearcoatNormalMap:le,clearcoatRoughnessMap:Be,iridescence:O,iridescenceMap:Ie,iridescenceThicknessMap:Ke,sheen:R,sheenColorMap:Oe,sheenRoughnessMap:pe,specularMap:xe,specularColorMap:ke,specularIntensityMap:ge,transmission:q,transmissionMap:we,thicknessMap:qe,gradientMap:Ee,opaque:P.transparent===!1&&P.blending===Zg,alphaMap:tt,alphaTest:De,alphaHash:We,combine:P.combine,mapUv:oe&&v(P.map.channel),aoMapUv:ze&&v(P.aoMap.channel),lightMapUv:V&&v(P.lightMap.channel),bumpMapUv:Y&&v(P.bumpMap.channel),normalMapUv:me&&v(P.normalMap.channel),displacementMapUv:Q&&v(P.displacementMap.channel),emissiveMapUv:se&&v(P.emissiveMap.channel),metalnessMapUv:de&&v(P.metalnessMap.channel),roughnessMapUv:Le&&v(P.roughnessMap.channel),anisotropyMapUv:J&&v(P.anisotropyMap.channel),clearcoatMapUv:fe&&v(P.clearcoatMap.channel),clearcoatNormalMapUv:le&&v(P.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Be&&v(P.clearcoatRoughnessMap.channel),iridescenceMapUv:Ie&&v(P.iridescenceMap.channel),iridescenceThicknessMapUv:Ke&&v(P.iridescenceThicknessMap.channel),sheenColorMapUv:Oe&&v(P.sheenColorMap.channel),sheenRoughnessMapUv:pe&&v(P.sheenRoughnessMap.channel),specularMapUv:xe&&v(P.specularMap.channel),specularColorMapUv:ke&&v(P.specularColorMap.channel),specularIntensityMapUv:ge&&v(P.specularIntensityMap.channel),transmissionMapUv:we&&v(P.transmissionMap.channel),thicknessMapUv:qe&&v(P.thicknessMap.channel),alphaMapUv:tt&&v(P.alphaMap.channel),vertexTangents:!!$.attributes.tangent&&(me||Ne),vertexColors:P.vertexColors,vertexAlphas:P.vertexColors===!0&&!!$.attributes.color&&$.attributes.color.itemSize===4,vertexUv1s:Re,vertexUv2s:$e,vertexUv3s:ht,pointsUvs:B.isPoints===!0&&!!$.attributes.uv&&(oe||tt),fog:!!D,useFog:P.fog===!0,fogExp2:D&&D.isFogExp2,flatShading:P.flatShading===!0,sizeAttenuation:P.sizeAttenuation===!0,logarithmicDepthBuffer:h,skinning:B.isSkinnedMesh===!0,morphTargets:$.morphAttributes.position!==void 0,morphNormals:$.morphAttributes.normal!==void 0,morphColors:$.morphAttributes.color!==void 0,morphTargetsCount:H,morphTextureStride:K,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:P.dithering,shadowMapEnabled:t.shadowMap.enabled&&U.length>0,shadowMapType:t.shadowMap.type,toneMapping:At,useLegacyLights:t._useLegacyLights,decodeVideoTexture:oe&&P.map.isVideoTexture===!0&&Fr.getTransfer(P.map.colorSpace)===ea,premultipliedAlpha:P.premultipliedAlpha,doubleSided:P.side===Du,flipSided:P.side===no,useDepthPacking:P.depthPacking>=0,depthPacking:P.depthPacking||0,index0AttributeName:P.index0AttributeName,extensionDerivatives:Ae&&P.extensions.derivatives===!0,extensionFragDepth:Ae&&P.extensions.fragDepth===!0,extensionDrawBuffers:Ae&&P.extensions.drawBuffers===!0,extensionShaderTextureLOD:Ae&&P.extensions.shaderTextureLOD===!0,rendererExtensionFragDepth:d||r.has("EXT_frag_depth"),rendererExtensionDrawBuffers:d||r.has("WEBGL_draw_buffers"),rendererExtensionShaderTextureLod:d||r.has("EXT_shader_texture_lod"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:P.customProgramCacheKey()}}function y(P){const E=[];if(P.shaderID?E.push(P.shaderID):(E.push(P.customVertexShaderID),E.push(P.customFragmentShaderID)),P.defines!==void 0)for(const U in P.defines)E.push(U),E.push(P.defines[U]);return P.isRawShaderMaterial===!1&&(_(E,P),N(E,P),E.push(t.outputColorSpace)),E.push(P.customProgramCacheKey),E.join()}function _(P,E){P.push(E.precision),P.push(E.outputColorSpace),P.push(E.envMapMode),P.push(E.envMapCubeUVHeight),P.push(E.mapUv),P.push(E.alphaMapUv),P.push(E.lightMapUv),P.push(E.aoMapUv),P.push(E.bumpMapUv),P.push(E.normalMapUv),P.push(E.displacementMapUv),P.push(E.emissiveMapUv),P.push(E.metalnessMapUv),P.push(E.roughnessMapUv),P.push(E.anisotropyMapUv),P.push(E.clearcoatMapUv),P.push(E.clearcoatNormalMapUv),P.push(E.clearcoatRoughnessMapUv),P.push(E.iridescenceMapUv),P.push(E.iridescenceThicknessMapUv),P.push(E.sheenColorMapUv),P.push(E.sheenRoughnessMapUv),P.push(E.specularMapUv),P.push(E.specularColorMapUv),P.push(E.specularIntensityMapUv),P.push(E.transmissionMapUv),P.push(E.thicknessMapUv),P.push(E.combine),P.push(E.fogExp2),P.push(E.sizeAttenuation),P.push(E.morphTargetsCount),P.push(E.morphAttributeCount),P.push(E.numDirLights),P.push(E.numPointLights),P.push(E.numSpotLights),P.push(E.numSpotLightMaps),P.push(E.numHemiLights),P.push(E.numRectAreaLights),P.push(E.numDirLightShadows),P.push(E.numPointLightShadows),P.push(E.numSpotLightShadows),P.push(E.numSpotLightShadowsWithMaps),P.push(E.numLightProbes),P.push(E.shadowMapType),P.push(E.toneMapping),P.push(E.numClippingPlanes),P.push(E.numClipIntersection),P.push(E.depthPacking)}function N(P,E){l.disableAll(),E.isWebGL2&&l.enable(0),E.supportsVertexTextures&&l.enable(1),E.instancing&&l.enable(2),E.instancingColor&&l.enable(3),E.matcap&&l.enable(4),E.envMap&&l.enable(5),E.normalMapObjectSpace&&l.enable(6),E.normalMapTangentSpace&&l.enable(7),E.clearcoat&&l.enable(8),E.iridescence&&l.enable(9),E.alphaTest&&l.enable(10),E.vertexColors&&l.enable(11),E.vertexAlphas&&l.enable(12),E.vertexUv1s&&l.enable(13),E.vertexUv2s&&l.enable(14),E.vertexUv3s&&l.enable(15),E.vertexTangents&&l.enable(16),E.anisotropy&&l.enable(17),E.alphaHash&&l.enable(18),E.batching&&l.enable(19),P.push(l.mask),l.disableAll(),E.fog&&l.enable(0),E.useFog&&l.enable(1),E.flatShading&&l.enable(2),E.logarithmicDepthBuffer&&l.enable(3),E.skinning&&l.enable(4),E.morphTargets&&l.enable(5),E.morphNormals&&l.enable(6),E.morphColors&&l.enable(7),E.premultipliedAlpha&&l.enable(8),E.shadowMapEnabled&&l.enable(9),E.useLegacyLights&&l.enable(10),E.doubleSided&&l.enable(11),E.flipSided&&l.enable(12),E.useDepthPacking&&l.enable(13),E.dithering&&l.enable(14),E.transmission&&l.enable(15),E.sheen&&l.enable(16),E.opaque&&l.enable(17),E.pointsUvs&&l.enable(18),E.decodeVideoTexture&&l.enable(19),P.push(l.mask)}function k(P){const E=x[P.type];let U;if(E){const L=Xs[E];U=nL.clone(L.uniforms)}else U=P.uniforms;return U}function A(P,E){let U;for(let L=0,B=u.length;L<B;L++){const D=u[L];if(D.cacheKey===E){U=D,++U.usedTimes;break}}return U===void 0&&(U=new dAe(t,E,P,s),u.push(U)),U}function M(P){if(--P.usedTimes===0){const E=u.indexOf(P);u[E]=u[u.length-1],u.pop(),P.destroy()}}function C(P){c.remove(P)}function j(){c.dispose()}return{getParameters:g,getProgramCacheKey:y,getUniforms:k,acquireProgram:A,releaseProgram:M,releaseShaderCache:C,programs:u,dispose:j}}function gAe(){let t=new WeakMap;function e(s){let o=t.get(s);return o===void 0&&(o={},t.set(s,o)),o}function n(s){t.delete(s)}function r(s,o,l){t.get(s)[o]=l}function a(){t=new WeakMap}return{get:e,remove:n,update:r,dispose:a}}function bAe(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.material.id!==e.material.id?t.material.id-e.material.id:t.z!==e.z?t.z-e.z:t.id-e.id}function xH(t,e){return t.groupOrder!==e.groupOrder?t.groupOrder-e.groupOrder:t.renderOrder!==e.renderOrder?t.renderOrder-e.renderOrder:t.z!==e.z?e.z-t.z:t.id-e.id}function yH(){const t=[];let e=0;const n=[],r=[],a=[];function s(){e=0,n.length=0,r.length=0,a.length=0}function o(h,f,p,x,v,g){let y=t[e];return y===void 0?(y={id:h.id,object:h,geometry:f,material:p,groupOrder:x,renderOrder:h.renderOrder,z:v,group:g},t[e]=y):(y.id=h.id,y.object=h,y.geometry=f,y.material=p,y.groupOrder=x,y.renderOrder=h.renderOrder,y.z=v,y.group=g),e++,y}function l(h,f,p,x,v,g){const y=o(h,f,p,x,v,g);p.transmission>0?r.push(y):p.transparent===!0?a.push(y):n.push(y)}function c(h,f,p,x,v,g){const y=o(h,f,p,x,v,g);p.transmission>0?r.unshift(y):p.transparent===!0?a.unshift(y):n.unshift(y)}function u(h,f){n.length>1&&n.sort(h||bAe),r.length>1&&r.sort(f||xH),a.length>1&&a.sort(f||xH)}function d(){for(let h=e,f=t.length;h<f;h++){const p=t[h];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:n,transmissive:r,transparent:a,init:s,push:l,unshift:c,finish:d,sort:u}}function xAe(){let t=new WeakMap;function e(r,a){const s=t.get(r);let o;return s===void 0?(o=new yH,t.set(r,[o])):a>=s.length?(o=new yH,s.push(o)):o=s[a],o}function n(){t=new WeakMap}return{get:e,dispose:n}}function yAe(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Ze,color:new dn};break;case"SpotLight":n={position:new Ze,direction:new Ze,color:new dn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Ze,color:new dn,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Ze,skyColor:new dn,groundColor:new dn};break;case"RectAreaLight":n={color:new dn,position:new Ze,halfWidth:new Ze,halfHeight:new Ze};break}return t[e.id]=n,n}}}function vAe(){const t={};return{get:function(e){if(t[e.id]!==void 0)return t[e.id];let n;switch(e.type){case"DirectionalLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new _n};break;case"SpotLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new _n};break;case"PointLight":n={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new _n,shadowCameraNear:1,shadowCameraFar:1e3};break}return t[e.id]=n,n}}}let wAe=0;function SAe(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function _Ae(t,e){const n=new yAe,r=vAe(),a={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let d=0;d<9;d++)a.probe.push(new Ze);const s=new Ze,o=new Yr,l=new Yr;function c(d,h){let f=0,p=0,x=0;for(let L=0;L<9;L++)a.probe[L].set(0,0,0);let v=0,g=0,y=0,_=0,N=0,k=0,A=0,M=0,C=0,j=0,P=0;d.sort(SAe);const E=h===!0?Math.PI:1;for(let L=0,B=d.length;L<B;L++){const D=d[L],$=D.color,G=D.intensity,z=D.distance,W=D.shadow&&D.shadow.map?D.shadow.map.texture:null;if(D.isAmbientLight)f+=$.r*G*E,p+=$.g*G*E,x+=$.b*G*E;else if(D.isLightProbe){for(let X=0;X<9;X++)a.probe[X].addScaledVector(D.sh.coefficients[X],G);P++}else if(D.isDirectionalLight){const X=n.get(D);if(X.color.copy(D.color).multiplyScalar(D.intensity*E),D.castShadow){const ae=D.shadow,H=r.get(D);H.shadowBias=ae.bias,H.shadowNormalBias=ae.normalBias,H.shadowRadius=ae.radius,H.shadowMapSize=ae.mapSize,a.directionalShadow[v]=H,a.directionalShadowMap[v]=W,a.directionalShadowMatrix[v]=D.shadow.matrix,k++}a.directional[v]=X,v++}else if(D.isSpotLight){const X=n.get(D);X.position.setFromMatrixPosition(D.matrixWorld),X.color.copy($).multiplyScalar(G*E),X.distance=z,X.coneCos=Math.cos(D.angle),X.penumbraCos=Math.cos(D.angle*(1-D.penumbra)),X.decay=D.decay,a.spot[y]=X;const ae=D.shadow;if(D.map&&(a.spotLightMap[C]=D.map,C++,ae.updateMatrices(D),D.castShadow&&j++),a.spotLightMatrix[y]=ae.matrix,D.castShadow){const H=r.get(D);H.shadowBias=ae.bias,H.shadowNormalBias=ae.normalBias,H.shadowRadius=ae.radius,H.shadowMapSize=ae.mapSize,a.spotShadow[y]=H,a.spotShadowMap[y]=W,M++}y++}else if(D.isRectAreaLight){const X=n.get(D);X.color.copy($).multiplyScalar(G),X.halfWidth.set(D.width*.5,0,0),X.halfHeight.set(0,D.height*.5,0),a.rectArea[_]=X,_++}else if(D.isPointLight){const X=n.get(D);if(X.color.copy(D.color).multiplyScalar(D.intensity*E),X.distance=D.distance,X.decay=D.decay,D.castShadow){const ae=D.shadow,H=r.get(D);H.shadowBias=ae.bias,H.shadowNormalBias=ae.normalBias,H.shadowRadius=ae.radius,H.shadowMapSize=ae.mapSize,H.shadowCameraNear=ae.camera.near,H.shadowCameraFar=ae.camera.far,a.pointShadow[g]=H,a.pointShadowMap[g]=W,a.pointShadowMatrix[g]=D.shadow.matrix,A++}a.point[g]=X,g++}else if(D.isHemisphereLight){const X=n.get(D);X.skyColor.copy(D.color).multiplyScalar(G*E),X.groundColor.copy(D.groundColor).multiplyScalar(G*E),a.hemi[N]=X,N++}}_>0&&(e.isWebGL2||t.has("OES_texture_float_linear")===!0?(a.rectAreaLTC1=Ut.LTC_FLOAT_1,a.rectAreaLTC2=Ut.LTC_FLOAT_2):t.has("OES_texture_half_float_linear")===!0?(a.rectAreaLTC1=Ut.LTC_HALF_1,a.rectAreaLTC2=Ut.LTC_HALF_2):console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.")),a.ambient[0]=f,a.ambient[1]=p,a.ambient[2]=x;const U=a.hash;(U.directionalLength!==v||U.pointLength!==g||U.spotLength!==y||U.rectAreaLength!==_||U.hemiLength!==N||U.numDirectionalShadows!==k||U.numPointShadows!==A||U.numSpotShadows!==M||U.numSpotMaps!==C||U.numLightProbes!==P)&&(a.directional.length=v,a.spot.length=y,a.rectArea.length=_,a.point.length=g,a.hemi.length=N,a.directionalShadow.length=k,a.directionalShadowMap.length=k,a.pointShadow.length=A,a.pointShadowMap.length=A,a.spotShadow.length=M,a.spotShadowMap.length=M,a.directionalShadowMatrix.length=k,a.pointShadowMatrix.length=A,a.spotLightMatrix.length=M+C-j,a.spotLightMap.length=C,a.numSpotLightShadowsWithMaps=j,a.numLightProbes=P,U.directionalLength=v,U.pointLength=g,U.spotLength=y,U.rectAreaLength=_,U.hemiLength=N,U.numDirectionalShadows=k,U.numPointShadows=A,U.numSpotShadows=M,U.numSpotMaps=C,U.numLightProbes=P,a.version=wAe++)}function u(d,h){let f=0,p=0,x=0,v=0,g=0;const y=h.matrixWorldInverse;for(let _=0,N=d.length;_<N;_++){const k=d[_];if(k.isDirectionalLight){const A=a.directional[f];A.direction.setFromMatrixPosition(k.matrixWorld),s.setFromMatrixPosition(k.target.matrixWorld),A.direction.sub(s),A.direction.transformDirection(y),f++}else if(k.isSpotLight){const A=a.spot[x];A.position.setFromMatrixPosition(k.matrixWorld),A.position.applyMatrix4(y),A.direction.setFromMatrixPosition(k.matrixWorld),s.setFromMatrixPosition(k.target.matrixWorld),A.direction.sub(s),A.direction.transformDirection(y),x++}else if(k.isRectAreaLight){const A=a.rectArea[v];A.position.setFromMatrixPosition(k.matrixWorld),A.position.applyMatrix4(y),l.identity(),o.copy(k.matrixWorld),o.premultiply(y),l.extractRotation(o),A.halfWidth.set(k.width*.5,0,0),A.halfHeight.set(0,k.height*.5,0),A.halfWidth.applyMatrix4(l),A.halfHeight.applyMatrix4(l),v++}else if(k.isPointLight){const A=a.point[p];A.position.setFromMatrixPosition(k.matrixWorld),A.position.applyMatrix4(y),p++}else if(k.isHemisphereLight){const A=a.hemi[g];A.direction.setFromMatrixPosition(k.matrixWorld),A.direction.transformDirection(y),g++}}}return{setup:c,setupView:u,state:a}}function vH(t,e){const n=new _Ae(t,e),r=[],a=[];function s(){r.length=0,a.length=0}function o(h){r.push(h)}function l(h){a.push(h)}function c(h){n.setup(r,h)}function u(h){n.setupView(r,h)}return{init:s,state:{lightsArray:r,shadowsArray:a,lights:n},setupLights:c,setupLightsView:u,pushLight:o,pushShadow:l}}function NAe(t,e){let n=new WeakMap;function r(s,o=0){const l=n.get(s);let c;return l===void 0?(c=new vH(t,e),n.set(s,[c])):o>=l.length?(c=new vH(t,e),l.push(c)):c=l[o],c}function a(){n=new WeakMap}return{get:r,dispose:a}}class CAe extends Xb{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=u_e,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class kAe extends Xb{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}const AAe=`void main() {
  7369. gl_Position = vec4( position, 1.0 );
  7370. }`,TAe=`uniform sampler2D shadow_pass;
  7371. uniform vec2 resolution;
  7372. uniform float radius;
  7373. #include <packing>
  7374. void main() {
  7375. const float samples = float( VSM_SAMPLES );
  7376. float mean = 0.0;
  7377. float squared_mean = 0.0;
  7378. float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
  7379. float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
  7380. for ( float i = 0.0; i < samples; i ++ ) {
  7381. float uvOffset = uvStart + i * uvStride;
  7382. #ifdef HORIZONTAL_PASS
  7383. vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
  7384. mean += distribution.x;
  7385. squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
  7386. #else
  7387. float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
  7388. mean += depth;
  7389. squared_mean += depth * depth;
  7390. #endif
  7391. }
  7392. mean = mean / samples;
  7393. squared_mean = squared_mean / samples;
  7394. float std_dev = sqrt( squared_mean - mean * mean );
  7395. gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
  7396. }`;function MAe(t,e,n){let r=new ck;const a=new _n,s=new _n,o=new Or,l=new CAe({depthPacking:d_e}),c=new kAe,u={},d=n.maxTextureSize,h={[Wh]:no,[no]:Wh,[Du]:Du},f=new Kh({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new _n},radius:{value:4}},vertexShader:AAe,fragmentShader:TAe}),p=f.clone();p.defines.HORIZONTAL_PASS=1;const x=new ys;x.setAttribute("position",new Do(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Gl(x,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=yY;let y=this.type;this.render=function(A,M,C){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;const j=t.getRenderTarget(),P=t.getActiveCubeFace(),E=t.getActiveMipmapLevel(),U=t.state;U.setBlending(Fh),U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const L=y!==Mu&&this.type===Mu,B=y===Mu&&this.type!==Mu;for(let D=0,$=A.length;D<$;D++){const G=A[D],z=G.shadow;if(z===void 0){console.warn("THREE.WebGLShadowMap:",G,"has no shadow.");continue}if(z.autoUpdate===!1&&z.needsUpdate===!1)continue;a.copy(z.mapSize);const W=z.getFrameExtents();if(a.multiply(W),s.copy(z.mapSize),(a.x>d||a.y>d)&&(a.x>d&&(s.x=Math.floor(d/W.x),a.x=s.x*W.x,z.mapSize.x=s.x),a.y>d&&(s.y=Math.floor(d/W.y),a.y=s.y*W.y,z.mapSize.y=s.y)),z.map===null||L===!0||B===!0){const ae=this.type!==Mu?{minFilter:Xi,magFilter:Xi}:{};z.map!==null&&z.map.dispose(),z.map=new If(a.x,a.y,ae),z.map.texture.name=G.name+".shadowMap",z.camera.updateProjectionMatrix()}t.setRenderTarget(z.map),t.clear();const X=z.getViewportCount();for(let ae=0;ae<X;ae++){const H=z.getViewport(ae);o.set(s.x*H.x,s.y*H.y,s.x*H.z,s.y*H.w),U.viewport(o),z.updateMatrices(G,ae),r=z.getFrustum(),k(M,C,z.camera,G,this.type)}z.isPointLightShadow!==!0&&this.type===Mu&&_(z,C),z.needsUpdate=!1}y=this.type,g.needsUpdate=!1,t.setRenderTarget(j,P,E)};function _(A,M){const C=e.update(v);f.defines.VSM_SAMPLES!==A.blurSamples&&(f.defines.VSM_SAMPLES=A.blurSamples,p.defines.VSM_SAMPLES=A.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),A.mapPass===null&&(A.mapPass=new If(a.x,a.y)),f.uniforms.shadow_pass.value=A.map.texture,f.uniforms.resolution.value=A.mapSize,f.uniforms.radius.value=A.radius,t.setRenderTarget(A.mapPass),t.clear(),t.renderBufferDirect(M,null,C,f,v,null),p.uniforms.shadow_pass.value=A.mapPass.texture,p.uniforms.resolution.value=A.mapSize,p.uniforms.radius.value=A.radius,t.setRenderTarget(A.map),t.clear(),t.renderBufferDirect(M,null,C,p,v,null)}function N(A,M,C,j){let P=null;const E=C.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(E!==void 0)P=E;else if(P=C.isPointLight===!0?c:l,t.localClippingEnabled&&M.clipShadows===!0&&Array.isArray(M.clippingPlanes)&&M.clippingPlanes.length!==0||M.displacementMap&&M.displacementScale!==0||M.alphaMap&&M.alphaTest>0||M.map&&M.alphaTest>0){const U=P.uuid,L=M.uuid;let B=u[U];B===void 0&&(B={},u[U]=B);let D=B[L];D===void 0&&(D=P.clone(),B[L]=D),P=D}if(P.visible=M.visible,P.wireframe=M.wireframe,j===Mu?P.side=M.shadowSide!==null?M.shadowSide:M.side:P.side=M.shadowSide!==null?M.shadowSide:h[M.side],P.alphaMap=M.alphaMap,P.alphaTest=M.alphaTest,P.map=M.map,P.clipShadows=M.clipShadows,P.clippingPlanes=M.clippingPlanes,P.clipIntersection=M.clipIntersection,P.displacementMap=M.displacementMap,P.displacementScale=M.displacementScale,P.displacementBias=M.displacementBias,P.wireframeLinewidth=M.wireframeLinewidth,P.linewidth=M.linewidth,C.isPointLight===!0&&P.isMeshDistanceMaterial===!0){const U=t.properties.get(P);U.light=C}return P}function k(A,M,C,j,P){if(A.visible===!1)return;if(A.layers.test(M.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&P===Mu)&&(!A.frustumCulled||r.intersectsObject(A))){A.modelViewMatrix.multiplyMatrices(C.matrixWorldInverse,A.matrixWorld);const L=e.update(A),B=A.material;if(Array.isArray(B)){const D=L.groups;for(let $=0,G=D.length;$<G;$++){const z=D[$],W=B[z.materialIndex];if(W&&W.visible){const X=N(A,W,j,P);A.onBeforeShadow(t,A,M,C,L,X,z),t.renderBufferDirect(C,null,L,X,A,z),A.onAfterShadow(t,A,M,C,L,X,z)}}}else if(B.visible){const D=N(A,B,j,P);A.onBeforeShadow(t,A,M,C,L,D,null),t.renderBufferDirect(C,null,L,D,A,null),A.onAfterShadow(t,A,M,C,L,D,null)}}const U=A.children;for(let L=0,B=U.length;L<B;L++)k(U[L],M,C,j,P)}}function PAe(t,e,n){const r=n.isWebGL2;function a(){let De=!1;const We=new Or;let Ae=null;const Re=new Or(0,0,0,0);return{setMask:function($e){Ae!==$e&&!De&&(t.colorMask($e,$e,$e,$e),Ae=$e)},setLocked:function($e){De=$e},setClear:function($e,ht,At,Dt,It){It===!0&&($e*=Dt,ht*=Dt,At*=Dt),We.set($e,ht,At,Dt),Re.equals(We)===!1&&(t.clearColor($e,ht,At,Dt),Re.copy(We))},reset:function(){De=!1,Ae=null,Re.set(-1,0,0,0)}}}function s(){let De=!1,We=null,Ae=null,Re=null;return{setTest:function($e){$e?he(t.DEPTH_TEST):oe(t.DEPTH_TEST)},setMask:function($e){We!==$e&&!De&&(t.depthMask($e),We=$e)},setFunc:function($e){if(Ae!==$e){switch($e){case BSe:t.depthFunc(t.NEVER);break;case HSe:t.depthFunc(t.ALWAYS);break;case $Se:t.depthFunc(t.LESS);break;case j1:t.depthFunc(t.LEQUAL);break;case VSe:t.depthFunc(t.EQUAL);break;case qSe:t.depthFunc(t.GEQUAL);break;case GSe:t.depthFunc(t.GREATER);break;case WSe:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}Ae=$e}},setLocked:function($e){De=$e},setClear:function($e){Re!==$e&&(t.clearDepth($e),Re=$e)},reset:function(){De=!1,We=null,Ae=null,Re=null}}}function o(){let De=!1,We=null,Ae=null,Re=null,$e=null,ht=null,At=null,Dt=null,It=null;return{setTest:function(kt){De||(kt?he(t.STENCIL_TEST):oe(t.STENCIL_TEST))},setMask:function(kt){We!==kt&&!De&&(t.stencilMask(kt),We=kt)},setFunc:function(kt,Ue,bt){(Ae!==kt||Re!==Ue||$e!==bt)&&(t.stencilFunc(kt,Ue,bt),Ae=kt,Re=Ue,$e=bt)},setOp:function(kt,Ue,bt){(ht!==kt||At!==Ue||Dt!==bt)&&(t.stencilOp(kt,Ue,bt),ht=kt,At=Ue,Dt=bt)},setLocked:function(kt){De=kt},setClear:function(kt){It!==kt&&(t.clearStencil(kt),It=kt)},reset:function(){De=!1,We=null,Ae=null,Re=null,$e=null,ht=null,At=null,Dt=null,It=null}}}const l=new a,c=new s,u=new o,d=new WeakMap,h=new WeakMap;let f={},p={},x=new WeakMap,v=[],g=null,y=!1,_=null,N=null,k=null,A=null,M=null,C=null,j=null,P=new dn(0,0,0),E=0,U=!1,L=null,B=null,D=null,$=null,G=null;const z=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let W=!1,X=0;const ae=t.getParameter(t.VERSION);ae.indexOf("WebGL")!==-1?(X=parseFloat(/^WebGL (\d)/.exec(ae)[1]),W=X>=1):ae.indexOf("OpenGL ES")!==-1&&(X=parseFloat(/^OpenGL ES (\d)/.exec(ae)[1]),W=X>=2);let H=null,K={};const te=t.getParameter(t.SCISSOR_BOX),Z=t.getParameter(t.VIEWPORT),ve=new Or().fromArray(te),ce=new Or().fromArray(Z);function ee(De,We,Ae,Re){const $e=new Uint8Array(4),ht=t.createTexture();t.bindTexture(De,ht),t.texParameteri(De,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(De,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let At=0;At<Ae;At++)r&&(De===t.TEXTURE_3D||De===t.TEXTURE_2D_ARRAY)?t.texImage3D(We,0,t.RGBA,1,1,Re,0,t.RGBA,t.UNSIGNED_BYTE,$e):t.texImage2D(We+At,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,$e);return ht}const je={};je[t.TEXTURE_2D]=ee(t.TEXTURE_2D,t.TEXTURE_2D,1),je[t.TEXTURE_CUBE_MAP]=ee(t.TEXTURE_CUBE_MAP,t.TEXTURE_CUBE_MAP_POSITIVE_X,6),r&&(je[t.TEXTURE_2D_ARRAY]=ee(t.TEXTURE_2D_ARRAY,t.TEXTURE_2D_ARRAY,1,1),je[t.TEXTURE_3D]=ee(t.TEXTURE_3D,t.TEXTURE_3D,1,1)),l.setClear(0,0,0,1),c.setClear(1),u.setClear(0),he(t.DEPTH_TEST),c.setFunc(j1),se(!1),de(n6),he(t.CULL_FACE),me(Fh);function he(De){f[De]!==!0&&(t.enable(De),f[De]=!0)}function oe(De){f[De]!==!1&&(t.disable(De),f[De]=!1)}function _e(De,We){return p[De]!==We?(t.bindFramebuffer(De,We),p[De]=We,r&&(De===t.DRAW_FRAMEBUFFER&&(p[t.FRAMEBUFFER]=We),De===t.FRAMEBUFFER&&(p[t.DRAW_FRAMEBUFFER]=We)),!0):!1}function ie(De,We){let Ae=v,Re=!1;if(De)if(Ae=x.get(We),Ae===void 0&&(Ae=[],x.set(We,Ae)),De.isWebGLMultipleRenderTargets){const $e=De.texture;if(Ae.length!==$e.length||Ae[0]!==t.COLOR_ATTACHMENT0){for(let ht=0,At=$e.length;ht<At;ht++)Ae[ht]=t.COLOR_ATTACHMENT0+ht;Ae.length=$e.length,Re=!0}}else Ae[0]!==t.COLOR_ATTACHMENT0&&(Ae[0]=t.COLOR_ATTACHMENT0,Re=!0);else Ae[0]!==t.BACK&&(Ae[0]=t.BACK,Re=!0);Re&&(n.isWebGL2?t.drawBuffers(Ae):e.get("WEBGL_draw_buffers").drawBuffersWEBGL(Ae))}function ze(De){return g!==De?(t.useProgram(De),g=De,!0):!1}const V={[Km]:t.FUNC_ADD,[kSe]:t.FUNC_SUBTRACT,[ASe]:t.FUNC_REVERSE_SUBTRACT};if(r)V[s6]=t.MIN,V[o6]=t.MAX;else{const De=e.get("EXT_blend_minmax");De!==null&&(V[s6]=De.MIN_EXT,V[o6]=De.MAX_EXT)}const Y={[TSe]:t.ZERO,[MSe]:t.ONE,[PSe]:t.SRC_COLOR,[nD]:t.SRC_ALPHA,[LSe]:t.SRC_ALPHA_SATURATE,[RSe]:t.DST_COLOR,[jSe]:t.DST_ALPHA,[ESe]:t.ONE_MINUS_SRC_COLOR,[rD]:t.ONE_MINUS_SRC_ALPHA,[FSe]:t.ONE_MINUS_DST_COLOR,[DSe]:t.ONE_MINUS_DST_ALPHA,[OSe]:t.CONSTANT_COLOR,[ISe]:t.ONE_MINUS_CONSTANT_COLOR,[zSe]:t.CONSTANT_ALPHA,[USe]:t.ONE_MINUS_CONSTANT_ALPHA};function me(De,We,Ae,Re,$e,ht,At,Dt,It,kt){if(De===Fh){y===!0&&(oe(t.BLEND),y=!1);return}if(y===!1&&(he(t.BLEND),y=!0),De!==CSe){if(De!==_||kt!==U){if((N!==Km||M!==Km)&&(t.blendEquation(t.FUNC_ADD),N=Km,M=Km),kt)switch(De){case Zg:t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case r6:t.blendFunc(t.ONE,t.ONE);break;case a6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case i6:t.blendFuncSeparate(t.ZERO,t.SRC_COLOR,t.ZERO,t.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",De);break}else switch(De){case Zg:t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA);break;case r6:t.blendFunc(t.SRC_ALPHA,t.ONE);break;case a6:t.blendFuncSeparate(t.ZERO,t.ONE_MINUS_SRC_COLOR,t.ZERO,t.ONE);break;case i6:t.blendFunc(t.ZERO,t.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",De);break}k=null,A=null,C=null,j=null,P.set(0,0,0),E=0,_=De,U=kt}return}$e=$e||We,ht=ht||Ae,At=At||Re,(We!==N||$e!==M)&&(t.blendEquationSeparate(V[We],V[$e]),N=We,M=$e),(Ae!==k||Re!==A||ht!==C||At!==j)&&(t.blendFuncSeparate(Y[Ae],Y[Re],Y[ht],Y[At]),k=Ae,A=Re,C=ht,j=At),(Dt.equals(P)===!1||It!==E)&&(t.blendColor(Dt.r,Dt.g,Dt.b,It),P.copy(Dt),E=It),_=De,U=!1}function Q(De,We){De.side===Du?oe(t.CULL_FACE):he(t.CULL_FACE);let Ae=De.side===no;We&&(Ae=!Ae),se(Ae),De.blending===Zg&&De.transparent===!1?me(Fh):me(De.blending,De.blendEquation,De.blendSrc,De.blendDst,De.blendEquationAlpha,De.blendSrcAlpha,De.blendDstAlpha,De.blendColor,De.blendAlpha,De.premultipliedAlpha),c.setFunc(De.depthFunc),c.setTest(De.depthTest),c.setMask(De.depthWrite),l.setMask(De.colorWrite);const Re=De.stencilWrite;u.setTest(Re),Re&&(u.setMask(De.stencilWriteMask),u.setFunc(De.stencilFunc,De.stencilRef,De.stencilFuncMask),u.setOp(De.stencilFail,De.stencilZFail,De.stencilZPass)),Ne(De.polygonOffset,De.polygonOffsetFactor,De.polygonOffsetUnits),De.alphaToCoverage===!0?he(t.SAMPLE_ALPHA_TO_COVERAGE):oe(t.SAMPLE_ALPHA_TO_COVERAGE)}function se(De){L!==De&&(De?t.frontFace(t.CW):t.frontFace(t.CCW),L=De)}function de(De){De!==SSe?(he(t.CULL_FACE),De!==B&&(De===n6?t.cullFace(t.BACK):De===_Se?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):oe(t.CULL_FACE),B=De}function Le(De){De!==D&&(W&&t.lineWidth(De),D=De)}function Ne(De,We,Ae){De?(he(t.POLYGON_OFFSET_FILL),($!==We||G!==Ae)&&(t.polygonOffset(We,Ae),$=We,G=Ae)):oe(t.POLYGON_OFFSET_FILL)}function be(De){De?he(t.SCISSOR_TEST):oe(t.SCISSOR_TEST)}function O(De){De===void 0&&(De=t.TEXTURE0+z-1),H!==De&&(t.activeTexture(De),H=De)}function R(De,We,Ae){Ae===void 0&&(H===null?Ae=t.TEXTURE0+z-1:Ae=H);let Re=K[Ae];Re===void 0&&(Re={type:void 0,texture:void 0},K[Ae]=Re),(Re.type!==De||Re.texture!==We)&&(H!==Ae&&(t.activeTexture(Ae),H=Ae),t.bindTexture(De,We||je[De]),Re.type=De,Re.texture=We)}function q(){const De=K[H];De!==void 0&&De.type!==void 0&&(t.bindTexture(De.type,null),De.type=void 0,De.texture=void 0)}function J(){try{t.compressedTexImage2D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function fe(){try{t.compressedTexImage3D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function le(){try{t.texSubImage2D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function Be(){try{t.texSubImage3D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function Ie(){try{t.compressedTexSubImage2D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function Ke(){try{t.compressedTexSubImage3D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function Oe(){try{t.texStorage2D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function pe(){try{t.texStorage3D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function xe(){try{t.texImage2D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function ke(){try{t.texImage3D.apply(t,arguments)}catch(De){console.error("THREE.WebGLState:",De)}}function ge(De){ve.equals(De)===!1&&(t.scissor(De.x,De.y,De.z,De.w),ve.copy(De))}function we(De){ce.equals(De)===!1&&(t.viewport(De.x,De.y,De.z,De.w),ce.copy(De))}function qe(De,We){let Ae=h.get(We);Ae===void 0&&(Ae=new WeakMap,h.set(We,Ae));let Re=Ae.get(De);Re===void 0&&(Re=t.getUniformBlockIndex(We,De.name),Ae.set(De,Re))}function Ee(De,We){const Re=h.get(We).get(De);d.get(We)!==Re&&(t.uniformBlockBinding(We,Re,De.__bindingPointIndex),d.set(We,Re))}function tt(){t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SCISSOR_TEST),t.disable(t.STENCIL_TEST),t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.blendFuncSeparate(t.ONE,t.ZERO,t.ONE,t.ZERO),t.blendColor(0,0,0,0),t.colorMask(!0,!0,!0,!0),t.clearColor(0,0,0,0),t.depthMask(!0),t.depthFunc(t.LESS),t.clearDepth(1),t.stencilMask(4294967295),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.clearStencil(0),t.cullFace(t.BACK),t.frontFace(t.CCW),t.polygonOffset(0,0),t.activeTexture(t.TEXTURE0),t.bindFramebuffer(t.FRAMEBUFFER,null),r===!0&&(t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindFramebuffer(t.READ_FRAMEBUFFER,null)),t.useProgram(null),t.lineWidth(1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.viewport(0,0,t.canvas.width,t.canvas.height),f={},H=null,K={},p={},x=new WeakMap,v=[],g=null,y=!1,_=null,N=null,k=null,A=null,M=null,C=null,j=null,P=new dn(0,0,0),E=0,U=!1,L=null,B=null,D=null,$=null,G=null,ve.set(0,0,t.canvas.width,t.canvas.height),ce.set(0,0,t.canvas.width,t.canvas.height),l.reset(),c.reset(),u.reset()}return{buffers:{color:l,depth:c,stencil:u},enable:he,disable:oe,bindFramebuffer:_e,drawBuffers:ie,useProgram:ze,setBlending:me,setMaterial:Q,setFlipSided:se,setCullFace:de,setLineWidth:Le,setPolygonOffset:Ne,setScissorTest:be,activeTexture:O,bindTexture:R,unbindTexture:q,compressedTexImage2D:J,compressedTexImage3D:fe,texImage2D:xe,texImage3D:ke,updateUBOMapping:qe,uniformBlockBinding:Ee,texStorage2D:Oe,texStorage3D:pe,texSubImage2D:le,texSubImage3D:Be,compressedTexSubImage2D:Ie,compressedTexSubImage3D:Ke,scissor:ge,viewport:we,reset:tt}}function EAe(t,e,n,r,a,s,o){const l=a.isWebGL2,c=a.maxTextures,u=a.maxCubemapSize,d=a.maxTextureSize,h=a.maxSamples,f=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,p=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),x=new WeakMap;let v;const g=new WeakMap;let y=!1;try{y=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(O,R){return y?new OffscreenCanvas(O,R):O1("canvas")}function N(O,R,q,J){let fe=1;if((O.width>J||O.height>J)&&(fe=J/Math.max(O.width,O.height)),fe<1||R===!0)if(typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&O instanceof ImageBitmap){const le=R?L1:Math.floor,Be=le(fe*O.width),Ie=le(fe*O.height);v===void 0&&(v=_(Be,Ie));const Ke=q?_(Be,Ie):v;return Ke.width=Be,Ke.height=Ie,Ke.getContext("2d").drawImage(O,0,0,Be,Ie),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+O.width+"x"+O.height+") to ("+Be+"x"+Ie+")."),Ke}else return"data"in O&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+O.width+"x"+O.height+")."),O;return O}function k(O){return uD(O.width)&&uD(O.height)}function A(O){return l?!1:O.wrapS!==Ul||O.wrapT!==Ul||O.minFilter!==Xi&&O.minFilter!==ol}function M(O,R){return O.generateMipmaps&&R&&O.minFilter!==Xi&&O.minFilter!==ol}function C(O){t.generateMipmap(O)}function j(O,R,q,J,fe=!1){if(l===!1)return R;if(O!==null){if(t[O]!==void 0)return t[O];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+O+"'")}let le=R;if(R===t.RED&&(q===t.FLOAT&&(le=t.R32F),q===t.HALF_FLOAT&&(le=t.R16F),q===t.UNSIGNED_BYTE&&(le=t.R8)),R===t.RED_INTEGER&&(q===t.UNSIGNED_BYTE&&(le=t.R8UI),q===t.UNSIGNED_SHORT&&(le=t.R16UI),q===t.UNSIGNED_INT&&(le=t.R32UI),q===t.BYTE&&(le=t.R8I),q===t.SHORT&&(le=t.R16I),q===t.INT&&(le=t.R32I)),R===t.RG&&(q===t.FLOAT&&(le=t.RG32F),q===t.HALF_FLOAT&&(le=t.RG16F),q===t.UNSIGNED_BYTE&&(le=t.RG8)),R===t.RGBA){const Be=fe?D1:Fr.getTransfer(J);q===t.FLOAT&&(le=t.RGBA32F),q===t.HALF_FLOAT&&(le=t.RGBA16F),q===t.UNSIGNED_BYTE&&(le=Be===ea?t.SRGB8_ALPHA8:t.RGBA8),q===t.UNSIGNED_SHORT_4_4_4_4&&(le=t.RGBA4),q===t.UNSIGNED_SHORT_5_5_5_1&&(le=t.RGB5_A1)}return(le===t.R16F||le===t.R32F||le===t.RG16F||le===t.RG32F||le===t.RGBA16F||le===t.RGBA32F)&&e.get("EXT_color_buffer_float"),le}function P(O,R,q){return M(O,q)===!0||O.isFramebufferTexture&&O.minFilter!==Xi&&O.minFilter!==ol?Math.log2(Math.max(R.width,R.height))+1:O.mipmaps!==void 0&&O.mipmaps.length>0?O.mipmaps.length:O.isCompressedTexture&&Array.isArray(O.image)?R.mipmaps.length:1}function E(O){return O===Xi||O===l6||O===wP?t.NEAREST:t.LINEAR}function U(O){const R=O.target;R.removeEventListener("dispose",U),B(R),R.isVideoTexture&&x.delete(R)}function L(O){const R=O.target;R.removeEventListener("dispose",L),$(R)}function B(O){const R=r.get(O);if(R.__webglInit===void 0)return;const q=O.source,J=g.get(q);if(J){const fe=J[R.__cacheKey];fe.usedTimes--,fe.usedTimes===0&&D(O),Object.keys(J).length===0&&g.delete(q)}r.remove(O)}function D(O){const R=r.get(O);t.deleteTexture(R.__webglTexture);const q=O.source,J=g.get(q);delete J[R.__cacheKey],o.memory.textures--}function $(O){const R=O.texture,q=r.get(O),J=r.get(R);if(J.__webglTexture!==void 0&&(t.deleteTexture(J.__webglTexture),o.memory.textures--),O.depthTexture&&O.depthTexture.dispose(),O.isWebGLCubeRenderTarget)for(let fe=0;fe<6;fe++){if(Array.isArray(q.__webglFramebuffer[fe]))for(let le=0;le<q.__webglFramebuffer[fe].length;le++)t.deleteFramebuffer(q.__webglFramebuffer[fe][le]);else t.deleteFramebuffer(q.__webglFramebuffer[fe]);q.__webglDepthbuffer&&t.deleteRenderbuffer(q.__webglDepthbuffer[fe])}else{if(Array.isArray(q.__webglFramebuffer))for(let fe=0;fe<q.__webglFramebuffer.length;fe++)t.deleteFramebuffer(q.__webglFramebuffer[fe]);else t.deleteFramebuffer(q.__webglFramebuffer);if(q.__webglDepthbuffer&&t.deleteRenderbuffer(q.__webglDepthbuffer),q.__webglMultisampledFramebuffer&&t.deleteFramebuffer(q.__webglMultisampledFramebuffer),q.__webglColorRenderbuffer)for(let fe=0;fe<q.__webglColorRenderbuffer.length;fe++)q.__webglColorRenderbuffer[fe]&&t.deleteRenderbuffer(q.__webglColorRenderbuffer[fe]);q.__webglDepthRenderbuffer&&t.deleteRenderbuffer(q.__webglDepthRenderbuffer)}if(O.isWebGLMultipleRenderTargets)for(let fe=0,le=R.length;fe<le;fe++){const Be=r.get(R[fe]);Be.__webglTexture&&(t.deleteTexture(Be.__webglTexture),o.memory.textures--),r.remove(R[fe])}r.remove(R),r.remove(O)}let G=0;function z(){G=0}function W(){const O=G;return O>=c&&console.warn("THREE.WebGLTextures: Trying to use "+O+" texture units while this GPU supports only "+c),G+=1,O}function X(O){const R=[];return R.push(O.wrapS),R.push(O.wrapT),R.push(O.wrapR||0),R.push(O.magFilter),R.push(O.minFilter),R.push(O.anisotropy),R.push(O.internalFormat),R.push(O.format),R.push(O.type),R.push(O.generateMipmaps),R.push(O.premultiplyAlpha),R.push(O.flipY),R.push(O.unpackAlignment),R.push(O.colorSpace),R.join()}function ae(O,R){const q=r.get(O);if(O.isVideoTexture&&Ne(O),O.isRenderTargetTexture===!1&&O.version>0&&q.__version!==O.version){const J=O.image;if(J===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{he(q,O,R);return}}n.bindTexture(t.TEXTURE_2D,q.__webglTexture,t.TEXTURE0+R)}function H(O,R){const q=r.get(O);if(O.version>0&&q.__version!==O.version){he(q,O,R);return}n.bindTexture(t.TEXTURE_2D_ARRAY,q.__webglTexture,t.TEXTURE0+R)}function K(O,R){const q=r.get(O);if(O.version>0&&q.__version!==O.version){he(q,O,R);return}n.bindTexture(t.TEXTURE_3D,q.__webglTexture,t.TEXTURE0+R)}function te(O,R){const q=r.get(O);if(O.version>0&&q.__version!==O.version){oe(q,O,R);return}n.bindTexture(t.TEXTURE_CUBE_MAP,q.__webglTexture,t.TEXTURE0+R)}const Z={[sD]:t.REPEAT,[Ul]:t.CLAMP_TO_EDGE,[oD]:t.MIRRORED_REPEAT},ve={[Xi]:t.NEAREST,[l6]:t.NEAREST_MIPMAP_NEAREST,[wP]:t.NEAREST_MIPMAP_LINEAR,[ol]:t.LINEAR,[t_e]:t.LINEAR_MIPMAP_NEAREST,[Cv]:t.LINEAR_MIPMAP_LINEAR},ce={[m_e]:t.NEVER,[y_e]:t.ALWAYS,[f_e]:t.LESS,[PY]:t.LEQUAL,[p_e]:t.EQUAL,[x_e]:t.GEQUAL,[g_e]:t.GREATER,[b_e]:t.NOTEQUAL};function ee(O,R,q){if(q?(t.texParameteri(O,t.TEXTURE_WRAP_S,Z[R.wrapS]),t.texParameteri(O,t.TEXTURE_WRAP_T,Z[R.wrapT]),(O===t.TEXTURE_3D||O===t.TEXTURE_2D_ARRAY)&&t.texParameteri(O,t.TEXTURE_WRAP_R,Z[R.wrapR]),t.texParameteri(O,t.TEXTURE_MAG_FILTER,ve[R.magFilter]),t.texParameteri(O,t.TEXTURE_MIN_FILTER,ve[R.minFilter])):(t.texParameteri(O,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(O,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),(O===t.TEXTURE_3D||O===t.TEXTURE_2D_ARRAY)&&t.texParameteri(O,t.TEXTURE_WRAP_R,t.CLAMP_TO_EDGE),(R.wrapS!==Ul||R.wrapT!==Ul)&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."),t.texParameteri(O,t.TEXTURE_MAG_FILTER,E(R.magFilter)),t.texParameteri(O,t.TEXTURE_MIN_FILTER,E(R.minFilter)),R.minFilter!==Xi&&R.minFilter!==ol&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.")),R.compareFunction&&(t.texParameteri(O,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(O,t.TEXTURE_COMPARE_FUNC,ce[R.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){const J=e.get("EXT_texture_filter_anisotropic");if(R.magFilter===Xi||R.minFilter!==wP&&R.minFilter!==Cv||R.type===zu&&e.has("OES_texture_float_linear")===!1||l===!1&&R.type===kv&&e.has("OES_texture_half_float_linear")===!1)return;(R.anisotropy>1||r.get(R).__currentAnisotropy)&&(t.texParameterf(O,J.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(R.anisotropy,a.getMaxAnisotropy())),r.get(R).__currentAnisotropy=R.anisotropy)}}function je(O,R){let q=!1;O.__webglInit===void 0&&(O.__webglInit=!0,R.addEventListener("dispose",U));const J=R.source;let fe=g.get(J);fe===void 0&&(fe={},g.set(J,fe));const le=X(R);if(le!==O.__cacheKey){fe[le]===void 0&&(fe[le]={texture:t.createTexture(),usedTimes:0},o.memory.textures++,q=!0),fe[le].usedTimes++;const Be=fe[O.__cacheKey];Be!==void 0&&(fe[O.__cacheKey].usedTimes--,Be.usedTimes===0&&D(R)),O.__cacheKey=le,O.__webglTexture=fe[le].texture}return q}function he(O,R,q){let J=t.TEXTURE_2D;(R.isDataArrayTexture||R.isCompressedArrayTexture)&&(J=t.TEXTURE_2D_ARRAY),R.isData3DTexture&&(J=t.TEXTURE_3D);const fe=je(O,R),le=R.source;n.bindTexture(J,O.__webglTexture,t.TEXTURE0+q);const Be=r.get(le);if(le.version!==Be.__version||fe===!0){n.activeTexture(t.TEXTURE0+q);const Ie=Fr.getPrimaries(Fr.workingColorSpace),Ke=R.colorSpace===cl?null:Fr.getPrimaries(R.colorSpace),Oe=R.colorSpace===cl||Ie===Ke?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Oe);const pe=A(R)&&k(R.image)===!1;let xe=N(R.image,pe,!1,d);xe=be(R,xe);const ke=k(xe)||l,ge=s.convert(R.format,R.colorSpace);let we=s.convert(R.type),qe=j(R.internalFormat,ge,we,R.colorSpace,R.isVideoTexture);ee(J,R,ke);let Ee;const tt=R.mipmaps,De=l&&R.isVideoTexture!==!0&&qe!==AY,We=Be.__version===void 0||fe===!0,Ae=P(R,xe,ke);if(R.isDepthTexture)qe=t.DEPTH_COMPONENT,l?R.type===zu?qe=t.DEPTH_COMPONENT32F:R.type===wh?qe=t.DEPTH_COMPONENT24:R.type===mf?qe=t.DEPTH24_STENCIL8:qe=t.DEPTH_COMPONENT16:R.type===zu&&console.error("WebGLRenderer: Floating point depth texture requires WebGL2."),R.format===ff&&qe===t.DEPTH_COMPONENT&&R.type!==ZF&&R.type!==wh&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),R.type=wh,we=s.convert(R.type)),R.format===wb&&qe===t.DEPTH_COMPONENT&&(qe=t.DEPTH_STENCIL,R.type!==mf&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),R.type=mf,we=s.convert(R.type))),We&&(De?n.texStorage2D(t.TEXTURE_2D,1,qe,xe.width,xe.height):n.texImage2D(t.TEXTURE_2D,0,qe,xe.width,xe.height,0,ge,we,null));else if(R.isDataTexture)if(tt.length>0&&ke){De&&We&&n.texStorage2D(t.TEXTURE_2D,Ae,qe,tt[0].width,tt[0].height);for(let Re=0,$e=tt.length;Re<$e;Re++)Ee=tt[Re],De?n.texSubImage2D(t.TEXTURE_2D,Re,0,0,Ee.width,Ee.height,ge,we,Ee.data):n.texImage2D(t.TEXTURE_2D,Re,qe,Ee.width,Ee.height,0,ge,we,Ee.data);R.generateMipmaps=!1}else De?(We&&n.texStorage2D(t.TEXTURE_2D,Ae,qe,xe.width,xe.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,xe.width,xe.height,ge,we,xe.data)):n.texImage2D(t.TEXTURE_2D,0,qe,xe.width,xe.height,0,ge,we,xe.data);else if(R.isCompressedTexture)if(R.isCompressedArrayTexture){De&&We&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ae,qe,tt[0].width,tt[0].height,xe.depth);for(let Re=0,$e=tt.length;Re<$e;Re++)Ee=tt[Re],R.format!==ll?ge!==null?De?n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,Re,0,0,0,Ee.width,Ee.height,xe.depth,ge,Ee.data,0,0):n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,Re,qe,Ee.width,Ee.height,xe.depth,0,Ee.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):De?n.texSubImage3D(t.TEXTURE_2D_ARRAY,Re,0,0,0,Ee.width,Ee.height,xe.depth,ge,we,Ee.data):n.texImage3D(t.TEXTURE_2D_ARRAY,Re,qe,Ee.width,Ee.height,xe.depth,0,ge,we,Ee.data)}else{De&&We&&n.texStorage2D(t.TEXTURE_2D,Ae,qe,tt[0].width,tt[0].height);for(let Re=0,$e=tt.length;Re<$e;Re++)Ee=tt[Re],R.format!==ll?ge!==null?De?n.compressedTexSubImage2D(t.TEXTURE_2D,Re,0,0,Ee.width,Ee.height,ge,Ee.data):n.compressedTexImage2D(t.TEXTURE_2D,Re,qe,Ee.width,Ee.height,0,Ee.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):De?n.texSubImage2D(t.TEXTURE_2D,Re,0,0,Ee.width,Ee.height,ge,we,Ee.data):n.texImage2D(t.TEXTURE_2D,Re,qe,Ee.width,Ee.height,0,ge,we,Ee.data)}else if(R.isDataArrayTexture)De?(We&&n.texStorage3D(t.TEXTURE_2D_ARRAY,Ae,qe,xe.width,xe.height,xe.depth),n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,xe.width,xe.height,xe.depth,ge,we,xe.data)):n.texImage3D(t.TEXTURE_2D_ARRAY,0,qe,xe.width,xe.height,xe.depth,0,ge,we,xe.data);else if(R.isData3DTexture)De?(We&&n.texStorage3D(t.TEXTURE_3D,Ae,qe,xe.width,xe.height,xe.depth),n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,xe.width,xe.height,xe.depth,ge,we,xe.data)):n.texImage3D(t.TEXTURE_3D,0,qe,xe.width,xe.height,xe.depth,0,ge,we,xe.data);else if(R.isFramebufferTexture){if(We)if(De)n.texStorage2D(t.TEXTURE_2D,Ae,qe,xe.width,xe.height);else{let Re=xe.width,$e=xe.height;for(let ht=0;ht<Ae;ht++)n.texImage2D(t.TEXTURE_2D,ht,qe,Re,$e,0,ge,we,null),Re>>=1,$e>>=1}}else if(tt.length>0&&ke){De&&We&&n.texStorage2D(t.TEXTURE_2D,Ae,qe,tt[0].width,tt[0].height);for(let Re=0,$e=tt.length;Re<$e;Re++)Ee=tt[Re],De?n.texSubImage2D(t.TEXTURE_2D,Re,0,0,ge,we,Ee):n.texImage2D(t.TEXTURE_2D,Re,qe,ge,we,Ee);R.generateMipmaps=!1}else De?(We&&n.texStorage2D(t.TEXTURE_2D,Ae,qe,xe.width,xe.height),n.texSubImage2D(t.TEXTURE_2D,0,0,0,ge,we,xe)):n.texImage2D(t.TEXTURE_2D,0,qe,ge,we,xe);M(R,ke)&&C(J),Be.__version=le.version,R.onUpdate&&R.onUpdate(R)}O.__version=R.version}function oe(O,R,q){if(R.image.length!==6)return;const J=je(O,R),fe=R.source;n.bindTexture(t.TEXTURE_CUBE_MAP,O.__webglTexture,t.TEXTURE0+q);const le=r.get(fe);if(fe.version!==le.__version||J===!0){n.activeTexture(t.TEXTURE0+q);const Be=Fr.getPrimaries(Fr.workingColorSpace),Ie=R.colorSpace===cl?null:Fr.getPrimaries(R.colorSpace),Ke=R.colorSpace===cl||Be===Ie?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,R.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,R.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,R.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ke);const Oe=R.isCompressedTexture||R.image[0].isCompressedTexture,pe=R.image[0]&&R.image[0].isDataTexture,xe=[];for(let Re=0;Re<6;Re++)!Oe&&!pe?xe[Re]=N(R.image[Re],!1,!0,u):xe[Re]=pe?R.image[Re].image:R.image[Re],xe[Re]=be(R,xe[Re]);const ke=xe[0],ge=k(ke)||l,we=s.convert(R.format,R.colorSpace),qe=s.convert(R.type),Ee=j(R.internalFormat,we,qe,R.colorSpace),tt=l&&R.isVideoTexture!==!0,De=le.__version===void 0||J===!0;let We=P(R,ke,ge);ee(t.TEXTURE_CUBE_MAP,R,ge);let Ae;if(Oe){tt&&De&&n.texStorage2D(t.TEXTURE_CUBE_MAP,We,Ee,ke.width,ke.height);for(let Re=0;Re<6;Re++){Ae=xe[Re].mipmaps;for(let $e=0;$e<Ae.length;$e++){const ht=Ae[$e];R.format!==ll?we!==null?tt?n.compressedTexSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,0,0,ht.width,ht.height,we,ht.data):n.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,Ee,ht.width,ht.height,0,ht.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):tt?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,0,0,ht.width,ht.height,we,qe,ht.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e,Ee,ht.width,ht.height,0,we,qe,ht.data)}}}else{Ae=R.mipmaps,tt&&De&&(Ae.length>0&&We++,n.texStorage2D(t.TEXTURE_CUBE_MAP,We,Ee,xe[0].width,xe[0].height));for(let Re=0;Re<6;Re++)if(pe){tt?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,0,0,xe[Re].width,xe[Re].height,we,qe,xe[Re].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,Ee,xe[Re].width,xe[Re].height,0,we,qe,xe[Re].data);for(let $e=0;$e<Ae.length;$e++){const At=Ae[$e].image[Re].image;tt?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,0,0,At.width,At.height,we,qe,At.data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,Ee,At.width,At.height,0,we,qe,At.data)}}else{tt?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,0,0,we,qe,xe[Re]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,0,Ee,we,qe,xe[Re]);for(let $e=0;$e<Ae.length;$e++){const ht=Ae[$e];tt?n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,0,0,we,qe,ht.image[Re]):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+Re,$e+1,Ee,we,qe,ht.image[Re])}}}M(R,ge)&&C(t.TEXTURE_CUBE_MAP),le.__version=fe.version,R.onUpdate&&R.onUpdate(R)}O.__version=R.version}function _e(O,R,q,J,fe,le){const Be=s.convert(q.format,q.colorSpace),Ie=s.convert(q.type),Ke=j(q.internalFormat,Be,Ie,q.colorSpace);if(!r.get(R).__hasExternalTextures){const pe=Math.max(1,R.width>>le),xe=Math.max(1,R.height>>le);fe===t.TEXTURE_3D||fe===t.TEXTURE_2D_ARRAY?n.texImage3D(fe,le,Ke,pe,xe,R.depth,0,Be,Ie,null):n.texImage2D(fe,le,Ke,pe,xe,0,Be,Ie,null)}n.bindFramebuffer(t.FRAMEBUFFER,O),Le(R)?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,J,fe,r.get(q).__webglTexture,0,de(R)):(fe===t.TEXTURE_2D||fe>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&fe<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,J,fe,r.get(q).__webglTexture,le),n.bindFramebuffer(t.FRAMEBUFFER,null)}function ie(O,R,q){if(t.bindRenderbuffer(t.RENDERBUFFER,O),R.depthBuffer&&!R.stencilBuffer){let J=l===!0?t.DEPTH_COMPONENT24:t.DEPTH_COMPONENT16;if(q||Le(R)){const fe=R.depthTexture;fe&&fe.isDepthTexture&&(fe.type===zu?J=t.DEPTH_COMPONENT32F:fe.type===wh&&(J=t.DEPTH_COMPONENT24));const le=de(R);Le(R)?f.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,le,J,R.width,R.height):t.renderbufferStorageMultisample(t.RENDERBUFFER,le,J,R.width,R.height)}else t.renderbufferStorage(t.RENDERBUFFER,J,R.width,R.height);t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,O)}else if(R.depthBuffer&&R.stencilBuffer){const J=de(R);q&&Le(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,J,t.DEPTH24_STENCIL8,R.width,R.height):Le(R)?f.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,J,t.DEPTH24_STENCIL8,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,R.width,R.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,O)}else{const J=R.isWebGLMultipleRenderTargets===!0?R.texture:[R.texture];for(let fe=0;fe<J.length;fe++){const le=J[fe],Be=s.convert(le.format,le.colorSpace),Ie=s.convert(le.type),Ke=j(le.internalFormat,Be,Ie,le.colorSpace),Oe=de(R);q&&Le(R)===!1?t.renderbufferStorageMultisample(t.RENDERBUFFER,Oe,Ke,R.width,R.height):Le(R)?f.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,Oe,Ke,R.width,R.height):t.renderbufferStorage(t.RENDERBUFFER,Ke,R.width,R.height)}}t.bindRenderbuffer(t.RENDERBUFFER,null)}function ze(O,R){if(R&&R.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,O),!(R.depthTexture&&R.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!r.get(R.depthTexture).__webglTexture||R.depthTexture.image.width!==R.width||R.depthTexture.image.height!==R.height)&&(R.depthTexture.image.width=R.width,R.depthTexture.image.height=R.height,R.depthTexture.needsUpdate=!0),ae(R.depthTexture,0);const J=r.get(R.depthTexture).__webglTexture,fe=de(R);if(R.depthTexture.format===ff)Le(R)?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,J,0,fe):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,J,0);else if(R.depthTexture.format===wb)Le(R)?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,J,0,fe):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,J,0);else throw new Error("Unknown depthTexture format")}function V(O){const R=r.get(O),q=O.isWebGLCubeRenderTarget===!0;if(O.depthTexture&&!R.__autoAllocateDepthBuffer){if(q)throw new Error("target.depthTexture not supported in Cube render targets");ze(R.__webglFramebuffer,O)}else if(q){R.__webglDepthbuffer=[];for(let J=0;J<6;J++)n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer[J]),R.__webglDepthbuffer[J]=t.createRenderbuffer(),ie(R.__webglDepthbuffer[J],O,!1)}else n.bindFramebuffer(t.FRAMEBUFFER,R.__webglFramebuffer),R.__webglDepthbuffer=t.createRenderbuffer(),ie(R.__webglDepthbuffer,O,!1);n.bindFramebuffer(t.FRAMEBUFFER,null)}function Y(O,R,q){const J=r.get(O);R!==void 0&&_e(J.__webglFramebuffer,O,O.texture,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,0),q!==void 0&&V(O)}function me(O){const R=O.texture,q=r.get(O),J=r.get(R);O.addEventListener("dispose",L),O.isWebGLMultipleRenderTargets!==!0&&(J.__webglTexture===void 0&&(J.__webglTexture=t.createTexture()),J.__version=R.version,o.memory.textures++);const fe=O.isWebGLCubeRenderTarget===!0,le=O.isWebGLMultipleRenderTargets===!0,Be=k(O)||l;if(fe){q.__webglFramebuffer=[];for(let Ie=0;Ie<6;Ie++)if(l&&R.mipmaps&&R.mipmaps.length>0){q.__webglFramebuffer[Ie]=[];for(let Ke=0;Ke<R.mipmaps.length;Ke++)q.__webglFramebuffer[Ie][Ke]=t.createFramebuffer()}else q.__webglFramebuffer[Ie]=t.createFramebuffer()}else{if(l&&R.mipmaps&&R.mipmaps.length>0){q.__webglFramebuffer=[];for(let Ie=0;Ie<R.mipmaps.length;Ie++)q.__webglFramebuffer[Ie]=t.createFramebuffer()}else q.__webglFramebuffer=t.createFramebuffer();if(le)if(a.drawBuffers){const Ie=O.texture;for(let Ke=0,Oe=Ie.length;Ke<Oe;Ke++){const pe=r.get(Ie[Ke]);pe.__webglTexture===void 0&&(pe.__webglTexture=t.createTexture(),o.memory.textures++)}}else console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.");if(l&&O.samples>0&&Le(O)===!1){const Ie=le?R:[R];q.__webglMultisampledFramebuffer=t.createFramebuffer(),q.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,q.__webglMultisampledFramebuffer);for(let Ke=0;Ke<Ie.length;Ke++){const Oe=Ie[Ke];q.__webglColorRenderbuffer[Ke]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,q.__webglColorRenderbuffer[Ke]);const pe=s.convert(Oe.format,Oe.colorSpace),xe=s.convert(Oe.type),ke=j(Oe.internalFormat,pe,xe,Oe.colorSpace,O.isXRRenderTarget===!0),ge=de(O);t.renderbufferStorageMultisample(t.RENDERBUFFER,ge,ke,O.width,O.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Ke,t.RENDERBUFFER,q.__webglColorRenderbuffer[Ke])}t.bindRenderbuffer(t.RENDERBUFFER,null),O.depthBuffer&&(q.__webglDepthRenderbuffer=t.createRenderbuffer(),ie(q.__webglDepthRenderbuffer,O,!0)),n.bindFramebuffer(t.FRAMEBUFFER,null)}}if(fe){n.bindTexture(t.TEXTURE_CUBE_MAP,J.__webglTexture),ee(t.TEXTURE_CUBE_MAP,R,Be);for(let Ie=0;Ie<6;Ie++)if(l&&R.mipmaps&&R.mipmaps.length>0)for(let Ke=0;Ke<R.mipmaps.length;Ke++)_e(q.__webglFramebuffer[Ie][Ke],O,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,Ke);else _e(q.__webglFramebuffer[Ie],O,R,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0);M(R,Be)&&C(t.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(le){const Ie=O.texture;for(let Ke=0,Oe=Ie.length;Ke<Oe;Ke++){const pe=Ie[Ke],xe=r.get(pe);n.bindTexture(t.TEXTURE_2D,xe.__webglTexture),ee(t.TEXTURE_2D,pe,Be),_e(q.__webglFramebuffer,O,pe,t.COLOR_ATTACHMENT0+Ke,t.TEXTURE_2D,0),M(pe,Be)&&C(t.TEXTURE_2D)}n.unbindTexture()}else{let Ie=t.TEXTURE_2D;if((O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(l?Ie=O.isWebGL3DRenderTarget?t.TEXTURE_3D:t.TEXTURE_2D_ARRAY:console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.")),n.bindTexture(Ie,J.__webglTexture),ee(Ie,R,Be),l&&R.mipmaps&&R.mipmaps.length>0)for(let Ke=0;Ke<R.mipmaps.length;Ke++)_e(q.__webglFramebuffer[Ke],O,R,t.COLOR_ATTACHMENT0,Ie,Ke);else _e(q.__webglFramebuffer,O,R,t.COLOR_ATTACHMENT0,Ie,0);M(R,Be)&&C(Ie),n.unbindTexture()}O.depthBuffer&&V(O)}function Q(O){const R=k(O)||l,q=O.isWebGLMultipleRenderTargets===!0?O.texture:[O.texture];for(let J=0,fe=q.length;J<fe;J++){const le=q[J];if(M(le,R)){const Be=O.isWebGLCubeRenderTarget?t.TEXTURE_CUBE_MAP:t.TEXTURE_2D,Ie=r.get(le).__webglTexture;n.bindTexture(Be,Ie),C(Be),n.unbindTexture()}}}function se(O){if(l&&O.samples>0&&Le(O)===!1){const R=O.isWebGLMultipleRenderTargets?O.texture:[O.texture],q=O.width,J=O.height;let fe=t.COLOR_BUFFER_BIT;const le=[],Be=O.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,Ie=r.get(O),Ke=O.isWebGLMultipleRenderTargets===!0;if(Ke)for(let Oe=0;Oe<R.length;Oe++)n.bindFramebuffer(t.FRAMEBUFFER,Ie.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.RENDERBUFFER,null),n.bindFramebuffer(t.FRAMEBUFFER,Ie.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.TEXTURE_2D,null,0);n.bindFramebuffer(t.READ_FRAMEBUFFER,Ie.__webglMultisampledFramebuffer),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ie.__webglFramebuffer);for(let Oe=0;Oe<R.length;Oe++){le.push(t.COLOR_ATTACHMENT0+Oe),O.depthBuffer&&le.push(Be);const pe=Ie.__ignoreDepthValues!==void 0?Ie.__ignoreDepthValues:!1;if(pe===!1&&(O.depthBuffer&&(fe|=t.DEPTH_BUFFER_BIT),O.stencilBuffer&&(fe|=t.STENCIL_BUFFER_BIT)),Ke&&t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,Ie.__webglColorRenderbuffer[Oe]),pe===!0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,[Be]),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,[Be])),Ke){const xe=r.get(R[Oe]).__webglTexture;t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,xe,0)}t.blitFramebuffer(0,0,q,J,0,0,q,J,fe,t.NEAREST),p&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,le)}if(n.bindFramebuffer(t.READ_FRAMEBUFFER,null),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),Ke)for(let Oe=0;Oe<R.length;Oe++){n.bindFramebuffer(t.FRAMEBUFFER,Ie.__webglMultisampledFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.RENDERBUFFER,Ie.__webglColorRenderbuffer[Oe]);const pe=r.get(R[Oe]).__webglTexture;n.bindFramebuffer(t.FRAMEBUFFER,Ie.__webglFramebuffer),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+Oe,t.TEXTURE_2D,pe,0)}n.bindFramebuffer(t.DRAW_FRAMEBUFFER,Ie.__webglMultisampledFramebuffer)}}function de(O){return Math.min(h,O.samples)}function Le(O){const R=r.get(O);return l&&O.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&R.__useRenderToTexture!==!1}function Ne(O){const R=o.render.frame;x.get(O)!==R&&(x.set(O,R),O.update())}function be(O,R){const q=O.colorSpace,J=O.format,fe=O.type;return O.isCompressedTexture===!0||O.isVideoTexture===!0||O.format===cD||q!==id&&q!==cl&&(Fr.getTransfer(q)===ea?l===!1?e.has("EXT_sRGB")===!0&&J===ll?(O.format=cD,O.minFilter=ol,O.generateMipmaps=!1):R=DY.sRGBToLinear(R):(J!==ll||fe!==Oh)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",q)),R}this.allocateTextureUnit=W,this.resetTextureUnits=z,this.setTexture2D=ae,this.setTexture2DArray=H,this.setTexture3D=K,this.setTextureCube=te,this.rebindTextures=Y,this.setupRenderTarget=me,this.updateRenderTargetMipmap=Q,this.updateMultisampleRenderTarget=se,this.setupDepthRenderbuffer=V,this.setupFrameBufferTexture=_e,this.useMultisampledRTT=Le}function jAe(t,e,n){const r=n.isWebGL2;function a(s,o=cl){let l;const c=Fr.getTransfer(o);if(s===Oh)return t.UNSIGNED_BYTE;if(s===SY)return t.UNSIGNED_SHORT_4_4_4_4;if(s===_Y)return t.UNSIGNED_SHORT_5_5_5_1;if(s===n_e)return t.BYTE;if(s===r_e)return t.SHORT;if(s===ZF)return t.UNSIGNED_SHORT;if(s===wY)return t.INT;if(s===wh)return t.UNSIGNED_INT;if(s===zu)return t.FLOAT;if(s===kv)return r?t.HALF_FLOAT:(l=e.get("OES_texture_half_float"),l!==null?l.HALF_FLOAT_OES:null);if(s===a_e)return t.ALPHA;if(s===ll)return t.RGBA;if(s===i_e)return t.LUMINANCE;if(s===s_e)return t.LUMINANCE_ALPHA;if(s===ff)return t.DEPTH_COMPONENT;if(s===wb)return t.DEPTH_STENCIL;if(s===cD)return l=e.get("EXT_sRGB"),l!==null?l.SRGB_ALPHA_EXT:null;if(s===o_e)return t.RED;if(s===NY)return t.RED_INTEGER;if(s===l_e)return t.RG;if(s===CY)return t.RG_INTEGER;if(s===kY)return t.RGBA_INTEGER;if(s===SP||s===_P||s===NP||s===CP)if(c===ea)if(l=e.get("WEBGL_compressed_texture_s3tc_srgb"),l!==null){if(s===SP)return l.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(s===_P)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(s===NP)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(s===CP)return l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(l=e.get("WEBGL_compressed_texture_s3tc"),l!==null){if(s===SP)return l.COMPRESSED_RGB_S3TC_DXT1_EXT;if(s===_P)return l.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(s===NP)return l.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(s===CP)return l.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(s===c6||s===u6||s===d6||s===h6)if(l=e.get("WEBGL_compressed_texture_pvrtc"),l!==null){if(s===c6)return l.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(s===u6)return l.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(s===d6)return l.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(s===h6)return l.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(s===AY)return l=e.get("WEBGL_compressed_texture_etc1"),l!==null?l.COMPRESSED_RGB_ETC1_WEBGL:null;if(s===m6||s===f6)if(l=e.get("WEBGL_compressed_texture_etc"),l!==null){if(s===m6)return c===ea?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(s===f6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(s===p6||s===g6||s===b6||s===x6||s===y6||s===v6||s===w6||s===S6||s===_6||s===N6||s===C6||s===k6||s===A6||s===T6)if(l=e.get("WEBGL_compressed_texture_astc"),l!==null){if(s===p6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:l.COMPRESSED_RGBA_ASTC_4x4_KHR;if(s===g6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:l.COMPRESSED_RGBA_ASTC_5x4_KHR;if(s===b6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:l.COMPRESSED_RGBA_ASTC_5x5_KHR;if(s===x6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:l.COMPRESSED_RGBA_ASTC_6x5_KHR;if(s===y6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:l.COMPRESSED_RGBA_ASTC_6x6_KHR;if(s===v6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:l.COMPRESSED_RGBA_ASTC_8x5_KHR;if(s===w6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:l.COMPRESSED_RGBA_ASTC_8x6_KHR;if(s===S6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:l.COMPRESSED_RGBA_ASTC_8x8_KHR;if(s===_6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:l.COMPRESSED_RGBA_ASTC_10x5_KHR;if(s===N6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:l.COMPRESSED_RGBA_ASTC_10x6_KHR;if(s===C6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:l.COMPRESSED_RGBA_ASTC_10x8_KHR;if(s===k6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:l.COMPRESSED_RGBA_ASTC_10x10_KHR;if(s===A6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:l.COMPRESSED_RGBA_ASTC_12x10_KHR;if(s===T6)return c===ea?l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:l.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(s===kP||s===M6||s===P6)if(l=e.get("EXT_texture_compression_bptc"),l!==null){if(s===kP)return c===ea?l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:l.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(s===M6)return l.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(s===P6)return l.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(s===c_e||s===E6||s===j6||s===D6)if(l=e.get("EXT_texture_compression_rgtc"),l!==null){if(s===kP)return l.COMPRESSED_RED_RGTC1_EXT;if(s===E6)return l.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(s===j6)return l.COMPRESSED_RED_GREEN_RGTC2_EXT;if(s===D6)return l.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return s===mf?r?t.UNSIGNED_INT_24_8:(l=e.get("WEBGL_depth_texture"),l!==null?l.UNSIGNED_INT_24_8_WEBGL:null):t[s]!==void 0?t[s]:null}return{convert:a}}class DAe extends Ao{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class My extends Rs{constructor(){super(),this.isGroup=!0,this.type="Group"}}const RAe={type:"move"};class XP{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new My,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new My,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ze,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ze),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new My,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ze,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ze),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const n=this._hand;if(n)for(const r of e.hand.values())this._getHandJoint(n,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,n,r){let a=null,s=null,o=null;const l=this._targetRay,c=this._grip,u=this._hand;if(e&&n.session.visibilityState!=="visible-blurred"){if(u&&e.hand){o=!0;for(const v of e.hand.values()){const g=n.getJointPose(v,r),y=this._getHandJoint(u,v);g!==null&&(y.matrix.fromArray(g.transform.matrix),y.matrix.decompose(y.position,y.rotation,y.scale),y.matrixWorldNeedsUpdate=!0,y.jointRadius=g.radius),y.visible=g!==null}const d=u.joints["index-finger-tip"],h=u.joints["thumb-tip"],f=d.position.distanceTo(h.position),p=.02,x=.005;u.inputState.pinching&&f>p+x?(u.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!u.inputState.pinching&&f<=p-x&&(u.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=n.getPose(e.gripSpace,r),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));l!==null&&(a=n.getPose(e.targetRaySpace,r),a===null&&s!==null&&(a=s),a!==null&&(l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,a.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(a.linearVelocity)):l.hasLinearVelocity=!1,a.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(a.angularVelocity)):l.hasAngularVelocity=!1,this.dispatchEvent(RAe)))}return l!==null&&(l.visible=a!==null),c!==null&&(c.visible=s!==null),u!==null&&(u.visible=o!==null),this}_getHandJoint(e,n){if(e.joints[n.jointName]===void 0){const r=new My;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[n.jointName]=r,e.add(r)}return e.joints[n.jointName]}}class FAe extends rp{constructor(e,n){super();const r=this;let a=null,s=1,o=null,l="local-floor",c=1,u=null,d=null,h=null,f=null,p=null,x=null;const v=n.getContextAttributes();let g=null,y=null;const _=[],N=[],k=new _n;let A=null;const M=new Ao;M.layers.enable(1),M.viewport=new Or;const C=new Ao;C.layers.enable(2),C.viewport=new Or;const j=[M,C],P=new DAe;P.layers.enable(1),P.layers.enable(2);let E=null,U=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(te){let Z=_[te];return Z===void 0&&(Z=new XP,_[te]=Z),Z.getTargetRaySpace()},this.getControllerGrip=function(te){let Z=_[te];return Z===void 0&&(Z=new XP,_[te]=Z),Z.getGripSpace()},this.getHand=function(te){let Z=_[te];return Z===void 0&&(Z=new XP,_[te]=Z),Z.getHandSpace()};function L(te){const Z=N.indexOf(te.inputSource);if(Z===-1)return;const ve=_[Z];ve!==void 0&&(ve.update(te.inputSource,te.frame,u||o),ve.dispatchEvent({type:te.type,data:te.inputSource}))}function B(){a.removeEventListener("select",L),a.removeEventListener("selectstart",L),a.removeEventListener("selectend",L),a.removeEventListener("squeeze",L),a.removeEventListener("squeezestart",L),a.removeEventListener("squeezeend",L),a.removeEventListener("end",B),a.removeEventListener("inputsourceschange",D);for(let te=0;te<_.length;te++){const Z=N[te];Z!==null&&(N[te]=null,_[te].disconnect(Z))}E=null,U=null,e.setRenderTarget(g),p=null,f=null,h=null,a=null,y=null,K.stop(),r.isPresenting=!1,e.setPixelRatio(A),e.setSize(k.width,k.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(te){s=te,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(te){l=te,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return u||o},this.setReferenceSpace=function(te){u=te},this.getBaseLayer=function(){return f!==null?f:p},this.getBinding=function(){return h},this.getFrame=function(){return x},this.getSession=function(){return a},this.setSession=async function(te){if(a=te,a!==null){if(g=e.getRenderTarget(),a.addEventListener("select",L),a.addEventListener("selectstart",L),a.addEventListener("selectend",L),a.addEventListener("squeeze",L),a.addEventListener("squeezestart",L),a.addEventListener("squeezeend",L),a.addEventListener("end",B),a.addEventListener("inputsourceschange",D),v.xrCompatible!==!0&&await n.makeXRCompatible(),A=e.getPixelRatio(),e.getSize(k),a.renderState.layers===void 0||e.capabilities.isWebGL2===!1){const Z={antialias:a.renderState.layers===void 0?v.antialias:!0,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(a,n,Z),a.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),y=new If(p.framebufferWidth,p.framebufferHeight,{format:ll,type:Oh,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil})}else{let Z=null,ve=null,ce=null;v.depth&&(ce=v.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,Z=v.stencil?wb:ff,ve=v.stencil?mf:wh);const ee={colorFormat:n.RGBA8,depthFormat:ce,scaleFactor:s};h=new XRWebGLBinding(a,n),f=h.createProjectionLayer(ee),a.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),y=new If(f.textureWidth,f.textureHeight,{format:ll,type:Oh,depthTexture:new qY(f.textureWidth,f.textureHeight,ve,void 0,void 0,void 0,void 0,void 0,void 0,Z),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0});const je=e.properties.get(y);je.__ignoreDepthValues=f.ignoreDepthValues}y.isXRRenderTarget=!0,this.setFoveation(c),u=null,o=await a.requestReferenceSpace(l),K.setContext(a),K.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode};function D(te){for(let Z=0;Z<te.removed.length;Z++){const ve=te.removed[Z],ce=N.indexOf(ve);ce>=0&&(N[ce]=null,_[ce].disconnect(ve))}for(let Z=0;Z<te.added.length;Z++){const ve=te.added[Z];let ce=N.indexOf(ve);if(ce===-1){for(let je=0;je<_.length;je++)if(je>=N.length){N.push(ve),ce=je;break}else if(N[je]===null){N[je]=ve,ce=je;break}if(ce===-1)break}const ee=_[ce];ee&&ee.connect(ve)}}const $=new Ze,G=new Ze;function z(te,Z,ve){$.setFromMatrixPosition(Z.matrixWorld),G.setFromMatrixPosition(ve.matrixWorld);const ce=$.distanceTo(G),ee=Z.projectionMatrix.elements,je=ve.projectionMatrix.elements,he=ee[14]/(ee[10]-1),oe=ee[14]/(ee[10]+1),_e=(ee[9]+1)/ee[5],ie=(ee[9]-1)/ee[5],ze=(ee[8]-1)/ee[0],V=(je[8]+1)/je[0],Y=he*ze,me=he*V,Q=ce/(-ze+V),se=Q*-ze;Z.matrixWorld.decompose(te.position,te.quaternion,te.scale),te.translateX(se),te.translateZ(Q),te.matrixWorld.compose(te.position,te.quaternion,te.scale),te.matrixWorldInverse.copy(te.matrixWorld).invert();const de=he+Q,Le=oe+Q,Ne=Y-se,be=me+(ce-se),O=_e*oe/Le*de,R=ie*oe/Le*de;te.projectionMatrix.makePerspective(Ne,be,O,R,de,Le),te.projectionMatrixInverse.copy(te.projectionMatrix).invert()}function W(te,Z){Z===null?te.matrixWorld.copy(te.matrix):te.matrixWorld.multiplyMatrices(Z.matrixWorld,te.matrix),te.matrixWorldInverse.copy(te.matrixWorld).invert()}this.updateCamera=function(te){if(a===null)return;P.near=C.near=M.near=te.near,P.far=C.far=M.far=te.far,(E!==P.near||U!==P.far)&&(a.updateRenderState({depthNear:P.near,depthFar:P.far}),E=P.near,U=P.far);const Z=te.parent,ve=P.cameras;W(P,Z);for(let ce=0;ce<ve.length;ce++)W(ve[ce],Z);ve.length===2?z(P,M,C):P.projectionMatrix.copy(M.projectionMatrix),X(te,P,Z)};function X(te,Z,ve){ve===null?te.matrix.copy(Z.matrixWorld):(te.matrix.copy(ve.matrixWorld),te.matrix.invert(),te.matrix.multiply(Z.matrixWorld)),te.matrix.decompose(te.position,te.quaternion,te.scale),te.updateMatrixWorld(!0),te.projectionMatrix.copy(Z.projectionMatrix),te.projectionMatrixInverse.copy(Z.projectionMatrixInverse),te.isPerspectiveCamera&&(te.fov=Tv*2*Math.atan(1/te.projectionMatrix.elements[5]),te.zoom=1)}this.getCamera=function(){return P},this.getFoveation=function(){if(!(f===null&&p===null))return c},this.setFoveation=function(te){c=te,f!==null&&(f.fixedFoveation=te),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=te)};let ae=null;function H(te,Z){if(d=Z.getViewerPose(u||o),x=Z,d!==null){const ve=d.views;p!==null&&(e.setRenderTargetFramebuffer(y,p.framebuffer),e.setRenderTarget(y));let ce=!1;ve.length!==P.cameras.length&&(P.cameras.length=0,ce=!0);for(let ee=0;ee<ve.length;ee++){const je=ve[ee];let he=null;if(p!==null)he=p.getViewport(je);else{const _e=h.getViewSubImage(f,je);he=_e.viewport,ee===0&&(e.setRenderTargetTextures(y,_e.colorTexture,f.ignoreDepthValues?void 0:_e.depthStencilTexture),e.setRenderTarget(y))}let oe=j[ee];oe===void 0&&(oe=new Ao,oe.layers.enable(ee),oe.viewport=new Or,j[ee]=oe),oe.matrix.fromArray(je.transform.matrix),oe.matrix.decompose(oe.position,oe.quaternion,oe.scale),oe.projectionMatrix.fromArray(je.projectionMatrix),oe.projectionMatrixInverse.copy(oe.projectionMatrix).invert(),oe.viewport.set(he.x,he.y,he.width,he.height),ee===0&&(P.matrix.copy(oe.matrix),P.matrix.decompose(P.position,P.quaternion,P.scale)),ce===!0&&P.cameras.push(oe)}}for(let ve=0;ve<_.length;ve++){const ce=N[ve],ee=_[ve];ce!==null&&ee!==void 0&&ee.update(ce,Z,u||o)}ae&&ae(te,Z),Z.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:Z}),x=null}const K=new VY;K.setAnimationLoop(H),this.setAnimationLoop=function(te){ae=te},this.dispose=function(){}}}function LAe(t,e){function n(g,y){g.matrixAutoUpdate===!0&&g.updateMatrix(),y.value.copy(g.matrix)}function r(g,y){y.color.getRGB(g.fogColor.value,BY(t)),y.isFog?(g.fogNear.value=y.near,g.fogFar.value=y.far):y.isFogExp2&&(g.fogDensity.value=y.density)}function a(g,y,_,N,k){y.isMeshBasicMaterial||y.isMeshLambertMaterial?s(g,y):y.isMeshToonMaterial?(s(g,y),h(g,y)):y.isMeshPhongMaterial?(s(g,y),d(g,y)):y.isMeshStandardMaterial?(s(g,y),f(g,y),y.isMeshPhysicalMaterial&&p(g,y,k)):y.isMeshMatcapMaterial?(s(g,y),x(g,y)):y.isMeshDepthMaterial?s(g,y):y.isMeshDistanceMaterial?(s(g,y),v(g,y)):y.isMeshNormalMaterial?s(g,y):y.isLineBasicMaterial?(o(g,y),y.isLineDashedMaterial&&l(g,y)):y.isPointsMaterial?c(g,y,_,N):y.isSpriteMaterial?u(g,y):y.isShadowMaterial?(g.color.value.copy(y.color),g.opacity.value=y.opacity):y.isShaderMaterial&&(y.uniformsNeedUpdate=!1)}function s(g,y){g.opacity.value=y.opacity,y.color&&g.diffuse.value.copy(y.color),y.emissive&&g.emissive.value.copy(y.emissive).multiplyScalar(y.emissiveIntensity),y.map&&(g.map.value=y.map,n(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.bumpMap&&(g.bumpMap.value=y.bumpMap,n(y.bumpMap,g.bumpMapTransform),g.bumpScale.value=y.bumpScale,y.side===no&&(g.bumpScale.value*=-1)),y.normalMap&&(g.normalMap.value=y.normalMap,n(y.normalMap,g.normalMapTransform),g.normalScale.value.copy(y.normalScale),y.side===no&&g.normalScale.value.negate()),y.displacementMap&&(g.displacementMap.value=y.displacementMap,n(y.displacementMap,g.displacementMapTransform),g.displacementScale.value=y.displacementScale,g.displacementBias.value=y.displacementBias),y.emissiveMap&&(g.emissiveMap.value=y.emissiveMap,n(y.emissiveMap,g.emissiveMapTransform)),y.specularMap&&(g.specularMap.value=y.specularMap,n(y.specularMap,g.specularMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest);const _=e.get(y).envMap;if(_&&(g.envMap.value=_,g.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=y.reflectivity,g.ior.value=y.ior,g.refractionRatio.value=y.refractionRatio),y.lightMap){g.lightMap.value=y.lightMap;const N=t._useLegacyLights===!0?Math.PI:1;g.lightMapIntensity.value=y.lightMapIntensity*N,n(y.lightMap,g.lightMapTransform)}y.aoMap&&(g.aoMap.value=y.aoMap,g.aoMapIntensity.value=y.aoMapIntensity,n(y.aoMap,g.aoMapTransform))}function o(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,y.map&&(g.map.value=y.map,n(y.map,g.mapTransform))}function l(g,y){g.dashSize.value=y.dashSize,g.totalSize.value=y.dashSize+y.gapSize,g.scale.value=y.scale}function c(g,y,_,N){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.size.value=y.size*_,g.scale.value=N*.5,y.map&&(g.map.value=y.map,n(y.map,g.uvTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function u(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.rotation.value=y.rotation,y.map&&(g.map.value=y.map,n(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,n(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function d(g,y){g.specular.value.copy(y.specular),g.shininess.value=Math.max(y.shininess,1e-4)}function h(g,y){y.gradientMap&&(g.gradientMap.value=y.gradientMap)}function f(g,y){g.metalness.value=y.metalness,y.metalnessMap&&(g.metalnessMap.value=y.metalnessMap,n(y.metalnessMap,g.metalnessMapTransform)),g.roughness.value=y.roughness,y.roughnessMap&&(g.roughnessMap.value=y.roughnessMap,n(y.roughnessMap,g.roughnessMapTransform)),e.get(y).envMap&&(g.envMapIntensity.value=y.envMapIntensity)}function p(g,y,_){g.ior.value=y.ior,y.sheen>0&&(g.sheenColor.value.copy(y.sheenColor).multiplyScalar(y.sheen),g.sheenRoughness.value=y.sheenRoughness,y.sheenColorMap&&(g.sheenColorMap.value=y.sheenColorMap,n(y.sheenColorMap,g.sheenColorMapTransform)),y.sheenRoughnessMap&&(g.sheenRoughnessMap.value=y.sheenRoughnessMap,n(y.sheenRoughnessMap,g.sheenRoughnessMapTransform))),y.clearcoat>0&&(g.clearcoat.value=y.clearcoat,g.clearcoatRoughness.value=y.clearcoatRoughness,y.clearcoatMap&&(g.clearcoatMap.value=y.clearcoatMap,n(y.clearcoatMap,g.clearcoatMapTransform)),y.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=y.clearcoatRoughnessMap,n(y.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),y.clearcoatNormalMap&&(g.clearcoatNormalMap.value=y.clearcoatNormalMap,n(y.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(y.clearcoatNormalScale),y.side===no&&g.clearcoatNormalScale.value.negate())),y.iridescence>0&&(g.iridescence.value=y.iridescence,g.iridescenceIOR.value=y.iridescenceIOR,g.iridescenceThicknessMinimum.value=y.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=y.iridescenceThicknessRange[1],y.iridescenceMap&&(g.iridescenceMap.value=y.iridescenceMap,n(y.iridescenceMap,g.iridescenceMapTransform)),y.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=y.iridescenceThicknessMap,n(y.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),y.transmission>0&&(g.transmission.value=y.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),y.transmissionMap&&(g.transmissionMap.value=y.transmissionMap,n(y.transmissionMap,g.transmissionMapTransform)),g.thickness.value=y.thickness,y.thicknessMap&&(g.thicknessMap.value=y.thicknessMap,n(y.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=y.attenuationDistance,g.attenuationColor.value.copy(y.attenuationColor)),y.anisotropy>0&&(g.anisotropyVector.value.set(y.anisotropy*Math.cos(y.anisotropyRotation),y.anisotropy*Math.sin(y.anisotropyRotation)),y.anisotropyMap&&(g.anisotropyMap.value=y.anisotropyMap,n(y.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=y.specularIntensity,g.specularColor.value.copy(y.specularColor),y.specularColorMap&&(g.specularColorMap.value=y.specularColorMap,n(y.specularColorMap,g.specularColorMapTransform)),y.specularIntensityMap&&(g.specularIntensityMap.value=y.specularIntensityMap,n(y.specularIntensityMap,g.specularIntensityMapTransform))}function x(g,y){y.matcap&&(g.matcap.value=y.matcap)}function v(g,y){const _=e.get(y).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:a}}function OAe(t,e,n,r){let a={},s={},o=[];const l=n.isWebGL2?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0;function c(_,N){const k=N.program;r.uniformBlockBinding(_,k)}function u(_,N){let k=a[_.id];k===void 0&&(x(_),k=d(_),a[_.id]=k,_.addEventListener("dispose",g));const A=N.program;r.updateUBOMapping(_,A);const M=e.render.frame;s[_.id]!==M&&(f(_),s[_.id]=M)}function d(_){const N=h();_.__bindingPointIndex=N;const k=t.createBuffer(),A=_.__size,M=_.usage;return t.bindBuffer(t.UNIFORM_BUFFER,k),t.bufferData(t.UNIFORM_BUFFER,A,M),t.bindBuffer(t.UNIFORM_BUFFER,null),t.bindBufferBase(t.UNIFORM_BUFFER,N,k),k}function h(){for(let _=0;_<l;_++)if(o.indexOf(_)===-1)return o.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(_){const N=a[_.id],k=_.uniforms,A=_.__cache;t.bindBuffer(t.UNIFORM_BUFFER,N);for(let M=0,C=k.length;M<C;M++){const j=k[M];if(p(j,M,A)===!0){const P=j.__offset,E=Array.isArray(j.value)?j.value:[j.value];let U=0;for(let L=0;L<E.length;L++){const B=E[L],D=v(B);typeof B=="number"?(j.__data[0]=B,t.bufferSubData(t.UNIFORM_BUFFER,P+U,j.__data)):B.isMatrix3?(j.__data[0]=B.elements[0],j.__data[1]=B.elements[1],j.__data[2]=B.elements[2],j.__data[3]=B.elements[0],j.__data[4]=B.elements[3],j.__data[5]=B.elements[4],j.__data[6]=B.elements[5],j.__data[7]=B.elements[0],j.__data[8]=B.elements[6],j.__data[9]=B.elements[7],j.__data[10]=B.elements[8],j.__data[11]=B.elements[0]):(B.toArray(j.__data,U),U+=D.storage/Float32Array.BYTES_PER_ELEMENT)}t.bufferSubData(t.UNIFORM_BUFFER,P,j.__data)}}t.bindBuffer(t.UNIFORM_BUFFER,null)}function p(_,N,k){const A=_.value;if(k[N]===void 0){if(typeof A=="number")k[N]=A;else{const M=Array.isArray(A)?A:[A],C=[];for(let j=0;j<M.length;j++)C.push(M[j].clone());k[N]=C}return!0}else if(typeof A=="number"){if(k[N]!==A)return k[N]=A,!0}else{const M=Array.isArray(k[N])?k[N]:[k[N]],C=Array.isArray(A)?A:[A];for(let j=0;j<M.length;j++){const P=M[j];if(P.equals(C[j])===!1)return P.copy(C[j]),!0}}return!1}function x(_){const N=_.uniforms;let k=0;const A=16;let M=0;for(let C=0,j=N.length;C<j;C++){const P=N[C],E={boundary:0,storage:0},U=Array.isArray(P.value)?P.value:[P.value];for(let L=0,B=U.length;L<B;L++){const D=U[L],$=v(D);E.boundary+=$.boundary,E.storage+=$.storage}if(P.__data=new Float32Array(E.storage/Float32Array.BYTES_PER_ELEMENT),P.__offset=k,C>0){M=k%A;const L=A-M;M!==0&&L-E.boundary<0&&(k+=A-M,P.__offset=k)}k+=E.storage}return M=k%A,M>0&&(k+=A-M),_.__size=k,_.__cache={},this}function v(_){const N={boundary:0,storage:0};return typeof _=="number"?(N.boundary=4,N.storage=4):_.isVector2?(N.boundary=8,N.storage=8):_.isVector3||_.isColor?(N.boundary=16,N.storage=12):_.isVector4?(N.boundary=16,N.storage=16):_.isMatrix3?(N.boundary=48,N.storage=48):_.isMatrix4?(N.boundary=64,N.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),N}function g(_){const N=_.target;N.removeEventListener("dispose",g);const k=o.indexOf(N.__bindingPointIndex);o.splice(k,1),t.deleteBuffer(a[N.id]),delete a[N.id],delete s[N.id]}function y(){for(const _ in a)t.deleteBuffer(a[_]);o=[],a={},s={}}return{bind:c,update:u,dispose:y}}class hD{constructor(e={}){const{canvas:n=R_e(),context:r=null,depth:a=!0,stencil:s=!0,alpha:o=!1,antialias:l=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:u=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:h=!1}=e;this.isWebGLRenderer=!0;let f;r!==null?f=r.getContextAttributes().alpha:f=o;const p=new Uint32Array(4),x=new Int32Array(4);let v=null,g=null;const y=[],_=[];this.domElement=n,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Yi,this._useLegacyLights=!1,this.toneMapping=Lh,this.toneMappingExposure=1;const N=this;let k=!1,A=0,M=0,C=null,j=-1,P=null;const E=new Or,U=new Or;let L=null;const B=new dn(0);let D=0,$=n.width,G=n.height,z=1,W=null,X=null;const ae=new Or(0,0,$,G),H=new Or(0,0,$,G);let K=!1;const te=new ck;let Z=!1,ve=!1,ce=null;const ee=new Yr,je=new _n,he=new Ze,oe={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function _e(){return C===null?z:1}let ie=r;function ze(Fe,Se){for(let nt=0;nt<Fe.length;nt++){const ot=Fe[nt],Ge=n.getContext(ot,Se);if(Ge!==null)return Ge}return null}try{const Fe={alpha:!0,depth:a,stencil:s,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:u,powerPreference:d,failIfMajorPerformanceCaveat:h};if("setAttribute"in n&&n.setAttribute("data-engine",`three.js r${sk}`),n.addEventListener("webglcontextlost",tt,!1),n.addEventListener("webglcontextrestored",De,!1),n.addEventListener("webglcontextcreationerror",We,!1),ie===null){const Se=["webgl2","webgl","experimental-webgl"];if(N.isWebGL1Renderer===!0&&Se.shift(),ie=ze(Se,Fe),ie===null)throw ze(Se)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}typeof WebGLRenderingContext<"u"&&ie instanceof WebGLRenderingContext&&console.warn("THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163."),ie.getShaderPrecisionFormat===void 0&&(ie.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(Fe){throw console.error("THREE.WebGLRenderer: "+Fe.message),Fe}let V,Y,me,Q,se,de,Le,Ne,be,O,R,q,J,fe,le,Be,Ie,Ke,Oe,pe,xe,ke,ge,we;function qe(){V=new KCe(ie),Y=new BCe(ie,V,e),V.init(Y),ke=new jAe(ie,V,Y),me=new PAe(ie,V,Y),Q=new QCe(ie),se=new gAe,de=new EAe(ie,V,me,se,Y,ke,Q),Le=new $Ce(N),Ne=new WCe(N),be=new a1e(ie,Y),ge=new zCe(ie,V,be,Y),O=new XCe(ie,be,Q,ge),R=new tke(ie,O,be,Q),Oe=new eke(ie,Y,de),Be=new HCe(se),q=new pAe(N,Le,Ne,V,Y,ge,Be),J=new LAe(N,se),fe=new xAe,le=new NAe(V,Y),Ke=new ICe(N,Le,Ne,me,R,f,c),Ie=new MAe(N,R,Y),we=new OAe(ie,Q,Y,me),pe=new UCe(ie,V,Q,Y),xe=new YCe(ie,V,Q,Y),Q.programs=q.programs,N.capabilities=Y,N.extensions=V,N.properties=se,N.renderLists=fe,N.shadowMap=Ie,N.state=me,N.info=Q}qe();const Ee=new FAe(N,ie);this.xr=Ee,this.getContext=function(){return ie},this.getContextAttributes=function(){return ie.getContextAttributes()},this.forceContextLoss=function(){const Fe=V.get("WEBGL_lose_context");Fe&&Fe.loseContext()},this.forceContextRestore=function(){const Fe=V.get("WEBGL_lose_context");Fe&&Fe.restoreContext()},this.getPixelRatio=function(){return z},this.setPixelRatio=function(Fe){Fe!==void 0&&(z=Fe,this.setSize($,G,!1))},this.getSize=function(Fe){return Fe.set($,G)},this.setSize=function(Fe,Se,nt=!0){if(Ee.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}$=Fe,G=Se,n.width=Math.floor(Fe*z),n.height=Math.floor(Se*z),nt===!0&&(n.style.width=Fe+"px",n.style.height=Se+"px"),this.setViewport(0,0,Fe,Se)},this.getDrawingBufferSize=function(Fe){return Fe.set($*z,G*z).floor()},this.setDrawingBufferSize=function(Fe,Se,nt){$=Fe,G=Se,z=nt,n.width=Math.floor(Fe*nt),n.height=Math.floor(Se*nt),this.setViewport(0,0,Fe,Se)},this.getCurrentViewport=function(Fe){return Fe.copy(E)},this.getViewport=function(Fe){return Fe.copy(ae)},this.setViewport=function(Fe,Se,nt,ot){Fe.isVector4?ae.set(Fe.x,Fe.y,Fe.z,Fe.w):ae.set(Fe,Se,nt,ot),me.viewport(E.copy(ae).multiplyScalar(z).floor())},this.getScissor=function(Fe){return Fe.copy(H)},this.setScissor=function(Fe,Se,nt,ot){Fe.isVector4?H.set(Fe.x,Fe.y,Fe.z,Fe.w):H.set(Fe,Se,nt,ot),me.scissor(U.copy(H).multiplyScalar(z).floor())},this.getScissorTest=function(){return K},this.setScissorTest=function(Fe){me.setScissorTest(K=Fe)},this.setOpaqueSort=function(Fe){W=Fe},this.setTransparentSort=function(Fe){X=Fe},this.getClearColor=function(Fe){return Fe.copy(Ke.getClearColor())},this.setClearColor=function(){Ke.setClearColor.apply(Ke,arguments)},this.getClearAlpha=function(){return Ke.getClearAlpha()},this.setClearAlpha=function(){Ke.setClearAlpha.apply(Ke,arguments)},this.clear=function(Fe=!0,Se=!0,nt=!0){let ot=0;if(Fe){let Ge=!1;if(C!==null){const zt=C.texture.format;Ge=zt===kY||zt===CY||zt===NY}if(Ge){const zt=C.texture.type,ye=zt===Oh||zt===wh||zt===ZF||zt===mf||zt===SY||zt===_Y,He=Ke.getClearColor(),Ye=Ke.getClearAlpha(),Xe=He.r,Te=He.g,lt=He.b;ye?(p[0]=Xe,p[1]=Te,p[2]=lt,p[3]=Ye,ie.clearBufferuiv(ie.COLOR,0,p)):(x[0]=Xe,x[1]=Te,x[2]=lt,x[3]=Ye,ie.clearBufferiv(ie.COLOR,0,x))}else ot|=ie.COLOR_BUFFER_BIT}Se&&(ot|=ie.DEPTH_BUFFER_BIT),nt&&(ot|=ie.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ie.clear(ot)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){n.removeEventListener("webglcontextlost",tt,!1),n.removeEventListener("webglcontextrestored",De,!1),n.removeEventListener("webglcontextcreationerror",We,!1),fe.dispose(),le.dispose(),se.dispose(),Le.dispose(),Ne.dispose(),R.dispose(),ge.dispose(),we.dispose(),q.dispose(),Ee.dispose(),Ee.removeEventListener("sessionstart",It),Ee.removeEventListener("sessionend",kt),ce&&(ce.dispose(),ce=null),Ue.stop()};function tt(Fe){Fe.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),k=!0}function De(){console.log("THREE.WebGLRenderer: Context Restored."),k=!1;const Fe=Q.autoReset,Se=Ie.enabled,nt=Ie.autoUpdate,ot=Ie.needsUpdate,Ge=Ie.type;qe(),Q.autoReset=Fe,Ie.enabled=Se,Ie.autoUpdate=nt,Ie.needsUpdate=ot,Ie.type=Ge}function We(Fe){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",Fe.statusMessage)}function Ae(Fe){const Se=Fe.target;Se.removeEventListener("dispose",Ae),Re(Se)}function Re(Fe){$e(Fe),se.remove(Fe)}function $e(Fe){const Se=se.get(Fe).programs;Se!==void 0&&(Se.forEach(function(nt){q.releaseProgram(nt)}),Fe.isShaderMaterial&&q.releaseShaderCache(Fe))}this.renderBufferDirect=function(Fe,Se,nt,ot,Ge,zt){Se===null&&(Se=oe);const ye=Ge.isMesh&&Ge.matrixWorld.determinant()<0,He=dr(Fe,Se,nt,ot,Ge);me.setMaterial(ot,ye);let Ye=nt.index,Xe=1;if(ot.wireframe===!0){if(Ye=O.getWireframeAttribute(nt),Ye===void 0)return;Xe=2}const Te=nt.drawRange,lt=nt.attributes.position;let pt=Te.start*Xe,at=(Te.start+Te.count)*Xe;zt!==null&&(pt=Math.max(pt,zt.start*Xe),at=Math.min(at,(zt.start+zt.count)*Xe)),Ye!==null?(pt=Math.max(pt,0),at=Math.min(at,Ye.count)):lt!=null&&(pt=Math.max(pt,0),at=Math.min(at,lt.count));const Tt=at-pt;if(Tt<0||Tt===1/0)return;ge.setup(Ge,ot,He,nt,Ye);let $t,Rt=pe;if(Ye!==null&&($t=be.get(Ye),Rt=xe,Rt.setIndex($t)),Ge.isMesh)ot.wireframe===!0?(me.setLineWidth(ot.wireframeLinewidth*_e()),Rt.setMode(ie.LINES)):Rt.setMode(ie.TRIANGLES);else if(Ge.isLine){let Pt=ot.linewidth;Pt===void 0&&(Pt=1),me.setLineWidth(Pt*_e()),Ge.isLineSegments?Rt.setMode(ie.LINES):Ge.isLineLoop?Rt.setMode(ie.LINE_LOOP):Rt.setMode(ie.LINE_STRIP)}else Ge.isPoints?Rt.setMode(ie.POINTS):Ge.isSprite&&Rt.setMode(ie.TRIANGLES);if(Ge.isBatchedMesh)Rt.renderMultiDraw(Ge._multiDrawStarts,Ge._multiDrawCounts,Ge._multiDrawCount);else if(Ge.isInstancedMesh)Rt.renderInstances(pt,Tt,Ge.count);else if(nt.isInstancedBufferGeometry){const Pt=nt._maxInstanceCount!==void 0?nt._maxInstanceCount:1/0,sn=Math.min(nt.instanceCount,Pt);Rt.renderInstances(pt,Tt,sn)}else Rt.render(pt,Tt)};function ht(Fe,Se,nt){Fe.transparent===!0&&Fe.side===Du&&Fe.forceSinglePass===!1?(Fe.side=no,Fe.needsUpdate=!0,Qn(Fe,Se,nt),Fe.side=Wh,Fe.needsUpdate=!0,Qn(Fe,Se,nt),Fe.side=Du):Qn(Fe,Se,nt)}this.compile=function(Fe,Se,nt=null){nt===null&&(nt=Fe),g=le.get(nt),g.init(),_.push(g),nt.traverseVisible(function(Ge){Ge.isLight&&Ge.layers.test(Se.layers)&&(g.pushLight(Ge),Ge.castShadow&&g.pushShadow(Ge))}),Fe!==nt&&Fe.traverseVisible(function(Ge){Ge.isLight&&Ge.layers.test(Se.layers)&&(g.pushLight(Ge),Ge.castShadow&&g.pushShadow(Ge))}),g.setupLights(N._useLegacyLights);const ot=new Set;return Fe.traverse(function(Ge){const zt=Ge.material;if(zt)if(Array.isArray(zt))for(let ye=0;ye<zt.length;ye++){const He=zt[ye];ht(He,nt,Ge),ot.add(He)}else ht(zt,nt,Ge),ot.add(zt)}),_.pop(),g=null,ot},this.compileAsync=function(Fe,Se,nt=null){const ot=this.compile(Fe,Se,nt);return new Promise(Ge=>{function zt(){if(ot.forEach(function(ye){se.get(ye).currentProgram.isReady()&&ot.delete(ye)}),ot.size===0){Ge(Fe);return}setTimeout(zt,10)}V.get("KHR_parallel_shader_compile")!==null?zt():setTimeout(zt,10)})};let At=null;function Dt(Fe){At&&At(Fe)}function It(){Ue.stop()}function kt(){Ue.start()}const Ue=new VY;Ue.setAnimationLoop(Dt),typeof self<"u"&&Ue.setContext(self),this.setAnimationLoop=function(Fe){At=Fe,Ee.setAnimationLoop(Fe),Fe===null?Ue.stop():Ue.start()},Ee.addEventListener("sessionstart",It),Ee.addEventListener("sessionend",kt),this.render=function(Fe,Se){if(Se!==void 0&&Se.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(k===!0)return;Fe.matrixWorldAutoUpdate===!0&&Fe.updateMatrixWorld(),Se.parent===null&&Se.matrixWorldAutoUpdate===!0&&Se.updateMatrixWorld(),Ee.enabled===!0&&Ee.isPresenting===!0&&(Ee.cameraAutoUpdate===!0&&Ee.updateCamera(Se),Se=Ee.getCamera()),Fe.isScene===!0&&Fe.onBeforeRender(N,Fe,Se,C),g=le.get(Fe,_.length),g.init(),_.push(g),ee.multiplyMatrices(Se.projectionMatrix,Se.matrixWorldInverse),te.setFromProjectionMatrix(ee),ve=this.localClippingEnabled,Z=Be.init(this.clippingPlanes,ve),v=fe.get(Fe,y.length),v.init(),y.push(v),bt(Fe,Se,0,N.sortObjects),v.finish(),N.sortObjects===!0&&v.sort(W,X),this.info.render.frame++,Z===!0&&Be.beginShadows();const nt=g.state.shadowsArray;if(Ie.render(nt,Fe,Se),Z===!0&&Be.endShadows(),this.info.autoReset===!0&&this.info.reset(),Ke.render(v,Fe),g.setupLights(N._useLegacyLights),Se.isArrayCamera){const ot=Se.cameras;for(let Ge=0,zt=ot.length;Ge<zt;Ge++){const ye=ot[Ge];yt(v,Fe,ye,ye.viewport)}}else yt(v,Fe,Se);C!==null&&(de.updateMultisampleRenderTarget(C),de.updateRenderTargetMipmap(C)),Fe.isScene===!0&&Fe.onAfterRender(N,Fe,Se),ge.resetDefaultState(),j=-1,P=null,_.pop(),_.length>0?g=_[_.length-1]:g=null,y.pop(),y.length>0?v=y[y.length-1]:v=null};function bt(Fe,Se,nt,ot){if(Fe.visible===!1)return;if(Fe.layers.test(Se.layers)){if(Fe.isGroup)nt=Fe.renderOrder;else if(Fe.isLOD)Fe.autoUpdate===!0&&Fe.update(Se);else if(Fe.isLight)g.pushLight(Fe),Fe.castShadow&&g.pushShadow(Fe);else if(Fe.isSprite){if(!Fe.frustumCulled||te.intersectsSprite(Fe)){ot&&he.setFromMatrixPosition(Fe.matrixWorld).applyMatrix4(ee);const ye=R.update(Fe),He=Fe.material;He.visible&&v.push(Fe,ye,He,nt,he.z,null)}}else if((Fe.isMesh||Fe.isLine||Fe.isPoints)&&(!Fe.frustumCulled||te.intersectsObject(Fe))){const ye=R.update(Fe),He=Fe.material;if(ot&&(Fe.boundingSphere!==void 0?(Fe.boundingSphere===null&&Fe.computeBoundingSphere(),he.copy(Fe.boundingSphere.center)):(ye.boundingSphere===null&&ye.computeBoundingSphere(),he.copy(ye.boundingSphere.center)),he.applyMatrix4(Fe.matrixWorld).applyMatrix4(ee)),Array.isArray(He)){const Ye=ye.groups;for(let Xe=0,Te=Ye.length;Xe<Te;Xe++){const lt=Ye[Xe],pt=He[lt.materialIndex];pt&&pt.visible&&v.push(Fe,ye,pt,nt,he.z,lt)}}else He.visible&&v.push(Fe,ye,He,nt,he.z,null)}}const zt=Fe.children;for(let ye=0,He=zt.length;ye<He;ye++)bt(zt[ye],Se,nt,ot)}function yt(Fe,Se,nt,ot){const Ge=Fe.opaque,zt=Fe.transmissive,ye=Fe.transparent;g.setupLightsView(nt),Z===!0&&Be.setGlobalState(N.clippingPlanes,nt),zt.length>0&&Gt(Ge,zt,Se,nt),ot&&me.viewport(E.copy(ot)),Ge.length>0&&Cn(Ge,Se,nt),zt.length>0&&Cn(zt,Se,nt),ye.length>0&&Cn(ye,Se,nt),me.buffers.depth.setTest(!0),me.buffers.depth.setMask(!0),me.buffers.color.setMask(!0),me.setPolygonOffset(!1)}function Gt(Fe,Se,nt,ot){if((nt.isScene===!0?nt.overrideMaterial:null)!==null)return;const zt=Y.isWebGL2;ce===null&&(ce=new If(1,1,{generateMipmaps:!0,type:V.has("EXT_color_buffer_half_float")?kv:Oh,minFilter:Cv,samples:zt?4:0})),N.getDrawingBufferSize(je),zt?ce.setSize(je.x,je.y):ce.setSize(L1(je.x),L1(je.y));const ye=N.getRenderTarget();N.setRenderTarget(ce),N.getClearColor(B),D=N.getClearAlpha(),D<1&&N.setClearColor(16777215,.5),N.clear();const He=N.toneMapping;N.toneMapping=Lh,Cn(Fe,nt,ot),de.updateMultisampleRenderTarget(ce),de.updateRenderTargetMipmap(ce);let Ye=!1;for(let Xe=0,Te=Se.length;Xe<Te;Xe++){const lt=Se[Xe],pt=lt.object,at=lt.geometry,Tt=lt.material,$t=lt.group;if(Tt.side===Du&&pt.layers.test(ot.layers)){const Rt=Tt.side;Tt.side=no,Tt.needsUpdate=!0,vr(pt,nt,ot,at,Tt,$t),Tt.side=Rt,Tt.needsUpdate=!0,Ye=!0}}Ye===!0&&(de.updateMultisampleRenderTarget(ce),de.updateRenderTargetMipmap(ce)),N.setRenderTarget(ye),N.setClearColor(B,D),N.toneMapping=He}function Cn(Fe,Se,nt){const ot=Se.isScene===!0?Se.overrideMaterial:null;for(let Ge=0,zt=Fe.length;Ge<zt;Ge++){const ye=Fe[Ge],He=ye.object,Ye=ye.geometry,Xe=ot===null?ye.material:ot,Te=ye.group;He.layers.test(nt.layers)&&vr(He,Se,nt,Ye,Xe,Te)}}function vr(Fe,Se,nt,ot,Ge,zt){Fe.onBeforeRender(N,Se,nt,ot,Ge,zt),Fe.modelViewMatrix.multiplyMatrices(nt.matrixWorldInverse,Fe.matrixWorld),Fe.normalMatrix.getNormalMatrix(Fe.modelViewMatrix),Ge.onBeforeRender(N,Se,nt,ot,Fe,zt),Ge.transparent===!0&&Ge.side===Du&&Ge.forceSinglePass===!1?(Ge.side=no,Ge.needsUpdate=!0,N.renderBufferDirect(nt,Se,ot,Ge,Fe,zt),Ge.side=Wh,Ge.needsUpdate=!0,N.renderBufferDirect(nt,Se,ot,Ge,Fe,zt),Ge.side=Du):N.renderBufferDirect(nt,Se,ot,Ge,Fe,zt),Fe.onAfterRender(N,Se,nt,ot,Ge,zt)}function Qn(Fe,Se,nt){Se.isScene!==!0&&(Se=oe);const ot=se.get(Fe),Ge=g.state.lights,zt=g.state.shadowsArray,ye=Ge.state.version,He=q.getParameters(Fe,Ge.state,zt,Se,nt),Ye=q.getProgramCacheKey(He);let Xe=ot.programs;ot.environment=Fe.isMeshStandardMaterial?Se.environment:null,ot.fog=Se.fog,ot.envMap=(Fe.isMeshStandardMaterial?Ne:Le).get(Fe.envMap||ot.environment),Xe===void 0&&(Fe.addEventListener("dispose",Ae),Xe=new Map,ot.programs=Xe);let Te=Xe.get(Ye);if(Te!==void 0){if(ot.currentProgram===Te&&ot.lightsStateVersion===ye)return En(Fe,He),Te}else He.uniforms=q.getUniforms(Fe),Fe.onBuild(nt,He,N),Fe.onBeforeCompile(He,N),Te=q.acquireProgram(He,Ye),Xe.set(Ye,Te),ot.uniforms=He.uniforms;const lt=ot.uniforms;return(!Fe.isShaderMaterial&&!Fe.isRawShaderMaterial||Fe.clipping===!0)&&(lt.clippingPlanes=Be.uniform),En(Fe,He),ot.needsLights=si(Fe),ot.lightsStateVersion=ye,ot.needsLights&&(lt.ambientLightColor.value=Ge.state.ambient,lt.lightProbe.value=Ge.state.probe,lt.directionalLights.value=Ge.state.directional,lt.directionalLightShadows.value=Ge.state.directionalShadow,lt.spotLights.value=Ge.state.spot,lt.spotLightShadows.value=Ge.state.spotShadow,lt.rectAreaLights.value=Ge.state.rectArea,lt.ltc_1.value=Ge.state.rectAreaLTC1,lt.ltc_2.value=Ge.state.rectAreaLTC2,lt.pointLights.value=Ge.state.point,lt.pointLightShadows.value=Ge.state.pointShadow,lt.hemisphereLights.value=Ge.state.hemi,lt.directionalShadowMap.value=Ge.state.directionalShadowMap,lt.directionalShadowMatrix.value=Ge.state.directionalShadowMatrix,lt.spotShadowMap.value=Ge.state.spotShadowMap,lt.spotLightMatrix.value=Ge.state.spotLightMatrix,lt.spotLightMap.value=Ge.state.spotLightMap,lt.pointShadowMap.value=Ge.state.pointShadowMap,lt.pointShadowMatrix.value=Ge.state.pointShadowMatrix),ot.currentProgram=Te,ot.uniformsList=null,Te}function tr(Fe){if(Fe.uniformsList===null){const Se=Fe.currentProgram.getUniforms();Fe.uniformsList=Z_.seqWithValue(Se.seq,Fe.uniforms)}return Fe.uniformsList}function En(Fe,Se){const nt=se.get(Fe);nt.outputColorSpace=Se.outputColorSpace,nt.batching=Se.batching,nt.instancing=Se.instancing,nt.instancingColor=Se.instancingColor,nt.skinning=Se.skinning,nt.morphTargets=Se.morphTargets,nt.morphNormals=Se.morphNormals,nt.morphColors=Se.morphColors,nt.morphTargetsCount=Se.morphTargetsCount,nt.numClippingPlanes=Se.numClippingPlanes,nt.numIntersection=Se.numClipIntersection,nt.vertexAlphas=Se.vertexAlphas,nt.vertexTangents=Se.vertexTangents,nt.toneMapping=Se.toneMapping}function dr(Fe,Se,nt,ot,Ge){Se.isScene!==!0&&(Se=oe),de.resetTextureUnits();const zt=Se.fog,ye=ot.isMeshStandardMaterial?Se.environment:null,He=C===null?N.outputColorSpace:C.isXRRenderTarget===!0?C.texture.colorSpace:id,Ye=(ot.isMeshStandardMaterial?Ne:Le).get(ot.envMap||ye),Xe=ot.vertexColors===!0&&!!nt.attributes.color&&nt.attributes.color.itemSize===4,Te=!!nt.attributes.tangent&&(!!ot.normalMap||ot.anisotropy>0),lt=!!nt.morphAttributes.position,pt=!!nt.morphAttributes.normal,at=!!nt.morphAttributes.color;let Tt=Lh;ot.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(Tt=N.toneMapping);const $t=nt.morphAttributes.position||nt.morphAttributes.normal||nt.morphAttributes.color,Rt=$t!==void 0?$t.length:0,Pt=se.get(ot),sn=g.state.lights;if(Z===!0&&(ve===!0||Fe!==P)){const pn=Fe===P&&ot.id===j;Be.setState(ot,Fe,pn)}let Zt=!1;ot.version===Pt.__version?(Pt.needsLights&&Pt.lightsStateVersion!==sn.state.version||Pt.outputColorSpace!==He||Ge.isBatchedMesh&&Pt.batching===!1||!Ge.isBatchedMesh&&Pt.batching===!0||Ge.isInstancedMesh&&Pt.instancing===!1||!Ge.isInstancedMesh&&Pt.instancing===!0||Ge.isSkinnedMesh&&Pt.skinning===!1||!Ge.isSkinnedMesh&&Pt.skinning===!0||Ge.isInstancedMesh&&Pt.instancingColor===!0&&Ge.instanceColor===null||Ge.isInstancedMesh&&Pt.instancingColor===!1&&Ge.instanceColor!==null||Pt.envMap!==Ye||ot.fog===!0&&Pt.fog!==zt||Pt.numClippingPlanes!==void 0&&(Pt.numClippingPlanes!==Be.numPlanes||Pt.numIntersection!==Be.numIntersection)||Pt.vertexAlphas!==Xe||Pt.vertexTangents!==Te||Pt.morphTargets!==lt||Pt.morphNormals!==pt||Pt.morphColors!==at||Pt.toneMapping!==Tt||Y.isWebGL2===!0&&Pt.morphTargetsCount!==Rt)&&(Zt=!0):(Zt=!0,Pt.__version=ot.version);let un=Pt.currentProgram;Zt===!0&&(un=Qn(ot,Se,Ge));let kn=!1,Dn=!1,Xt=!1;const mn=un.getUniforms(),fn=Pt.uniforms;if(me.useProgram(un.program)&&(kn=!0,Dn=!0,Xt=!0),ot.id!==j&&(j=ot.id,Dn=!0),kn||P!==Fe){mn.setValue(ie,"projectionMatrix",Fe.projectionMatrix),mn.setValue(ie,"viewMatrix",Fe.matrixWorldInverse);const pn=mn.map.cameraPosition;pn!==void 0&&pn.setValue(ie,he.setFromMatrixPosition(Fe.matrixWorld)),Y.logarithmicDepthBuffer&&mn.setValue(ie,"logDepthBufFC",2/(Math.log(Fe.far+1)/Math.LN2)),(ot.isMeshPhongMaterial||ot.isMeshToonMaterial||ot.isMeshLambertMaterial||ot.isMeshBasicMaterial||ot.isMeshStandardMaterial||ot.isShaderMaterial)&&mn.setValue(ie,"isOrthographic",Fe.isOrthographicCamera===!0),P!==Fe&&(P=Fe,Dn=!0,Xt=!0)}if(Ge.isSkinnedMesh){mn.setOptional(ie,Ge,"bindMatrix"),mn.setOptional(ie,Ge,"bindMatrixInverse");const pn=Ge.skeleton;pn&&(Y.floatVertexTextures?(pn.boneTexture===null&&pn.computeBoneTexture(),mn.setValue(ie,"boneTexture",pn.boneTexture,de)):console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."))}Ge.isBatchedMesh&&(mn.setOptional(ie,Ge,"batchingTexture"),mn.setValue(ie,"batchingTexture",Ge._matricesTexture,de));const Gr=nt.morphAttributes;if((Gr.position!==void 0||Gr.normal!==void 0||Gr.color!==void 0&&Y.isWebGL2===!0)&&Oe.update(Ge,nt,un),(Dn||Pt.receiveShadow!==Ge.receiveShadow)&&(Pt.receiveShadow=Ge.receiveShadow,mn.setValue(ie,"receiveShadow",Ge.receiveShadow)),ot.isMeshGouraudMaterial&&ot.envMap!==null&&(fn.envMap.value=Ye,fn.flipEnvMap.value=Ye.isCubeTexture&&Ye.isRenderTargetTexture===!1?-1:1),Dn&&(mn.setValue(ie,"toneMappingExposure",N.toneMappingExposure),Pt.needsLights&&Tr(fn,Xt),zt&&ot.fog===!0&&J.refreshFogUniforms(fn,zt),J.refreshMaterialUniforms(fn,ot,z,G,ce),Z_.upload(ie,tr(Pt),fn,de)),ot.isShaderMaterial&&ot.uniformsNeedUpdate===!0&&(Z_.upload(ie,tr(Pt),fn,de),ot.uniformsNeedUpdate=!1),ot.isSpriteMaterial&&mn.setValue(ie,"center",Ge.center),mn.setValue(ie,"modelViewMatrix",Ge.modelViewMatrix),mn.setValue(ie,"normalMatrix",Ge.normalMatrix),mn.setValue(ie,"modelMatrix",Ge.matrixWorld),ot.isShaderMaterial||ot.isRawShaderMaterial){const pn=ot.uniformsGroups;for(let Rn=0,ia=pn.length;Rn<ia;Rn++)if(Y.isWebGL2){const Sn=pn[Rn];we.update(Sn,un),we.bind(Sn,un)}else console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.")}return un}function Tr(Fe,Se){Fe.ambientLightColor.needsUpdate=Se,Fe.lightProbe.needsUpdate=Se,Fe.directionalLights.needsUpdate=Se,Fe.directionalLightShadows.needsUpdate=Se,Fe.pointLights.needsUpdate=Se,Fe.pointLightShadows.needsUpdate=Se,Fe.spotLights.needsUpdate=Se,Fe.spotLightShadows.needsUpdate=Se,Fe.rectAreaLights.needsUpdate=Se,Fe.hemisphereLights.needsUpdate=Se}function si(Fe){return Fe.isMeshLambertMaterial||Fe.isMeshToonMaterial||Fe.isMeshPhongMaterial||Fe.isMeshStandardMaterial||Fe.isShadowMaterial||Fe.isShaderMaterial&&Fe.lights===!0}this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(Fe,Se,nt){se.get(Fe.texture).__webglTexture=Se,se.get(Fe.depthTexture).__webglTexture=nt;const ot=se.get(Fe);ot.__hasExternalTextures=!0,ot.__hasExternalTextures&&(ot.__autoAllocateDepthBuffer=nt===void 0,ot.__autoAllocateDepthBuffer||V.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),ot.__useRenderToTexture=!1))},this.setRenderTargetFramebuffer=function(Fe,Se){const nt=se.get(Fe);nt.__webglFramebuffer=Se,nt.__useDefaultFramebuffer=Se===void 0},this.setRenderTarget=function(Fe,Se=0,nt=0){C=Fe,A=Se,M=nt;let ot=!0,Ge=null,zt=!1,ye=!1;if(Fe){const Ye=se.get(Fe);Ye.__useDefaultFramebuffer!==void 0?(me.bindFramebuffer(ie.FRAMEBUFFER,null),ot=!1):Ye.__webglFramebuffer===void 0?de.setupRenderTarget(Fe):Ye.__hasExternalTextures&&de.rebindTextures(Fe,se.get(Fe.texture).__webglTexture,se.get(Fe.depthTexture).__webglTexture);const Xe=Fe.texture;(Xe.isData3DTexture||Xe.isDataArrayTexture||Xe.isCompressedArrayTexture)&&(ye=!0);const Te=se.get(Fe).__webglFramebuffer;Fe.isWebGLCubeRenderTarget?(Array.isArray(Te[Se])?Ge=Te[Se][nt]:Ge=Te[Se],zt=!0):Y.isWebGL2&&Fe.samples>0&&de.useMultisampledRTT(Fe)===!1?Ge=se.get(Fe).__webglMultisampledFramebuffer:Array.isArray(Te)?Ge=Te[nt]:Ge=Te,E.copy(Fe.viewport),U.copy(Fe.scissor),L=Fe.scissorTest}else E.copy(ae).multiplyScalar(z).floor(),U.copy(H).multiplyScalar(z).floor(),L=K;if(me.bindFramebuffer(ie.FRAMEBUFFER,Ge)&&Y.drawBuffers&&ot&&me.drawBuffers(Fe,Ge),me.viewport(E),me.scissor(U),me.setScissorTest(L),zt){const Ye=se.get(Fe.texture);ie.framebufferTexture2D(ie.FRAMEBUFFER,ie.COLOR_ATTACHMENT0,ie.TEXTURE_CUBE_MAP_POSITIVE_X+Se,Ye.__webglTexture,nt)}else if(ye){const Ye=se.get(Fe.texture),Xe=Se||0;ie.framebufferTextureLayer(ie.FRAMEBUFFER,ie.COLOR_ATTACHMENT0,Ye.__webglTexture,nt||0,Xe)}j=-1},this.readRenderTargetPixels=function(Fe,Se,nt,ot,Ge,zt,ye){if(!(Fe&&Fe.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let He=se.get(Fe).__webglFramebuffer;if(Fe.isWebGLCubeRenderTarget&&ye!==void 0&&(He=He[ye]),He){me.bindFramebuffer(ie.FRAMEBUFFER,He);try{const Ye=Fe.texture,Xe=Ye.format,Te=Ye.type;if(Xe!==ll&&ke.convert(Xe)!==ie.getParameter(ie.IMPLEMENTATION_COLOR_READ_FORMAT)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}const lt=Te===kv&&(V.has("EXT_color_buffer_half_float")||Y.isWebGL2&&V.has("EXT_color_buffer_float"));if(Te!==Oh&&ke.convert(Te)!==ie.getParameter(ie.IMPLEMENTATION_COLOR_READ_TYPE)&&!(Te===zu&&(Y.isWebGL2||V.has("OES_texture_float")||V.has("WEBGL_color_buffer_float")))&&!lt){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Se>=0&&Se<=Fe.width-ot&&nt>=0&&nt<=Fe.height-Ge&&ie.readPixels(Se,nt,ot,Ge,ke.convert(Xe),ke.convert(Te),zt)}finally{const Ye=C!==null?se.get(C).__webglFramebuffer:null;me.bindFramebuffer(ie.FRAMEBUFFER,Ye)}}},this.copyFramebufferToTexture=function(Fe,Se,nt=0){const ot=Math.pow(2,-nt),Ge=Math.floor(Se.image.width*ot),zt=Math.floor(Se.image.height*ot);de.setTexture2D(Se,0),ie.copyTexSubImage2D(ie.TEXTURE_2D,nt,0,0,Fe.x,Fe.y,Ge,zt),me.unbindTexture()},this.copyTextureToTexture=function(Fe,Se,nt,ot=0){const Ge=Se.image.width,zt=Se.image.height,ye=ke.convert(nt.format),He=ke.convert(nt.type);de.setTexture2D(nt,0),ie.pixelStorei(ie.UNPACK_FLIP_Y_WEBGL,nt.flipY),ie.pixelStorei(ie.UNPACK_PREMULTIPLY_ALPHA_WEBGL,nt.premultiplyAlpha),ie.pixelStorei(ie.UNPACK_ALIGNMENT,nt.unpackAlignment),Se.isDataTexture?ie.texSubImage2D(ie.TEXTURE_2D,ot,Fe.x,Fe.y,Ge,zt,ye,He,Se.image.data):Se.isCompressedTexture?ie.compressedTexSubImage2D(ie.TEXTURE_2D,ot,Fe.x,Fe.y,Se.mipmaps[0].width,Se.mipmaps[0].height,ye,Se.mipmaps[0].data):ie.texSubImage2D(ie.TEXTURE_2D,ot,Fe.x,Fe.y,ye,He,Se.image),ot===0&&nt.generateMipmaps&&ie.generateMipmap(ie.TEXTURE_2D),me.unbindTexture()},this.copyTextureToTexture3D=function(Fe,Se,nt,ot,Ge=0){if(N.isWebGL1Renderer){console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.");return}const zt=Fe.max.x-Fe.min.x+1,ye=Fe.max.y-Fe.min.y+1,He=Fe.max.z-Fe.min.z+1,Ye=ke.convert(ot.format),Xe=ke.convert(ot.type);let Te;if(ot.isData3DTexture)de.setTexture3D(ot,0),Te=ie.TEXTURE_3D;else if(ot.isDataArrayTexture)de.setTexture2DArray(ot,0),Te=ie.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}ie.pixelStorei(ie.UNPACK_FLIP_Y_WEBGL,ot.flipY),ie.pixelStorei(ie.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ot.premultiplyAlpha),ie.pixelStorei(ie.UNPACK_ALIGNMENT,ot.unpackAlignment);const lt=ie.getParameter(ie.UNPACK_ROW_LENGTH),pt=ie.getParameter(ie.UNPACK_IMAGE_HEIGHT),at=ie.getParameter(ie.UNPACK_SKIP_PIXELS),Tt=ie.getParameter(ie.UNPACK_SKIP_ROWS),$t=ie.getParameter(ie.UNPACK_SKIP_IMAGES),Rt=nt.isCompressedTexture?nt.mipmaps[0]:nt.image;ie.pixelStorei(ie.UNPACK_ROW_LENGTH,Rt.width),ie.pixelStorei(ie.UNPACK_IMAGE_HEIGHT,Rt.height),ie.pixelStorei(ie.UNPACK_SKIP_PIXELS,Fe.min.x),ie.pixelStorei(ie.UNPACK_SKIP_ROWS,Fe.min.y),ie.pixelStorei(ie.UNPACK_SKIP_IMAGES,Fe.min.z),nt.isDataTexture||nt.isData3DTexture?ie.texSubImage3D(Te,Ge,Se.x,Se.y,Se.z,zt,ye,He,Ye,Xe,Rt.data):nt.isCompressedArrayTexture?(console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."),ie.compressedTexSubImage3D(Te,Ge,Se.x,Se.y,Se.z,zt,ye,He,Ye,Rt.data)):ie.texSubImage3D(Te,Ge,Se.x,Se.y,Se.z,zt,ye,He,Ye,Xe,Rt),ie.pixelStorei(ie.UNPACK_ROW_LENGTH,lt),ie.pixelStorei(ie.UNPACK_IMAGE_HEIGHT,pt),ie.pixelStorei(ie.UNPACK_SKIP_PIXELS,at),ie.pixelStorei(ie.UNPACK_SKIP_ROWS,Tt),ie.pixelStorei(ie.UNPACK_SKIP_IMAGES,$t),Ge===0&&ot.generateMipmaps&&ie.generateMipmap(Te),me.unbindTexture()},this.initTexture=function(Fe){Fe.isCubeTexture?de.setTextureCube(Fe,0):Fe.isData3DTexture?de.setTexture3D(Fe,0):Fe.isDataArrayTexture||Fe.isCompressedArrayTexture?de.setTexture2DArray(Fe,0):de.setTexture2D(Fe,0),me.unbindTexture()},this.resetState=function(){A=0,M=0,C=null,me.reset(),ge.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Ac}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const n=this.getContext();n.drawingBufferColorSpace=e===JF?"display-p3":"srgb",n.unpackColorSpace=Fr.workingColorSpace===lk?"display-p3":"srgb"}get physicallyCorrectLights(){return console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),!this.useLegacyLights}set physicallyCorrectLights(e){console.warn("THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead."),this.useLegacyLights=!e}get outputEncoding(){return console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace===Yi?pf:TY}set outputEncoding(e){console.warn("THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead."),this.outputColorSpace=e===pf?Yi:id}get useLegacyLights(){return console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights}set useLegacyLights(e){console.warn("THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733."),this._useLegacyLights=e}}class IAe extends hD{}IAe.prototype.isWebGL1Renderer=!0;class iL{constructor(e,n=1,r=1e3){this.isFog=!0,this.name="",this.color=new dn(e),this.near=n,this.far=r}clone(){return new iL(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class zAe extends Rs{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,n){return super.copy(e,n),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const n=super.toJSON(e);return this.fog!==null&&(n.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(n.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(n.object.backgroundIntensity=this.backgroundIntensity),n}}class UAe{constructor(e,n){this.isInterleavedBuffer=!0,this.array=e,this.stride=n,this.count=e!==void 0?e.length/n:0,this.usage=lD,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Gu()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return console.warn('THREE.InterleavedBuffer: "updateRange" is deprecated and removed in r169. Use "addUpdateRange()" instead.'),this._updateRange}setUsage(e){return this.usage=e,this}addUpdateRange(e,n){this.updateRanges.push({start:e,count:n})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,n,r){e*=this.stride,r*=n.stride;for(let a=0,s=this.stride;a<s;a++)this.array[e+a]=n.array[r+a];return this}set(e,n=0){return this.array.set(e,n),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Gu()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const n=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),r=new this.constructor(n,this.stride);return r.setUsage(this.usage),r}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Gu()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Cs=new Ze;class Sh{constructor(e,n,r,a=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=n,this.offset=r,this.normalized=a}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let n=0,r=this.data.count;n<r;n++)Cs.fromBufferAttribute(this,n),Cs.applyMatrix4(e),this.setXYZ(n,Cs.x,Cs.y,Cs.z);return this}applyNormalMatrix(e){for(let n=0,r=this.count;n<r;n++)Cs.fromBufferAttribute(this,n),Cs.applyNormalMatrix(e),this.setXYZ(n,Cs.x,Cs.y,Cs.z);return this}transformDirection(e){for(let n=0,r=this.count;n<r;n++)Cs.fromBufferAttribute(this,n),Cs.transformDirection(e),this.setXYZ(n,Cs.x,Cs.y,Cs.z);return this}setX(e,n){return this.normalized&&(n=Rr(n,this.array)),this.data.array[e*this.data.stride+this.offset]=n,this}setY(e,n){return this.normalized&&(n=Rr(n,this.array)),this.data.array[e*this.data.stride+this.offset+1]=n,this}setZ(e,n){return this.normalized&&(n=Rr(n,this.array)),this.data.array[e*this.data.stride+this.offset+2]=n,this}setW(e,n){return this.normalized&&(n=Rr(n,this.array)),this.data.array[e*this.data.stride+this.offset+3]=n,this}getX(e){let n=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(n=Nc(n,this.array)),n}getY(e){let n=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(n=Nc(n,this.array)),n}getZ(e){let n=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(n=Nc(n,this.array)),n}getW(e){let n=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(n=Nc(n,this.array)),n}setXY(e,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this}setXYZ(e,n,r,a){return e=e*this.data.stride+this.offset,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array),a=Rr(a,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=a,this}setXYZW(e,n,r,a,s){return e=e*this.data.stride+this.offset,this.normalized&&(n=Rr(n,this.array),r=Rr(r,this.array),a=Rr(a,this.array),s=Rr(s,this.array)),this.data.array[e+0]=n,this.data.array[e+1]=r,this.data.array[e+2]=a,this.data.array[e+3]=s,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const n=[];for(let r=0;r<this.count;r++){const a=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[a+s])}return new Do(new this.array.constructor(n),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Sh(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const n=[];for(let r=0;r<this.count;r++){const a=r*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)n.push(this.data.array[a+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:n,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class BAe extends ro{constructor(e=null,n=1,r=1,a,s,o,l,c,u=Xi,d=Xi,h,f){super(null,o,l,c,u,d,a,s,h,f),this.isDataTexture=!0,this.image={data:e,width:n,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}function HAe(t,e){return t.z-e.z}function $Ae(t,e){return e.z-t.z}class VAe{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,n){const r=this.pool,a=this.list;this.index>=r.length&&r.push({start:-1,count:-1,z:-1});const s=r[this.index];a.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=n}reset(){this.list.length=0,this.index=0}}const vg="batchId",Jd=new Yr,wH=new Yr,qAe=new Yr,SH=new Yr,YP=new ck,QS=new pl,Lm=new jc,hy=new Ze,QP=new VAe,us=new Gl,ZS=[];function GAe(t,e,n=0){const r=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const a=t.count;for(let s=0;s<a;s++)for(let o=0;o<r;o++)e.setComponent(s+n,o,t.getComponent(s,o))}else e.array.set(t.array,n*r);e.needsUpdate=!0}class WAe extends Gl{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,n,r=n*2,a){super(new ys,a),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._drawRanges=[],this._reservedRanges=[],this._visibility=[],this._active=[],this._bounds=[],this._maxGeometryCount=e,this._maxVertexCount=n,this._maxIndexCount=r,this._geometryInitialized=!1,this._geometryCount=0,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._visibilityChanged=!0,this._matricesTexture=null,this._initMatricesTexture()}_initMatricesTexture(){let e=Math.sqrt(this._maxGeometryCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const n=new Float32Array(e*e*4),r=new BAe(n,e,e,ll,zu);this._matricesTexture=r}_initializeGeometry(e){const n=this.geometry,r=this._maxVertexCount,a=this._maxGeometryCount,s=this._maxIndexCount;if(this._geometryInitialized===!1){for(const l in e.attributes){const c=e.getAttribute(l),{array:u,itemSize:d,normalized:h}=c,f=new u.constructor(r*d),p=new c.constructor(f,d,h);p.setUsage(c.usage),n.setAttribute(l,p)}if(e.getIndex()!==null){const l=r>65536?new Uint32Array(s):new Uint16Array(s);n.setIndex(new Do(l,1))}const o=a>65536?new Uint32Array(r):new Uint16Array(r);n.setAttribute(vg,new Do(o,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(vg))throw new Error(`BatchedMesh: Geometry cannot use attribute "${vg}"`);const n=this.geometry;if(!!e.getIndex()!=!!n.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const r in n.attributes){if(r===vg)continue;if(!e.hasAttribute(r))throw new Error(`BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);const a=e.getAttribute(r),s=n.getAttribute(r);if(a.itemSize!==s.itemSize||a.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new pl);const e=this._geometryCount,n=this.boundingBox,r=this._active;n.makeEmpty();for(let a=0;a<e;a++)r[a]!==!1&&(this.getMatrixAt(a,Jd),this.getBoundingBoxAt(a,QS).applyMatrix4(Jd),n.union(QS))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new jc);const e=this._geometryCount,n=this.boundingSphere,r=this._active;n.makeEmpty();for(let a=0;a<e;a++)r[a]!==!1&&(this.getMatrixAt(a,Jd),this.getBoundingSphereAt(a,Lm).applyMatrix4(Jd),n.union(Lm))}addGeometry(e,n=-1,r=-1){if(this._initializeGeometry(e),this._validateGeometry(e),this._geometryCount>=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");const a={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const o=this._reservedRanges,l=this._drawRanges,c=this._bounds;this._geometryCount!==0&&(s=o[o.length-1]),n===-1?a.vertexCount=e.getAttribute("position").count:a.vertexCount=n,s===null?a.vertexStart=0:a.vertexStart=s.vertexStart+s.vertexCount;const u=e.getIndex(),d=u!==null;if(d&&(r===-1?a.indexCount=u.count:a.indexCount=r,s===null?a.indexStart=0:a.indexStart=s.indexStart+s.indexCount),a.indexStart!==-1&&a.indexStart+a.indexCount>this._maxIndexCount||a.vertexStart+a.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const h=this._visibility,f=this._active,p=this._matricesTexture,x=this._matricesTexture.image.data;h.push(!0),f.push(!0);const v=this._geometryCount;this._geometryCount++,qAe.toArray(x,v*16),p.needsUpdate=!0,o.push(a),l.push({start:d?a.indexStart:a.vertexStart,count:-1}),c.push({boxInitialized:!1,box:new pl,sphereInitialized:!1,sphere:new jc});const g=this.geometry.getAttribute(vg);for(let y=0;y<a.vertexCount;y++)g.setX(a.vertexStart+y,v);return g.needsUpdate=!0,this.setGeometryAt(v,e),v}setGeometryAt(e,n){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(n);const r=this.geometry,a=r.getIndex()!==null,s=r.getIndex(),o=n.getIndex(),l=this._reservedRanges[e];if(a&&o.count>l.indexCount||n.attributes.position.count>l.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const c=l.vertexStart,u=l.vertexCount;for(const p in r.attributes){if(p===vg)continue;const x=n.getAttribute(p),v=r.getAttribute(p);GAe(x,v,c);const g=x.itemSize;for(let y=x.count,_=u;y<_;y++){const N=c+y;for(let k=0;k<g;k++)v.setComponent(N,k,0)}v.needsUpdate=!0}if(a){const p=l.indexStart;for(let x=0;x<o.count;x++)s.setX(p+x,c+o.getX(x));for(let x=o.count,v=l.indexCount;x<v;x++)s.setX(p+x,c);s.needsUpdate=!0}const d=this._bounds[e];n.boundingBox!==null?(d.box.copy(n.boundingBox),d.boxInitialized=!0):d.boxInitialized=!1,n.boundingSphere!==null?(d.sphere.copy(n.boundingSphere),d.sphereInitialized=!0):d.sphereInitialized=!1;const h=this._drawRanges[e],f=n.getAttribute("position");return h.count=a?o.count:f.count,this._visibilityChanged=!0,e}deleteGeometry(e){const n=this._active;return e>=n.length||n[e]===!1?this:(n[e]=!1,this._visibilityChanged=!0,this)}getBoundingBoxAt(e,n){if(this._active[e]===!1)return this;const a=this._bounds[e],s=a.box,o=this.geometry;if(a.boxInitialized===!1){s.makeEmpty();const l=o.index,c=o.attributes.position,u=this._drawRanges[e];for(let d=u.start,h=u.start+u.count;d<h;d++){let f=d;l&&(f=l.getX(f)),s.expandByPoint(hy.fromBufferAttribute(c,f))}a.boxInitialized=!0}return n.copy(s),n}getBoundingSphereAt(e,n){if(this._active[e]===!1)return this;const a=this._bounds[e],s=a.sphere,o=this.geometry;if(a.sphereInitialized===!1){s.makeEmpty(),this.getBoundingBoxAt(e,QS),QS.getCenter(s.center);const l=o.index,c=o.attributes.position,u=this._drawRanges[e];let d=0;for(let h=u.start,f=u.start+u.count;h<f;h++){let p=h;l&&(p=l.getX(p)),hy.fromBufferAttribute(c,p),d=Math.max(d,s.center.distanceToSquared(hy))}s.radius=Math.sqrt(d),a.sphereInitialized=!0}return n.copy(s),n}setMatrixAt(e,n){const r=this._active,a=this._matricesTexture,s=this._matricesTexture.image.data,o=this._geometryCount;return e>=o||r[e]===!1?this:(n.toArray(s,e*16),a.needsUpdate=!0,this)}getMatrixAt(e,n){const r=this._active,a=this._matricesTexture.image.data,s=this._geometryCount;return e>=s||r[e]===!1?null:n.fromArray(a,e*16)}setVisibleAt(e,n){const r=this._visibility,a=this._active,s=this._geometryCount;return e>=s||a[e]===!1||r[e]===n?this:(r[e]=n,this._visibilityChanged=!0,this)}getVisibleAt(e){const n=this._visibility,r=this._active,a=this._geometryCount;return e>=a||r[e]===!1?!1:n[e]}raycast(e,n){const r=this._visibility,a=this._active,s=this._drawRanges,o=this._geometryCount,l=this.matrixWorld,c=this.geometry;us.material=this.material,us.geometry.index=c.index,us.geometry.attributes=c.attributes,us.geometry.boundingBox===null&&(us.geometry.boundingBox=new pl),us.geometry.boundingSphere===null&&(us.geometry.boundingSphere=new jc);for(let u=0;u<o;u++){if(!r[u]||!a[u])continue;const d=s[u];us.geometry.setDrawRange(d.start,d.count),this.getMatrixAt(u,us.matrixWorld).premultiply(l),this.getBoundingBoxAt(u,us.geometry.boundingBox),this.getBoundingSphereAt(u,us.geometry.boundingSphere),us.raycast(e,ZS);for(let h=0,f=ZS.length;h<f;h++){const p=ZS[h];p.object=this,p.batchId=u,n.push(p)}ZS.length=0}us.material=null,us.geometry.index=null,us.geometry.attributes={},us.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._drawRanges=e._drawRanges.map(n=>({...n})),this._reservedRanges=e._reservedRanges.map(n=>({...n})),this._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map(n=>({boxInitialized:n.boxInitialized,box:n.box.clone(),sphereInitialized:n.sphereInitialized,sphere:n.sphere.clone()})),this._maxGeometryCount=e._maxGeometryCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this}onBeforeRender(e,n,r,a,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const o=a.getIndex(),l=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._visibility,u=this._multiDrawStarts,d=this._multiDrawCounts,h=this._drawRanges,f=this.perObjectFrustumCulled;f&&(SH.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),YP.setFromProjectionMatrix(SH,e.isWebGPURenderer?Av:Ac));let p=0;if(this.sortObjects){wH.copy(this.matrixWorld).invert(),hy.setFromMatrixPosition(r.matrixWorld).applyMatrix4(wH);for(let g=0,y=c.length;g<y;g++)if(c[g]){this.getMatrixAt(g,Jd),this.getBoundingSphereAt(g,Lm).applyMatrix4(Jd);let _=!1;if(f&&(_=!YP.intersectsSphere(Lm)),!_){const N=hy.distanceTo(Lm.center);QP.push(h[g],N)}}const x=QP.list,v=this.customSort;v===null?x.sort(s.transparent?$Ae:HAe):v.call(this,x,r);for(let g=0,y=x.length;g<y;g++){const _=x[g];u[p]=_.start*l,d[p]=_.count,p++}QP.reset()}else for(let x=0,v=c.length;x<v;x++)if(c[x]){let g=!1;if(f&&(this.getMatrixAt(x,Jd),this.getBoundingSphereAt(x,Lm).applyMatrix4(Jd),g=!YP.intersectsSphere(Lm)),!g){const y=h[x];u[p]=y.start*l,d[p]=y.count,p++}}this._multiDrawCount=p,this._visibilityChanged=!1}onBeforeShadow(e,n,r,a,s,o){this.onBeforeRender(e,null,a,s,o)}}class x0 extends Xb{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new dn(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const _H=new Ze,NH=new Ze,CH=new Yr,ZP=new tL,JS=new jc;let KAe=class extends Rs{constructor(e=new ys,n=new x0){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=n,this.updateMorphTargets()}copy(e,n){return super.copy(e,n),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[0];for(let a=1,s=n.count;a<s;a++)_H.fromBufferAttribute(n,a-1),NH.fromBufferAttribute(n,a),r[a]=r[a-1],r[a]+=_H.distanceTo(NH);e.setAttribute("lineDistance",new Ha(r,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,n){const r=this.geometry,a=this.matrixWorld,s=e.params.Line.threshold,o=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),JS.copy(r.boundingSphere),JS.applyMatrix4(a),JS.radius+=s,e.ray.intersectsSphere(JS)===!1)return;CH.copy(a).invert(),ZP.copy(e.ray).applyMatrix4(CH);const l=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=l*l,u=new Ze,d=new Ze,h=new Ze,f=new Ze,p=this.isLineSegments?2:1,x=r.index,g=r.attributes.position;if(x!==null){const y=Math.max(0,o.start),_=Math.min(x.count,o.start+o.count);for(let N=y,k=_-1;N<k;N+=p){const A=x.getX(N),M=x.getX(N+1);if(u.fromBufferAttribute(g,A),d.fromBufferAttribute(g,M),ZP.distanceSqToSegment(u,d,f,h)>c)continue;f.applyMatrix4(this.matrixWorld);const j=e.ray.origin.distanceTo(f);j<e.near||j>e.far||n.push({distance:j,point:h.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}else{const y=Math.max(0,o.start),_=Math.min(g.count,o.start+o.count);for(let N=y,k=_-1;N<k;N+=p){if(u.fromBufferAttribute(g,N),d.fromBufferAttribute(g,N+1),ZP.distanceSqToSegment(u,d,f,h)>c)continue;f.applyMatrix4(this.matrixWorld);const M=e.ray.origin.distanceTo(f);M<e.near||M>e.far||n.push({distance:M,point:h.clone().applyMatrix4(this.matrixWorld),index:N,face:null,faceIndex:null,object:this})}}}updateMorphTargets(){const n=this.geometry.morphAttributes,r=Object.keys(n);if(r.length>0){const a=n[r[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const l=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[l]=s}}}}};const kH=new Ze,AH=new Ze;class dk extends KAe{constructor(e,n){super(e,n),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const n=e.attributes.position,r=[];for(let a=0,s=n.count;a<s;a+=2)kH.fromBufferAttribute(n,a),AH.fromBufferAttribute(n,a+1),r[a]=a===0?0:r[a-1],r[a+1]=r[a]+kH.distanceTo(AH);e.setAttribute("lineDistance",new Ha(r,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class XAe extends ys{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const n=[],r=new Set,a=new Ze,s=new Ze;if(e.index!==null){const o=e.attributes.position,l=e.index;let c=e.groups;c.length===0&&(c=[{start:0,count:l.count,materialIndex:0}]);for(let u=0,d=c.length;u<d;++u){const h=c[u],f=h.start,p=h.count;for(let x=f,v=f+p;x<v;x+=3)for(let g=0;g<3;g++){const y=l.getX(x+g),_=l.getX(x+(g+1)%3);a.fromBufferAttribute(o,y),s.fromBufferAttribute(o,_),TH(a,s,r)===!0&&(n.push(a.x,a.y,a.z),n.push(s.x,s.y,s.z))}}}else{const o=e.attributes.position;for(let l=0,c=o.count/3;l<c;l++)for(let u=0;u<3;u++){const d=3*l+u,h=3*l+(u+1)%3;a.fromBufferAttribute(o,d),s.fromBufferAttribute(o,h),TH(a,s,r)===!0&&(n.push(a.x,a.y,a.z),n.push(s.x,s.y,s.z))}}this.setAttribute("position",new Ha(n,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function TH(t,e,n){const r=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`,a=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`;return n.has(r)===!0||n.has(a)===!0?!1:(n.add(r),n.add(a),!0)}class YAe extends Xb{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new dn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new dn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=MY,this.normalScale=new _n(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=QF,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class QAe extends x0{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}class QY extends Rs{constructor(e,n=1){super(),this.isLight=!0,this.type="Light",this.color=new dn(e),this.intensity=n}dispose(){}copy(e,n){return super.copy(e,n),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const n=super.toJSON(e);return n.object.color=this.color.getHex(),n.object.intensity=this.intensity,this.groundColor!==void 0&&(n.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(n.object.distance=this.distance),this.angle!==void 0&&(n.object.angle=this.angle),this.decay!==void 0&&(n.object.decay=this.decay),this.penumbra!==void 0&&(n.object.penumbra=this.penumbra),this.shadow!==void 0&&(n.object.shadow=this.shadow.toJSON()),n}}const JP=new Yr,MH=new Ze,PH=new Ze;class ZAe{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new _n(512,512),this.map=null,this.mapPass=null,this.matrix=new Yr,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ck,this._frameExtents=new _n(1,1),this._viewportCount=1,this._viewports=[new Or(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const n=this.camera,r=this.matrix;MH.setFromMatrixPosition(e.matrixWorld),n.position.copy(MH),PH.setFromMatrixPosition(e.target.matrixWorld),n.lookAt(PH),n.updateMatrixWorld(),JP.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(JP),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(JP)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.bias=e.bias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const EH=new Yr,my=new Ze,eE=new Ze;class JAe extends ZAe{constructor(){super(new Ao(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new _n(4,2),this._viewportCount=6,this._viewports=[new Or(2,1,1,1),new Or(0,1,1,1),new Or(3,1,1,1),new Or(1,1,1,1),new Or(3,0,1,1),new Or(1,0,1,1)],this._cubeDirections=[new Ze(1,0,0),new Ze(-1,0,0),new Ze(0,0,1),new Ze(0,0,-1),new Ze(0,1,0),new Ze(0,-1,0)],this._cubeUps=[new Ze(0,1,0),new Ze(0,1,0),new Ze(0,1,0),new Ze(0,1,0),new Ze(0,0,1),new Ze(0,0,-1)]}updateMatrices(e,n=0){const r=this.camera,a=this.matrix,s=e.distance||r.far;s!==r.far&&(r.far=s,r.updateProjectionMatrix()),my.setFromMatrixPosition(e.matrixWorld),r.position.copy(my),eE.copy(r.position),eE.add(this._cubeDirections[n]),r.up.copy(this._cubeUps[n]),r.lookAt(eE),r.updateMatrixWorld(),a.makeTranslation(-my.x,-my.y,-my.z),EH.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),this._frustum.setFromProjectionMatrix(EH)}}class eTe extends QY{constructor(e,n,r=0,a=2){super(e,n),this.isPointLight=!0,this.type="PointLight",this.distance=r,this.decay=a,this.shadow=new JAe}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,n){return super.copy(e,n),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class tTe extends QY{constructor(e,n){super(e,n),this.isAmbientLight=!0,this.type="AmbientLight"}}class nTe extends ys{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class mD extends UAe{constructor(e,n,r=1){super(e,n),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const n=super.clone(e);return n.meshPerAttribute=this.meshPerAttribute,n}toJSON(e){const n=super.toJSON(e);return n.isInstancedInterleavedBuffer=!0,n.meshPerAttribute=this.meshPerAttribute,n}}class jH{constructor(e=1,n=0,r=0){return this.radius=e,this.phi=n,this.theta=r,this}set(e,n,r){return this.radius=e,this.phi=n,this.theta=r,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Math.max(1e-6,Math.min(Math.PI-1e-6,this.phi)),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,n,r){return this.radius=Math.sqrt(e*e+n*n+r*r),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,r),this.phi=Math.acos(Qi(n/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const DH=new Ze,e_=new Ze;class rTe{constructor(e=new Ze,n=new Ze){this.start=e,this.end=n}set(e,n){return this.start.copy(e),this.end.copy(n),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,n){return this.delta(n).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,n){DH.subVectors(e,this.start),e_.subVectors(this.end,this.start);const r=e_.dot(e_);let s=e_.dot(DH)/r;return n&&(s=Qi(s,0,1)),s}closestPointToPoint(e,n,r){const a=this.closestPointToPointParameter(e,n);return this.delta(r).multiplyScalar(a).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}class aTe extends dk{constructor(e=1){const n=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],r=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],a=new ys;a.setAttribute("position",new Ha(n,3)),a.setAttribute("color",new Ha(r,3));const s=new x0({vertexColors:!0,toneMapped:!1});super(a,s),this.type="AxesHelper"}setColors(e,n,r){const a=new dn,s=this.geometry.attributes.color.array;return a.set(e),a.toArray(s,0),a.toArray(s,3),a.set(n),a.toArray(s,6),a.toArray(s,9),a.set(r),a.toArray(s,12),a.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:sk}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=sk);class Dc{constructor(e,n,r,a,s="div"){this.parent=e,this.object=n,this.property=r,this._disabled=!1,this._hidden=!1,this.initialValue=this.getValue(),this.domElement=document.createElement(s),this.domElement.classList.add("controller"),this.domElement.classList.add(a),this.$name=document.createElement("div"),this.$name.classList.add("name"),Dc.nextNameID=Dc.nextNameID||0,this.$name.id=`lil-gui-name-${++Dc.nextNameID}`,this.$widget=document.createElement("div"),this.$widget.classList.add("widget"),this.$disable=this.$widget,this.domElement.appendChild(this.$name),this.domElement.appendChild(this.$widget),this.domElement.addEventListener("keydown",o=>o.stopPropagation()),this.domElement.addEventListener("keyup",o=>o.stopPropagation()),this.parent.children.push(this),this.parent.controllers.push(this),this.parent.$children.appendChild(this.domElement),this._listenCallback=this._listenCallback.bind(this),this.name(r)}name(e){return this._name=e,this.$name.textContent=e,this}onChange(e){return this._onChange=e,this}_callOnChange(){this.parent._callOnChange(this),this._onChange!==void 0&&this._onChange.call(this,this.getValue()),this._changed=!0}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(){this._changed&&(this.parent._callOnFinishChange(this),this._onFinishChange!==void 0&&this._onFinishChange.call(this,this.getValue())),this._changed=!1}reset(){return this.setValue(this.initialValue),this._callOnFinishChange(),this}enable(e=!0){return this.disable(!e)}disable(e=!0){return e===this._disabled?this:(this._disabled=e,this.domElement.classList.toggle("disabled",e),this.$disable.toggleAttribute("disabled",e),this)}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}options(e){const n=this.parent.add(this.object,this.property,e);return n.name(this._name),this.destroy(),n}min(e){return this}max(e){return this}step(e){return this}decimals(e){return this}listen(e=!0){return this._listening=e,this._listenCallbackID!==void 0&&(cancelAnimationFrame(this._listenCallbackID),this._listenCallbackID=void 0),this._listening&&this._listenCallback(),this}_listenCallback(){this._listenCallbackID=requestAnimationFrame(this._listenCallback);const e=this.save();e!==this._listenPrevValue&&this.updateDisplay(),this._listenPrevValue=e}getValue(){return this.object[this.property]}setValue(e){return this.getValue()!==e&&(this.object[this.property]=e,this._callOnChange(),this.updateDisplay()),this}updateDisplay(){return this}load(e){return this.setValue(e),this._callOnFinishChange(),this}save(){return this.getValue()}destroy(){this.listen(!1),this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.controllers.splice(this.parent.controllers.indexOf(this),1),this.parent.$children.removeChild(this.domElement)}}class iTe extends Dc{constructor(e,n,r){super(e,n,r,"boolean","label"),this.$input=document.createElement("input"),this.$input.setAttribute("type","checkbox"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$widget.appendChild(this.$input),this.$input.addEventListener("change",()=>{this.setValue(this.$input.checked),this._callOnFinishChange()}),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.checked=this.getValue(),this}}function fD(t){let e,n;return(e=t.match(/(#|0x)?([a-f0-9]{6})/i))?n=e[2]:(e=t.match(/rgb\(\s*(\d*)\s*,\s*(\d*)\s*,\s*(\d*)\s*\)/))?n=parseInt(e[1]).toString(16).padStart(2,0)+parseInt(e[2]).toString(16).padStart(2,0)+parseInt(e[3]).toString(16).padStart(2,0):(e=t.match(/^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i))&&(n=e[1]+e[1]+e[2]+e[2]+e[3]+e[3]),n?"#"+n:!1}const sTe={isPrimitive:!0,match:t=>typeof t=="string",fromHexString:fD,toHexString:fD},Mv={isPrimitive:!0,match:t=>typeof t=="number",fromHexString:t=>parseInt(t.substring(1),16),toHexString:t=>"#"+t.toString(16).padStart(6,0)},oTe={isPrimitive:!1,match:t=>Array.isArray(t),fromHexString(t,e,n=1){const r=Mv.fromHexString(t);e[0]=(r>>16&255)/255*n,e[1]=(r>>8&255)/255*n,e[2]=(r&255)/255*n},toHexString([t,e,n],r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return Mv.toHexString(a)}},lTe={isPrimitive:!1,match:t=>Object(t)===t,fromHexString(t,e,n=1){const r=Mv.fromHexString(t);e.r=(r>>16&255)/255*n,e.g=(r>>8&255)/255*n,e.b=(r&255)/255*n},toHexString({r:t,g:e,b:n},r=1){r=255/r;const a=t*r<<16^e*r<<8^n*r<<0;return Mv.toHexString(a)}},cTe=[sTe,Mv,oTe,lTe];function uTe(t){return cTe.find(e=>e.match(t))}class dTe extends Dc{constructor(e,n,r,a){super(e,n,r,"color"),this.$input=document.createElement("input"),this.$input.setAttribute("type","color"),this.$input.setAttribute("tabindex",-1),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$text=document.createElement("input"),this.$text.setAttribute("type","text"),this.$text.setAttribute("spellcheck","false"),this.$text.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$display.appendChild(this.$input),this.$widget.appendChild(this.$display),this.$widget.appendChild(this.$text),this._format=uTe(this.initialValue),this._rgbScale=a,this._initialValueHexString=this.save(),this._textFocused=!1,this.$input.addEventListener("input",()=>{this._setValueFromHexString(this.$input.value)}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$text.addEventListener("input",()=>{const s=fD(this.$text.value);s&&this._setValueFromHexString(s)}),this.$text.addEventListener("focus",()=>{this._textFocused=!0,this.$text.select()}),this.$text.addEventListener("blur",()=>{this._textFocused=!1,this.updateDisplay(),this._callOnFinishChange()}),this.$disable=this.$text,this.updateDisplay()}reset(){return this._setValueFromHexString(this._initialValueHexString),this}_setValueFromHexString(e){if(this._format.isPrimitive){const n=this._format.fromHexString(e);this.setValue(n)}else this._format.fromHexString(e,this.getValue(),this._rgbScale),this._callOnChange(),this.updateDisplay()}save(){return this._format.toHexString(this.getValue(),this._rgbScale)}load(e){return this._setValueFromHexString(e),this._callOnFinishChange(),this}updateDisplay(){return this.$input.value=this._format.toHexString(this.getValue(),this._rgbScale),this._textFocused||(this.$text.value=this.$input.value.substring(1)),this.$display.style.backgroundColor=this.$input.value,this}}class tE extends Dc{constructor(e,n,r){super(e,n,r,"function"),this.$button=document.createElement("button"),this.$button.appendChild(this.$name),this.$widget.appendChild(this.$button),this.$button.addEventListener("click",a=>{a.preventDefault(),this.getValue().call(this.object),this._callOnChange()}),this.$button.addEventListener("touchstart",()=>{},{passive:!0}),this.$disable=this.$button}}class hTe extends Dc{constructor(e,n,r,a,s,o){super(e,n,r,"number"),this._initInput(),this.min(a),this.max(s);const l=o!==void 0;this.step(l?o:this._getImplicitStep(),l),this.updateDisplay()}decimals(e){return this._decimals=e,this.updateDisplay(),this}min(e){return this._min=e,this._onUpdateMinMax(),this}max(e){return this._max=e,this._onUpdateMinMax(),this}step(e,n=!0){return this._step=e,this._stepExplicit=n,this}updateDisplay(){const e=this.getValue();if(this._hasSlider){let n=(e-this._min)/(this._max-this._min);n=Math.max(0,Math.min(n,1)),this.$fill.style.width=n*100+"%"}return this._inputFocused||(this.$input.value=this._decimals===void 0?e:e.toFixed(this._decimals)),this}_initInput(){this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("aria-labelledby",this.$name.id),window.matchMedia("(pointer: coarse)").matches&&(this.$input.setAttribute("type","number"),this.$input.setAttribute("step","any")),this.$widget.appendChild(this.$input),this.$disable=this.$input;const n=()=>{let _=parseFloat(this.$input.value);isNaN(_)||(this._stepExplicit&&(_=this._snap(_)),this.setValue(this._clamp(_)))},r=_=>{const N=parseFloat(this.$input.value);isNaN(N)||(this._snapClampSetValue(N+_),this.$input.value=this.getValue())},a=_=>{_.key==="Enter"&&this.$input.blur(),_.code==="ArrowUp"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_))),_.code==="ArrowDown"&&(_.preventDefault(),r(this._step*this._arrowKeyMultiplier(_)*-1))},s=_=>{this._inputFocused&&(_.preventDefault(),r(this._step*this._normalizeMouseWheel(_)))};let o=!1,l,c,u,d,h;const f=5,p=_=>{l=_.clientX,c=u=_.clientY,o=!0,d=this.getValue(),h=0,window.addEventListener("mousemove",x),window.addEventListener("mouseup",v)},x=_=>{if(o){const N=_.clientX-l,k=_.clientY-c;Math.abs(k)>f?(_.preventDefault(),this.$input.blur(),o=!1,this._setDraggingStyle(!0,"vertical")):Math.abs(N)>f&&v()}if(!o){const N=_.clientY-u;h-=N*this._step*this._arrowKeyMultiplier(_),d+h>this._max?h=this._max-d:d+h<this._min&&(h=this._min-d),this._snapClampSetValue(d+h)}u=_.clientY},v=()=>{this._setDraggingStyle(!1,"vertical"),this._callOnFinishChange(),window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",v)},g=()=>{this._inputFocused=!0},y=()=>{this._inputFocused=!1,this.updateDisplay(),this._callOnFinishChange()};this.$input.addEventListener("input",n),this.$input.addEventListener("keydown",a),this.$input.addEventListener("wheel",s,{passive:!1}),this.$input.addEventListener("mousedown",p),this.$input.addEventListener("focus",g),this.$input.addEventListener("blur",y)}_initSlider(){this._hasSlider=!0,this.$slider=document.createElement("div"),this.$slider.classList.add("slider"),this.$fill=document.createElement("div"),this.$fill.classList.add("fill"),this.$slider.appendChild(this.$fill),this.$widget.insertBefore(this.$slider,this.$input),this.domElement.classList.add("hasSlider");const e=(y,_,N,k,A)=>(y-_)/(N-_)*(A-k)+k,n=y=>{const _=this.$slider.getBoundingClientRect();let N=e(y,_.left,_.right,this._min,this._max);this._snapClampSetValue(N)},r=y=>{this._setDraggingStyle(!0),n(y.clientX),window.addEventListener("mousemove",a),window.addEventListener("mouseup",s)},a=y=>{n(y.clientX)},s=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",s)};let o=!1,l,c;const u=y=>{y.preventDefault(),this._setDraggingStyle(!0),n(y.touches[0].clientX),o=!1},d=y=>{y.touches.length>1||(this._hasScrollBar?(l=y.touches[0].clientX,c=y.touches[0].clientY,o=!0):u(y),window.addEventListener("touchmove",h,{passive:!1}),window.addEventListener("touchend",f))},h=y=>{if(o){const _=y.touches[0].clientX-l,N=y.touches[0].clientY-c;Math.abs(_)>Math.abs(N)?u(y):(window.removeEventListener("touchmove",h),window.removeEventListener("touchend",f))}else y.preventDefault(),n(y.touches[0].clientX)},f=()=>{this._callOnFinishChange(),this._setDraggingStyle(!1),window.removeEventListener("touchmove",h),window.removeEventListener("touchend",f)},p=this._callOnFinishChange.bind(this),x=400;let v;const g=y=>{if(Math.abs(y.deltaX)<Math.abs(y.deltaY)&&this._hasScrollBar)return;y.preventDefault();const N=this._normalizeMouseWheel(y)*this._step;this._snapClampSetValue(this.getValue()+N),this.$input.value=this.getValue(),clearTimeout(v),v=setTimeout(p,x)};this.$slider.addEventListener("mousedown",r),this.$slider.addEventListener("touchstart",d,{passive:!1}),this.$slider.addEventListener("wheel",g,{passive:!1})}_setDraggingStyle(e,n="horizontal"){this.$slider&&this.$slider.classList.toggle("active",e),document.body.classList.toggle("lil-gui-dragging",e),document.body.classList.toggle(`lil-gui-${n}`,e)}_getImplicitStep(){return this._hasMin&&this._hasMax?(this._max-this._min)/1e3:.1}_onUpdateMinMax(){!this._hasSlider&&this._hasMin&&this._hasMax&&(this._stepExplicit||this.step(this._getImplicitStep(),!1),this._initSlider(),this.updateDisplay())}_normalizeMouseWheel(e){let{deltaX:n,deltaY:r}=e;return Math.floor(e.deltaY)!==e.deltaY&&e.wheelDelta&&(n=0,r=-e.wheelDelta/120,r*=this._stepExplicit?1:10),n+-r}_arrowKeyMultiplier(e){let n=this._stepExplicit?1:10;return e.shiftKey?n*=10:e.altKey&&(n/=10),n}_snap(e){const n=Math.round(e/this._step)*this._step;return parseFloat(n.toPrecision(15))}_clamp(e){return e<this._min&&(e=this._min),e>this._max&&(e=this._max),e}_snapClampSetValue(e){this.setValue(this._clamp(this._snap(e)))}get _hasScrollBar(){const e=this.parent.root.$children;return e.scrollHeight>e.clientHeight}get _hasMin(){return this._min!==void 0}get _hasMax(){return this._max!==void 0}}class mTe extends Dc{constructor(e,n,r,a){super(e,n,r,"option"),this.$select=document.createElement("select"),this.$select.setAttribute("aria-labelledby",this.$name.id),this.$display=document.createElement("div"),this.$display.classList.add("display"),this.$select.addEventListener("change",()=>{this.setValue(this._values[this.$select.selectedIndex]),this._callOnFinishChange()}),this.$select.addEventListener("focus",()=>{this.$display.classList.add("focus")}),this.$select.addEventListener("blur",()=>{this.$display.classList.remove("focus")}),this.$widget.appendChild(this.$select),this.$widget.appendChild(this.$display),this.$disable=this.$select,this.options(a)}options(e){return this._values=Array.isArray(e)?e:Object.values(e),this._names=Array.isArray(e)?e:Object.keys(e),this.$select.replaceChildren(),this._names.forEach(n=>{const r=document.createElement("option");r.textContent=n,this.$select.appendChild(r)}),this.updateDisplay(),this}updateDisplay(){const e=this.getValue(),n=this._values.indexOf(e);return this.$select.selectedIndex=n,this.$display.textContent=n===-1?e:this._names[n],this}}class fTe extends Dc{constructor(e,n,r){super(e,n,r,"string"),this.$input=document.createElement("input"),this.$input.setAttribute("type","text"),this.$input.setAttribute("spellcheck","false"),this.$input.setAttribute("aria-labelledby",this.$name.id),this.$input.addEventListener("input",()=>{this.setValue(this.$input.value)}),this.$input.addEventListener("keydown",a=>{a.code==="Enter"&&this.$input.blur()}),this.$input.addEventListener("blur",()=>{this._callOnFinishChange()}),this.$widget.appendChild(this.$input),this.$disable=this.$input,this.updateDisplay()}updateDisplay(){return this.$input.value=this.getValue(),this}}const pTe=`.lil-gui {
  7397. font-family: var(--font-family);
  7398. font-size: var(--font-size);
  7399. line-height: 1;
  7400. font-weight: normal;
  7401. font-style: normal;
  7402. text-align: left;
  7403. color: var(--text-color);
  7404. user-select: none;
  7405. -webkit-user-select: none;
  7406. touch-action: manipulation;
  7407. --background-color: #1f1f1f;
  7408. --text-color: #ebebeb;
  7409. --title-background-color: #111111;
  7410. --title-text-color: #ebebeb;
  7411. --widget-color: #424242;
  7412. --hover-color: #4f4f4f;
  7413. --focus-color: #595959;
  7414. --number-color: #2cc9ff;
  7415. --string-color: #a2db3c;
  7416. --font-size: 11px;
  7417. --input-font-size: 11px;
  7418. --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
  7419. --font-family-mono: Menlo, Monaco, Consolas, "Droid Sans Mono", monospace;
  7420. --padding: 4px;
  7421. --spacing: 4px;
  7422. --widget-height: 20px;
  7423. --title-height: calc(var(--widget-height) + var(--spacing) * 1.25);
  7424. --name-width: 45%;
  7425. --slider-knob-width: 2px;
  7426. --slider-input-width: 27%;
  7427. --color-input-width: 27%;
  7428. --slider-input-min-width: 45px;
  7429. --color-input-min-width: 45px;
  7430. --folder-indent: 7px;
  7431. --widget-padding: 0 0 0 3px;
  7432. --widget-border-radius: 2px;
  7433. --checkbox-size: calc(0.75 * var(--widget-height));
  7434. --scrollbar-width: 5px;
  7435. }
  7436. .lil-gui, .lil-gui * {
  7437. box-sizing: border-box;
  7438. margin: 0;
  7439. padding: 0;
  7440. }
  7441. .lil-gui.root {
  7442. width: var(--width, 245px);
  7443. display: flex;
  7444. flex-direction: column;
  7445. background: var(--background-color);
  7446. }
  7447. .lil-gui.root > .title {
  7448. background: var(--title-background-color);
  7449. color: var(--title-text-color);
  7450. }
  7451. .lil-gui.root > .children {
  7452. overflow-x: hidden;
  7453. overflow-y: auto;
  7454. }
  7455. .lil-gui.root > .children::-webkit-scrollbar {
  7456. width: var(--scrollbar-width);
  7457. height: var(--scrollbar-width);
  7458. background: var(--background-color);
  7459. }
  7460. .lil-gui.root > .children::-webkit-scrollbar-thumb {
  7461. border-radius: var(--scrollbar-width);
  7462. background: var(--focus-color);
  7463. }
  7464. @media (pointer: coarse) {
  7465. .lil-gui.allow-touch-styles, .lil-gui.allow-touch-styles .lil-gui {
  7466. --widget-height: 28px;
  7467. --padding: 6px;
  7468. --spacing: 6px;
  7469. --font-size: 13px;
  7470. --input-font-size: 16px;
  7471. --folder-indent: 10px;
  7472. --scrollbar-width: 7px;
  7473. --slider-input-min-width: 50px;
  7474. --color-input-min-width: 65px;
  7475. }
  7476. }
  7477. .lil-gui.force-touch-styles, .lil-gui.force-touch-styles .lil-gui {
  7478. --widget-height: 28px;
  7479. --padding: 6px;
  7480. --spacing: 6px;
  7481. --font-size: 13px;
  7482. --input-font-size: 16px;
  7483. --folder-indent: 10px;
  7484. --scrollbar-width: 7px;
  7485. --slider-input-min-width: 50px;
  7486. --color-input-min-width: 65px;
  7487. }
  7488. .lil-gui.autoPlace {
  7489. max-height: 100%;
  7490. position: fixed;
  7491. top: 0;
  7492. right: 15px;
  7493. z-index: 1001;
  7494. }
  7495. .lil-gui .controller {
  7496. display: flex;
  7497. align-items: center;
  7498. padding: 0 var(--padding);
  7499. margin: var(--spacing) 0;
  7500. }
  7501. .lil-gui .controller.disabled {
  7502. opacity: 0.5;
  7503. }
  7504. .lil-gui .controller.disabled, .lil-gui .controller.disabled * {
  7505. pointer-events: none !important;
  7506. }
  7507. .lil-gui .controller > .name {
  7508. min-width: var(--name-width);
  7509. flex-shrink: 0;
  7510. white-space: pre;
  7511. padding-right: var(--spacing);
  7512. line-height: var(--widget-height);
  7513. }
  7514. .lil-gui .controller .widget {
  7515. position: relative;
  7516. display: flex;
  7517. align-items: center;
  7518. width: 100%;
  7519. min-height: var(--widget-height);
  7520. }
  7521. .lil-gui .controller.string input {
  7522. color: var(--string-color);
  7523. }
  7524. .lil-gui .controller.boolean {
  7525. cursor: pointer;
  7526. }
  7527. .lil-gui .controller.color .display {
  7528. width: 100%;
  7529. height: var(--widget-height);
  7530. border-radius: var(--widget-border-radius);
  7531. position: relative;
  7532. }
  7533. @media (hover: hover) {
  7534. .lil-gui .controller.color .display:hover:before {
  7535. content: " ";
  7536. display: block;
  7537. position: absolute;
  7538. border-radius: var(--widget-border-radius);
  7539. border: 1px solid #fff9;
  7540. top: 0;
  7541. right: 0;
  7542. bottom: 0;
  7543. left: 0;
  7544. }
  7545. }
  7546. .lil-gui .controller.color input[type=color] {
  7547. opacity: 0;
  7548. width: 100%;
  7549. height: 100%;
  7550. cursor: pointer;
  7551. }
  7552. .lil-gui .controller.color input[type=text] {
  7553. margin-left: var(--spacing);
  7554. font-family: var(--font-family-mono);
  7555. min-width: var(--color-input-min-width);
  7556. width: var(--color-input-width);
  7557. flex-shrink: 0;
  7558. }
  7559. .lil-gui .controller.option select {
  7560. opacity: 0;
  7561. position: absolute;
  7562. width: 100%;
  7563. max-width: 100%;
  7564. }
  7565. .lil-gui .controller.option .display {
  7566. position: relative;
  7567. pointer-events: none;
  7568. border-radius: var(--widget-border-radius);
  7569. height: var(--widget-height);
  7570. line-height: var(--widget-height);
  7571. max-width: 100%;
  7572. overflow: hidden;
  7573. word-break: break-all;
  7574. padding-left: 0.55em;
  7575. padding-right: 1.75em;
  7576. background: var(--widget-color);
  7577. }
  7578. @media (hover: hover) {
  7579. .lil-gui .controller.option .display.focus {
  7580. background: var(--focus-color);
  7581. }
  7582. }
  7583. .lil-gui .controller.option .display.active {
  7584. background: var(--focus-color);
  7585. }
  7586. .lil-gui .controller.option .display:after {
  7587. font-family: "lil-gui";
  7588. content: "↕";
  7589. position: absolute;
  7590. top: 0;
  7591. right: 0;
  7592. bottom: 0;
  7593. padding-right: 0.375em;
  7594. }
  7595. .lil-gui .controller.option .widget,
  7596. .lil-gui .controller.option select {
  7597. cursor: pointer;
  7598. }
  7599. @media (hover: hover) {
  7600. .lil-gui .controller.option .widget:hover .display {
  7601. background: var(--hover-color);
  7602. }
  7603. }
  7604. .lil-gui .controller.number input {
  7605. color: var(--number-color);
  7606. }
  7607. .lil-gui .controller.number.hasSlider input {
  7608. margin-left: var(--spacing);
  7609. width: var(--slider-input-width);
  7610. min-width: var(--slider-input-min-width);
  7611. flex-shrink: 0;
  7612. }
  7613. .lil-gui .controller.number .slider {
  7614. width: 100%;
  7615. height: var(--widget-height);
  7616. background: var(--widget-color);
  7617. border-radius: var(--widget-border-radius);
  7618. padding-right: var(--slider-knob-width);
  7619. overflow: hidden;
  7620. cursor: ew-resize;
  7621. touch-action: pan-y;
  7622. }
  7623. @media (hover: hover) {
  7624. .lil-gui .controller.number .slider:hover {
  7625. background: var(--hover-color);
  7626. }
  7627. }
  7628. .lil-gui .controller.number .slider.active {
  7629. background: var(--focus-color);
  7630. }
  7631. .lil-gui .controller.number .slider.active .fill {
  7632. opacity: 0.95;
  7633. }
  7634. .lil-gui .controller.number .fill {
  7635. height: 100%;
  7636. border-right: var(--slider-knob-width) solid var(--number-color);
  7637. box-sizing: content-box;
  7638. }
  7639. .lil-gui-dragging .lil-gui {
  7640. --hover-color: var(--widget-color);
  7641. }
  7642. .lil-gui-dragging * {
  7643. cursor: ew-resize !important;
  7644. }
  7645. .lil-gui-dragging.lil-gui-vertical * {
  7646. cursor: ns-resize !important;
  7647. }
  7648. .lil-gui .title {
  7649. height: var(--title-height);
  7650. line-height: calc(var(--title-height) - 4px);
  7651. font-weight: 600;
  7652. padding: 0 var(--padding);
  7653. -webkit-tap-highlight-color: transparent;
  7654. cursor: pointer;
  7655. outline: none;
  7656. text-decoration-skip: objects;
  7657. }
  7658. .lil-gui .title:before {
  7659. font-family: "lil-gui";
  7660. content: "▾";
  7661. padding-right: 2px;
  7662. display: inline-block;
  7663. }
  7664. .lil-gui .title:active {
  7665. background: var(--title-background-color);
  7666. opacity: 0.75;
  7667. }
  7668. @media (hover: hover) {
  7669. body:not(.lil-gui-dragging) .lil-gui .title:hover {
  7670. background: var(--title-background-color);
  7671. opacity: 0.85;
  7672. }
  7673. .lil-gui .title:focus {
  7674. text-decoration: underline var(--focus-color);
  7675. }
  7676. }
  7677. .lil-gui.root > .title:focus {
  7678. text-decoration: none !important;
  7679. }
  7680. .lil-gui.closed > .title:before {
  7681. content: "▸";
  7682. }
  7683. .lil-gui.closed > .children {
  7684. transform: translateY(-7px);
  7685. opacity: 0;
  7686. }
  7687. .lil-gui.closed:not(.transition) > .children {
  7688. display: none;
  7689. }
  7690. .lil-gui.transition > .children {
  7691. transition-duration: 300ms;
  7692. transition-property: height, opacity, transform;
  7693. transition-timing-function: cubic-bezier(0.2, 0.6, 0.35, 1);
  7694. overflow: hidden;
  7695. pointer-events: none;
  7696. }
  7697. .lil-gui .children:empty:before {
  7698. content: "Empty";
  7699. padding: 0 var(--padding);
  7700. margin: var(--spacing) 0;
  7701. display: block;
  7702. height: var(--widget-height);
  7703. font-style: italic;
  7704. line-height: var(--widget-height);
  7705. opacity: 0.5;
  7706. }
  7707. .lil-gui.root > .children > .lil-gui > .title {
  7708. border: 0 solid var(--widget-color);
  7709. border-width: 1px 0;
  7710. transition: border-color 300ms;
  7711. }
  7712. .lil-gui.root > .children > .lil-gui.closed > .title {
  7713. border-bottom-color: transparent;
  7714. }
  7715. .lil-gui + .controller {
  7716. border-top: 1px solid var(--widget-color);
  7717. margin-top: 0;
  7718. padding-top: var(--spacing);
  7719. }
  7720. .lil-gui .lil-gui .lil-gui > .title {
  7721. border: none;
  7722. }
  7723. .lil-gui .lil-gui .lil-gui > .children {
  7724. border: none;
  7725. margin-left: var(--folder-indent);
  7726. border-left: 2px solid var(--widget-color);
  7727. }
  7728. .lil-gui .lil-gui .controller {
  7729. border: none;
  7730. }
  7731. .lil-gui label, .lil-gui input, .lil-gui button {
  7732. -webkit-tap-highlight-color: transparent;
  7733. }
  7734. .lil-gui input {
  7735. border: 0;
  7736. outline: none;
  7737. font-family: var(--font-family);
  7738. font-size: var(--input-font-size);
  7739. border-radius: var(--widget-border-radius);
  7740. height: var(--widget-height);
  7741. background: var(--widget-color);
  7742. color: var(--text-color);
  7743. width: 100%;
  7744. }
  7745. @media (hover: hover) {
  7746. .lil-gui input:hover {
  7747. background: var(--hover-color);
  7748. }
  7749. .lil-gui input:active {
  7750. background: var(--focus-color);
  7751. }
  7752. }
  7753. .lil-gui input:disabled {
  7754. opacity: 1;
  7755. }
  7756. .lil-gui input[type=text],
  7757. .lil-gui input[type=number] {
  7758. padding: var(--widget-padding);
  7759. -moz-appearance: textfield;
  7760. }
  7761. .lil-gui input[type=text]:focus,
  7762. .lil-gui input[type=number]:focus {
  7763. background: var(--focus-color);
  7764. }
  7765. .lil-gui input[type=checkbox] {
  7766. appearance: none;
  7767. width: var(--checkbox-size);
  7768. height: var(--checkbox-size);
  7769. border-radius: var(--widget-border-radius);
  7770. text-align: center;
  7771. cursor: pointer;
  7772. }
  7773. .lil-gui input[type=checkbox]:checked:before {
  7774. font-family: "lil-gui";
  7775. content: "✓";
  7776. font-size: var(--checkbox-size);
  7777. line-height: var(--checkbox-size);
  7778. }
  7779. @media (hover: hover) {
  7780. .lil-gui input[type=checkbox]:focus {
  7781. box-shadow: inset 0 0 0 1px var(--focus-color);
  7782. }
  7783. }
  7784. .lil-gui button {
  7785. outline: none;
  7786. cursor: pointer;
  7787. font-family: var(--font-family);
  7788. font-size: var(--font-size);
  7789. color: var(--text-color);
  7790. width: 100%;
  7791. height: var(--widget-height);
  7792. text-transform: none;
  7793. background: var(--widget-color);
  7794. border-radius: var(--widget-border-radius);
  7795. border: none;
  7796. }
  7797. @media (hover: hover) {
  7798. .lil-gui button:hover {
  7799. background: var(--hover-color);
  7800. }
  7801. .lil-gui button:focus {
  7802. box-shadow: inset 0 0 0 1px var(--focus-color);
  7803. }
  7804. }
  7805. .lil-gui button:active {
  7806. background: var(--focus-color);
  7807. }
  7808. @font-face {
  7809. font-family: "lil-gui";
  7810. src: url("data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAAUsAAsAAAAACJwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAAH4AAADAImwmYE9TLzIAAAGIAAAAPwAAAGBKqH5SY21hcAAAAcgAAAD0AAACrukyyJBnbHlmAAACvAAAAF8AAACEIZpWH2hlYWQAAAMcAAAAJwAAADZfcj2zaGhlYQAAA0QAAAAYAAAAJAC5AHhobXR4AAADXAAAABAAAABMAZAAAGxvY2EAAANsAAAAFAAAACgCEgIybWF4cAAAA4AAAAAeAAAAIAEfABJuYW1lAAADoAAAASIAAAIK9SUU/XBvc3QAAATEAAAAZgAAAJCTcMc2eJxVjbEOgjAURU+hFRBK1dGRL+ALnAiToyMLEzFpnPz/eAshwSa97517c/MwwJmeB9kwPl+0cf5+uGPZXsqPu4nvZabcSZldZ6kfyWnomFY/eScKqZNWupKJO6kXN3K9uCVoL7iInPr1X5baXs3tjuMqCtzEuagm/AAlzQgPAAB4nGNgYRBlnMDAysDAYM/gBiT5oLQBAwuDJAMDEwMrMwNWEJDmmsJwgCFeXZghBcjlZMgFCzOiKOIFAB71Bb8AeJy1kjFuwkAQRZ+DwRAwBtNQRUGKQ8OdKCAWUhAgKLhIuAsVSpWz5Bbkj3dEgYiUIszqWdpZe+Z7/wB1oCYmIoboiwiLT2WjKl/jscrHfGg/pKdMkyklC5Zs2LEfHYpjcRoPzme9MWWmk3dWbK9ObkWkikOetJ554fWyoEsmdSlt+uR0pCJR34b6t/TVg1SY3sYvdf8vuiKrpyaDXDISiegp17p7579Gp3p++y7HPAiY9pmTibljrr85qSidtlg4+l25GLCaS8e6rRxNBmsnERunKbaOObRz7N72ju5vdAjYpBXHgJylOAVsMseDAPEP8LYoUHicY2BiAAEfhiAGJgZWBgZ7RnFRdnVJELCQlBSRlATJMoLV2DK4glSYs6ubq5vbKrJLSbGrgEmovDuDJVhe3VzcXFwNLCOILB/C4IuQ1xTn5FPilBTj5FPmBAB4WwoqAHicY2BkYGAA4sk1sR/j+W2+MnAzpDBgAyEMQUCSg4EJxAEAwUgFHgB4nGNgZGBgSGFggJMhDIwMqEAYAByHATJ4nGNgAIIUNEwmAABl3AGReJxjYAACIQYlBiMGJ3wQAEcQBEV4nGNgZGBgEGZgY2BiAAEQyQWEDAz/wXwGAAsPATIAAHicXdBNSsNAHAXwl35iA0UQXYnMShfS9GPZA7T7LgIu03SSpkwzYTIt1BN4Ak/gKTyAeCxfw39jZkjymzcvAwmAW/wgwHUEGDb36+jQQ3GXGot79L24jxCP4gHzF/EIr4jEIe7wxhOC3g2TMYy4Q7+Lu/SHuEd/ivt4wJd4wPxbPEKMX3GI5+DJFGaSn4qNzk8mcbKSR6xdXdhSzaOZJGtdapd4vVPbi6rP+cL7TGXOHtXKll4bY1Xl7EGnPtp7Xy2n00zyKLVHfkHBa4IcJ2oD3cgggWvt/V/FbDrUlEUJhTn/0azVWbNTNr0Ens8de1tceK9xZmfB1CPjOmPH4kitmvOubcNpmVTN3oFJyjzCvnmrwhJTzqzVj9jiSX911FjeAAB4nG3HMRKCMBBA0f0giiKi4DU8k0V2GWbIZDOh4PoWWvq6J5V8If9NVNQcaDhyouXMhY4rPTcG7jwYmXhKq8Wz+p762aNaeYXom2n3m2dLTVgsrCgFJ7OTmIkYbwIbC6vIB7WmFfAAAA==") format("woff");
  7811. }`;function gTe(t){const e=document.createElement("style");e.innerHTML=t;const n=document.querySelector("head link[rel=stylesheet], head style");n?document.head.insertBefore(e,n):document.head.appendChild(e)}let RH=!1;class I1{constructor({parent:e,autoPlace:n=e===void 0,container:r,width:a,title:s="Controls",closeFolders:o=!1,injectStyles:l=!0,touchStyles:c=!0}={}){if(this.parent=e,this.root=e?e.root:this,this.children=[],this.controllers=[],this.folders=[],this._closed=!1,this._hidden=!1,this.domElement=document.createElement("div"),this.domElement.classList.add("lil-gui"),this.$title=document.createElement("div"),this.$title.classList.add("title"),this.$title.setAttribute("role","button"),this.$title.setAttribute("aria-expanded",!0),this.$title.setAttribute("tabindex",0),this.$title.addEventListener("click",()=>this.openAnimated(this._closed)),this.$title.addEventListener("keydown",u=>{(u.code==="Enter"||u.code==="Space")&&(u.preventDefault(),this.$title.click())}),this.$title.addEventListener("touchstart",()=>{},{passive:!0}),this.$children=document.createElement("div"),this.$children.classList.add("children"),this.domElement.appendChild(this.$title),this.domElement.appendChild(this.$children),this.title(s),this.parent){this.parent.children.push(this),this.parent.folders.push(this),this.parent.$children.appendChild(this.domElement);return}this.domElement.classList.add("root"),c&&this.domElement.classList.add("allow-touch-styles"),!RH&&l&&(gTe(pTe),RH=!0),r?r.appendChild(this.domElement):n&&(this.domElement.classList.add("autoPlace"),document.body.appendChild(this.domElement)),a&&this.domElement.style.setProperty("--width",a+"px"),this._closeFolders=o}add(e,n,r,a,s){if(Object(r)===r)return new mTe(this,e,n,r);const o=e[n];switch(typeof o){case"number":return new hTe(this,e,n,r,a,s);case"boolean":return new iTe(this,e,n);case"string":return new fTe(this,e,n);case"function":return new tE(this,e,n)}console.error(`gui.add failed
  7812. property:`,n,`
  7813. object:`,e,`
  7814. value:`,o)}addColor(e,n,r=1){return new dTe(this,e,n,r)}addFolder(e){const n=new I1({parent:this,title:e});return this.root._closeFolders&&n.close(),n}load(e,n=!0){return e.controllers&&this.controllers.forEach(r=>{r instanceof tE||r._name in e.controllers&&r.load(e.controllers[r._name])}),n&&e.folders&&this.folders.forEach(r=>{r._title in e.folders&&r.load(e.folders[r._title])}),this}save(e=!0){const n={controllers:{},folders:{}};return this.controllers.forEach(r=>{if(!(r instanceof tE)){if(r._name in n.controllers)throw new Error(`Cannot save GUI with duplicate property "${r._name}"`);n.controllers[r._name]=r.save()}}),e&&this.folders.forEach(r=>{if(r._title in n.folders)throw new Error(`Cannot save GUI with duplicate folder "${r._title}"`);n.folders[r._title]=r.save()}),n}open(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),this.domElement.classList.toggle("closed",this._closed),this}close(){return this.open(!1)}_setClosed(e){this._closed!==e&&(this._closed=e,this._callOnOpenClose(this))}show(e=!0){return this._hidden=!e,this.domElement.style.display=this._hidden?"none":"",this}hide(){return this.show(!1)}openAnimated(e=!0){return this._setClosed(!e),this.$title.setAttribute("aria-expanded",!this._closed),requestAnimationFrame(()=>{const n=this.$children.clientHeight;this.$children.style.height=n+"px",this.domElement.classList.add("transition");const r=s=>{s.target===this.$children&&(this.$children.style.height="",this.domElement.classList.remove("transition"),this.$children.removeEventListener("transitionend",r))};this.$children.addEventListener("transitionend",r);const a=e?this.$children.scrollHeight:0;this.domElement.classList.toggle("closed",!e),requestAnimationFrame(()=>{this.$children.style.height=a+"px"})}),this}title(e){return this._title=e,this.$title.textContent=e,this}reset(e=!0){return(e?this.controllersRecursive():this.controllers).forEach(r=>r.reset()),this}onChange(e){return this._onChange=e,this}_callOnChange(e){this.parent&&this.parent._callOnChange(e),this._onChange!==void 0&&this._onChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onFinishChange(e){return this._onFinishChange=e,this}_callOnFinishChange(e){this.parent&&this.parent._callOnFinishChange(e),this._onFinishChange!==void 0&&this._onFinishChange.call(this,{object:e.object,property:e.property,value:e.getValue(),controller:e})}onOpenClose(e){return this._onOpenClose=e,this}_callOnOpenClose(e){this.parent&&this.parent._callOnOpenClose(e),this._onOpenClose!==void 0&&this._onOpenClose.call(this,e)}destroy(){this.parent&&(this.parent.children.splice(this.parent.children.indexOf(this),1),this.parent.folders.splice(this.parent.folders.indexOf(this),1)),this.domElement.parentElement&&this.domElement.parentElement.removeChild(this.domElement),Array.from(this.children).forEach(e=>e.destroy())}controllersRecursive(){let e=Array.from(this.controllers);return this.folders.forEach(n=>{e=e.concat(n.controllersRecursive())}),e}foldersRecursive(){let e=Array.from(this.folders);return this.folders.forEach(n=>{e=e.concat(n.foldersRecursive())}),e}}function nE(t,e,n,r){return new(n||(n=Promise))((function(a,s){function o(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){var d;u.done?a(u.value):(d=u.value,d instanceof n?d:new n((function(h){h(d)}))).then(o,l)}c((r=r.apply(t,[])).next())}))}class sL{constructor(e,n,r,a){this.size=e,this.width=n,this.height=r,this.charLength=a,this.chars=""}static parse(e){const n=e.split(" "),r=n[0],a=r.split("x");return new sL(r,+a[0],+a[1],+n[1])}get src(){return"data:image/jpeg;base64,"+this.chars}get isValid(){return this.chars.length==this.charLength&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(this.chars)}}class oL{constructor(e,n,r,a){this.src=e,this.gcode=n,this.params=r,this.comment=a}}class FH extends oL{constructor(e,n,r,a){super(e,n,r,a),this.params=r}}class eh extends oL{constructor(e,n,r,a){super(e,n,void 0,r),this.toolIndex=a}}class LH{constructor(e,n,r,a=0){this.layer=e,this.commands=n,this.lineNumber=r,this.height=a}}class z1{constructor(e){this.lines=[],this.preamble=new LH(-1,[],0),this.layers=[],this.curZ=0,this.maxZ=0,this.metadata={thumbnails:{}},this.tolerance=0,this.tolerance=e??this.tolerance}parseGCode(e){const n=Array.isArray(e)?e:e.split(`
  7815. `);this.lines=this.lines.concat(n);const r=this.lines2commands(n);this.groupIntoLayers(r);const a=this.parseMetadata(r.filter((s=>s.comment))).thumbnails;for(const[s,o]of Object.entries(a))this.metadata.thumbnails[s]=o;return{layers:this.layers,metadata:this.metadata}}lines2commands(e){return e.map((n=>this.parseCommand(n)))}parseCommand(e,n=!0){var r;const a=e.trim().split(";"),s=a[0],o=n&&a[1]||void 0,l=s.split(/([a-zA-Z])/g).slice(1).map((d=>d.trim())),c=l.length?`${(r=l[0])===null||r===void 0?void 0:r.toLowerCase()}${l[1]}`:"",u=this.parseParams(l.slice(2));switch(c){case"g0":case"g00":case"g1":case"g01":case"g2":case"g02":case"g3":case"g03":return new FH(e,c,u,o);case"t0":return new eh(e,c,o,0);case"t1":return new eh(e,c,o,1);case"t2":return new eh(e,c,o,2);case"t3":return new eh(e,c,o,3);case"t4":return new eh(e,c,o,4);case"t5":return new eh(e,c,o,5);case"t6":return new eh(e,c,o,6);case"t7":return new eh(e,c,o,7);default:return new oL(e,c,u,o)}}parseMove(e){return e.reduce(((n,r)=>{const a=r.charAt(0).toLowerCase();return a!="x"&&a!="y"&&a!="z"&&a!="e"&&a!="r"&&a!="f"&&a!="i"&&a!="j"||(n[a]=parseFloat(r.slice(1))),n}),{})}isAlpha(e){const n=e.charCodeAt(0);return n>=97&&n<=122||n>=65&&n<=90}parseParams(e){return e.reduce(((n,r,a,s)=>{if(a%2==0)return n;let o=s[a-1];return o=o.toLowerCase(),this.isAlpha(o)&&(n[o]=parseFloat(r)),n}),{})}groupIntoLayers(e){var n;for(let r=0;r<e.length;r++){const a=e[r];if(a instanceof FH){const s=a.params;if(s.z&&(this.curZ=s.z),((n=s.e)!==null&&n!==void 0?n:0)>0&&(s.x!=null||s.y!=null)&&Math.abs(this.curZ-(this.maxZ||-1/0))>this.tolerance){const o=Math.abs(this.curZ-this.maxZ);this.maxZ=this.curZ,this.layers.push(new LH(this.layers.length,[],r,o))}}this.maxLayer.commands.push(a)}return this.layers}get maxLayer(){var e;return(e=this.layers[this.layers.length-1])!==null&&e!==void 0?e:this.preamble}parseMetadata(e){const n={};let r;for(const a of e){const s=a.comment;if(!s)continue;const o=s.indexOf("thumbnail begin"),l=s.indexOf("thumbnail end");o>-1?r=sL.parse(s.slice(o+15).trim()):r&&(l==-1?r.chars+=s.trim():(r.isValid&&(n[r.size]=r),r=void 0))}return{thumbnails:n}}}z1.prototype.parseGcode=z1.prototype.parseGCode;const OH={type:"change"},rE={type:"start"},IH={type:"end"},t_=new tL,zH=new sh,bTe=Math.cos(70*EY.DEG2RAD);class xTe extends rp{constructor(e,n){super(),this.object=e,this.domElement=n,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new Ze,this.cursor=new Ze,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:ng.ROTATE,MIDDLE:ng.DOLLY,RIGHT:ng.PAN},this.touches={ONE:rg.ROTATE,TWO:rg.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this.getPolarAngle=function(){return l.phi},this.getAzimuthalAngle=function(){return l.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(Y){Y.addEventListener("keydown",_e),this._domElementKeyEvents=Y},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",_e),this._domElementKeyEvents=null},this.saveState=function(){r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=function(){r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(OH),r.update(),s=a.NONE},this.update=(function(){const Y=new Ze,me=new zf().setFromUnitVectors(e.up,new Ze(0,1,0)),Q=me.clone().invert(),se=new Ze,de=new zf,Le=new Ze,Ne=2*Math.PI;return function(be=null){const O=r.object.position;Y.copy(O).sub(r.target),Y.applyQuaternion(me),l.setFromVector3(Y),r.autoRotate&&s===a.NONE&&E((function(fe){return fe!==null?2*Math.PI/60*r.autoRotateSpeed*fe:2*Math.PI/60/60*r.autoRotateSpeed})(be)),r.enableDamping?(l.theta+=c.theta*r.dampingFactor,l.phi+=c.phi*r.dampingFactor):(l.theta+=c.theta,l.phi+=c.phi);let R=r.minAzimuthAngle,q=r.maxAzimuthAngle;isFinite(R)&&isFinite(q)&&(R<-Math.PI?R+=Ne:R>Math.PI&&(R-=Ne),q<-Math.PI?q+=Ne:q>Math.PI&&(q-=Ne),l.theta=R<=q?Math.max(R,Math.min(q,l.theta)):l.theta>(R+q)/2?Math.max(R,l.theta):Math.min(q,l.theta)),l.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,l.phi)),l.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(d,r.dampingFactor):r.target.add(d),r.target.sub(r.cursor),r.target.clampLength(r.minTargetRadius,r.maxTargetRadius),r.target.add(r.cursor),r.zoomToCursor&&M||r.object.isOrthographicCamera?l.radius=W(l.radius):l.radius=W(l.radius*u),Y.setFromSpherical(l),Y.applyQuaternion(Q),O.copy(r.target).add(Y),r.object.lookAt(r.target),r.enableDamping===!0?(c.theta*=1-r.dampingFactor,c.phi*=1-r.dampingFactor,d.multiplyScalar(1-r.dampingFactor)):(c.set(0,0,0),d.set(0,0,0));let J=!1;if(r.zoomToCursor&&M){let fe=null;if(r.object.isPerspectiveCamera){const le=Y.length();fe=W(le*u);const Be=le-fe;r.object.position.addScaledVector(k,Be),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const le=new Ze(A.x,A.y,0);le.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/u)),r.object.updateProjectionMatrix(),J=!0;const Be=new Ze(A.x,A.y,0);Be.unproject(r.object),r.object.position.sub(Be).add(le),r.object.updateMatrixWorld(),fe=Y.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;fe!==null&&(this.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(fe).add(r.object.position):(t_.origin.copy(r.object.position),t_.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(t_.direction))<bTe?e.lookAt(r.target):(zH.setFromNormalAndCoplanarPoint(r.object.up,r.target),t_.intersectPlane(zH,r.target))))}else r.object.isOrthographicCamera&&(r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/u)),r.object.updateProjectionMatrix(),J=!0);return u=1,M=!1,!!(J||se.distanceToSquared(r.object.position)>o||8*(1-de.dot(r.object.quaternion))>o||Le.distanceToSquared(r.target)>0)&&(r.dispatchEvent(OH),se.copy(r.object.position),de.copy(r.object.quaternion),Le.copy(r.target),!0)}})(),this.dispose=function(){r.domElement.removeEventListener("contextmenu",ie),r.domElement.removeEventListener("pointerdown",ee),r.domElement.removeEventListener("pointercancel",he),r.domElement.removeEventListener("wheel",oe),r.domElement.removeEventListener("pointermove",je),r.domElement.removeEventListener("pointerup",he),r._domElementKeyEvents!==null&&(r._domElementKeyEvents.removeEventListener("keydown",_e),r._domElementKeyEvents=null)};const r=this,a={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let s=a.NONE;const o=1e-6,l=new jH,c=new jH;let u=1;const d=new Ze,h=new _n,f=new _n,p=new _n,x=new _n,v=new _n,g=new _n,y=new _n,_=new _n,N=new _n,k=new Ze,A=new _n;let M=!1;const C=[],j={};function P(){return Math.pow(.95,r.zoomSpeed)}function E(Y){c.theta-=Y}function U(Y){c.phi-=Y}const L=(function(){const Y=new Ze;return function(me,Q){Y.setFromMatrixColumn(Q,0),Y.multiplyScalar(-me),d.add(Y)}})(),B=(function(){const Y=new Ze;return function(me,Q){r.screenSpacePanning===!0?Y.setFromMatrixColumn(Q,1):(Y.setFromMatrixColumn(Q,0),Y.crossVectors(r.object.up,Y)),Y.multiplyScalar(me),d.add(Y)}})(),D=(function(){const Y=new Ze;return function(me,Q){const se=r.domElement;if(r.object.isPerspectiveCamera){const de=r.object.position;Y.copy(de).sub(r.target);let Le=Y.length();Le*=Math.tan(r.object.fov/2*Math.PI/180),L(2*me*Le/se.clientHeight,r.object.matrix),B(2*Q*Le/se.clientHeight,r.object.matrix)}else r.object.isOrthographicCamera?(L(me*(r.object.right-r.object.left)/r.object.zoom/se.clientWidth,r.object.matrix),B(Q*(r.object.top-r.object.bottom)/r.object.zoom/se.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function $(Y){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u/=Y:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function G(Y){r.object.isPerspectiveCamera||r.object.isOrthographicCamera?u*=Y:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function z(Y){if(!r.zoomToCursor)return;M=!0;const me=r.domElement.getBoundingClientRect(),Q=Y.clientX-me.left,se=Y.clientY-me.top,de=me.width,Le=me.height;A.x=Q/de*2-1,A.y=-se/Le*2+1,k.set(A.x,A.y,1).unproject(r.object).sub(r.object.position).normalize()}function W(Y){return Math.max(r.minDistance,Math.min(r.maxDistance,Y))}function X(Y){h.set(Y.clientX,Y.clientY)}function ae(Y){x.set(Y.clientX,Y.clientY)}function H(){if(C.length===1)h.set(C[0].pageX,C[0].pageY);else{const Y=.5*(C[0].pageX+C[1].pageX),me=.5*(C[0].pageY+C[1].pageY);h.set(Y,me)}}function K(){if(C.length===1)x.set(C[0].pageX,C[0].pageY);else{const Y=.5*(C[0].pageX+C[1].pageX),me=.5*(C[0].pageY+C[1].pageY);x.set(Y,me)}}function te(){const Y=C[0].pageX-C[1].pageX,me=C[0].pageY-C[1].pageY,Q=Math.sqrt(Y*Y+me*me);y.set(0,Q)}function Z(Y){if(C.length==1)f.set(Y.pageX,Y.pageY);else{const Q=V(Y),se=.5*(Y.pageX+Q.x),de=.5*(Y.pageY+Q.y);f.set(se,de)}p.subVectors(f,h).multiplyScalar(r.rotateSpeed);const me=r.domElement;E(2*Math.PI*p.x/me.clientHeight),U(2*Math.PI*p.y/me.clientHeight),h.copy(f)}function ve(Y){if(C.length===1)v.set(Y.pageX,Y.pageY);else{const me=V(Y),Q=.5*(Y.pageX+me.x),se=.5*(Y.pageY+me.y);v.set(Q,se)}g.subVectors(v,x).multiplyScalar(r.panSpeed),D(g.x,g.y),x.copy(v)}function ce(Y){const me=V(Y),Q=Y.pageX-me.x,se=Y.pageY-me.y,de=Math.sqrt(Q*Q+se*se);_.set(0,de),N.set(0,Math.pow(_.y/y.y,r.zoomSpeed)),$(N.y),y.copy(_)}function ee(Y){r.enabled!==!1&&(C.length===0&&(r.domElement.setPointerCapture(Y.pointerId),r.domElement.addEventListener("pointermove",je),r.domElement.addEventListener("pointerup",he)),(function(me){C.push(me)})(Y),Y.pointerType==="touch"?(function(me){switch(ze(me),C.length){case 1:switch(r.touches.ONE){case rg.ROTATE:if(r.enableRotate===!1)return;H(),s=a.TOUCH_ROTATE;break;case rg.PAN:if(r.enablePan===!1)return;K(),s=a.TOUCH_PAN;break;default:s=a.NONE}break;case 2:switch(r.touches.TWO){case rg.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;r.enableZoom&&te(),r.enablePan&&K(),s=a.TOUCH_DOLLY_PAN;break;case rg.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;r.enableZoom&&te(),r.enableRotate&&H(),s=a.TOUCH_DOLLY_ROTATE;break;default:s=a.NONE}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(rE)})(Y):(function(me){let Q;switch(me.button){case 0:Q=r.mouseButtons.LEFT;break;case 1:Q=r.mouseButtons.MIDDLE;break;case 2:Q=r.mouseButtons.RIGHT;break;default:Q=-1}switch(Q){case ng.DOLLY:if(r.enableZoom===!1)return;(function(se){z(se),y.set(se.clientX,se.clientY)})(me),s=a.DOLLY;break;case ng.ROTATE:if(me.ctrlKey||me.metaKey||me.shiftKey){if(r.enablePan===!1)return;ae(me),s=a.PAN}else{if(r.enableRotate===!1)return;X(me),s=a.ROTATE}break;case ng.PAN:if(me.ctrlKey||me.metaKey||me.shiftKey){if(r.enableRotate===!1)return;X(me),s=a.ROTATE}else{if(r.enablePan===!1)return;ae(me),s=a.PAN}break;default:s=a.NONE}s!==a.NONE&&r.dispatchEvent(rE)})(Y))}function je(Y){r.enabled!==!1&&(Y.pointerType==="touch"?(function(me){switch(ze(me),s){case a.TOUCH_ROTATE:if(r.enableRotate===!1)return;Z(me),r.update();break;case a.TOUCH_PAN:if(r.enablePan===!1)return;ve(me),r.update();break;case a.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;(function(Q){r.enableZoom&&ce(Q),r.enablePan&&ve(Q)})(me),r.update();break;case a.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;(function(Q){r.enableZoom&&ce(Q),r.enableRotate&&Z(Q)})(me),r.update();break;default:s=a.NONE}})(Y):(function(me){switch(s){case a.ROTATE:if(r.enableRotate===!1)return;(function(Q){f.set(Q.clientX,Q.clientY),p.subVectors(f,h).multiplyScalar(r.rotateSpeed);const se=r.domElement;E(2*Math.PI*p.x/se.clientHeight),U(2*Math.PI*p.y/se.clientHeight),h.copy(f),r.update()})(me);break;case a.DOLLY:if(r.enableZoom===!1)return;(function(Q){_.set(Q.clientX,Q.clientY),N.subVectors(_,y),N.y>0?$(P()):N.y<0&&G(P()),y.copy(_),r.update()})(me);break;case a.PAN:if(r.enablePan===!1)return;(function(Q){v.set(Q.clientX,Q.clientY),g.subVectors(v,x).multiplyScalar(r.panSpeed),D(g.x,g.y),x.copy(v),r.update()})(me)}})(Y))}function he(Y){(function(me){delete j[me.pointerId];for(let Q=0;Q<C.length;Q++)if(C[Q].pointerId==me.pointerId)return void C.splice(Q,1)})(Y),C.length===0&&(r.domElement.releasePointerCapture(Y.pointerId),r.domElement.removeEventListener("pointermove",je),r.domElement.removeEventListener("pointerup",he)),r.dispatchEvent(IH),s=a.NONE}function oe(Y){r.enabled!==!1&&r.enableZoom!==!1&&s===a.NONE&&(Y.preventDefault(),r.dispatchEvent(rE),(function(me){z(me),me.deltaY<0?G(P()):me.deltaY>0&&$(P()),r.update()})(Y),r.dispatchEvent(IH))}function _e(Y){r.enabled!==!1&&r.enablePan!==!1&&(function(me){let Q=!1;switch(me.code){case r.keys.UP:me.ctrlKey||me.metaKey||me.shiftKey?U(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):D(0,r.keyPanSpeed),Q=!0;break;case r.keys.BOTTOM:me.ctrlKey||me.metaKey||me.shiftKey?U(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):D(0,-r.keyPanSpeed),Q=!0;break;case r.keys.LEFT:me.ctrlKey||me.metaKey||me.shiftKey?E(2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):D(r.keyPanSpeed,0),Q=!0;break;case r.keys.RIGHT:me.ctrlKey||me.metaKey||me.shiftKey?E(-2*Math.PI*r.rotateSpeed/r.domElement.clientHeight):D(-r.keyPanSpeed,0),Q=!0}Q&&(me.preventDefault(),r.update())})(Y)}function ie(Y){r.enabled!==!1&&Y.preventDefault()}function ze(Y){let me=j[Y.pointerId];me===void 0&&(me=new _n,j[Y.pointerId]=me),me.set(Y.pageX,Y.pageY)}function V(Y){const me=Y.pointerId===C[0].pointerId?C[1]:C[0];return j[me.pointerId]}r.domElement.addEventListener("contextmenu",ie),r.domElement.addEventListener("pointerdown",ee),r.domElement.addEventListener("pointercancel",he),r.domElement.addEventListener("wheel",oe,{passive:!1}),this.update()}}Ut.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new _n(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Xs.line={uniforms:nL.merge([Ut.common,Ut.fog,Ut.line]),vertexShader:`
  7816. #include <common>
  7817. #include <color_pars_vertex>
  7818. #include <fog_pars_vertex>
  7819. #include <logdepthbuf_pars_vertex>
  7820. #include <clipping_planes_pars_vertex>
  7821. uniform float linewidth;
  7822. uniform vec2 resolution;
  7823. attribute vec3 instanceStart;
  7824. attribute vec3 instanceEnd;
  7825. attribute vec3 instanceColorStart;
  7826. attribute vec3 instanceColorEnd;
  7827. #ifdef WORLD_UNITS
  7828. varying vec4 worldPos;
  7829. varying vec3 worldStart;
  7830. varying vec3 worldEnd;
  7831. #ifdef USE_DASH
  7832. varying vec2 vUv;
  7833. #endif
  7834. #else
  7835. varying vec2 vUv;
  7836. #endif
  7837. #ifdef USE_DASH
  7838. uniform float dashScale;
  7839. attribute float instanceDistanceStart;
  7840. attribute float instanceDistanceEnd;
  7841. varying float vLineDistance;
  7842. #endif
  7843. void trimSegment( const in vec4 start, inout vec4 end ) {
  7844. // trim end segment so it terminates between the camera plane and the near plane
  7845. // conservative estimate of the near plane
  7846. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  7847. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  7848. float nearEstimate = - 0.5 * b / a;
  7849. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  7850. end.xyz = mix( start.xyz, end.xyz, alpha );
  7851. }
  7852. void main() {
  7853. #ifdef USE_COLOR
  7854. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  7855. #endif
  7856. #ifdef USE_DASH
  7857. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  7858. vUv = uv;
  7859. #endif
  7860. float aspect = resolution.x / resolution.y;
  7861. // camera space
  7862. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  7863. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  7864. #ifdef WORLD_UNITS
  7865. worldStart = start.xyz;
  7866. worldEnd = end.xyz;
  7867. #else
  7868. vUv = uv;
  7869. #endif
  7870. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  7871. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  7872. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  7873. // perhaps there is a more elegant solution -- WestLangley
  7874. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  7875. if ( perspective ) {
  7876. if ( start.z < 0.0 && end.z >= 0.0 ) {
  7877. trimSegment( start, end );
  7878. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  7879. trimSegment( end, start );
  7880. }
  7881. }
  7882. // clip space
  7883. vec4 clipStart = projectionMatrix * start;
  7884. vec4 clipEnd = projectionMatrix * end;
  7885. // ndc space
  7886. vec3 ndcStart = clipStart.xyz / clipStart.w;
  7887. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  7888. // direction
  7889. vec2 dir = ndcEnd.xy - ndcStart.xy;
  7890. // account for clip-space aspect ratio
  7891. dir.x *= aspect;
  7892. dir = normalize( dir );
  7893. #ifdef WORLD_UNITS
  7894. // get the offset direction as perpendicular to the view vector
  7895. vec3 worldDir = normalize( end.xyz - start.xyz );
  7896. vec3 offset;
  7897. if ( position.y < 0.5 ) {
  7898. offset = normalize( cross( start.xyz, worldDir ) );
  7899. } else {
  7900. offset = normalize( cross( end.xyz, worldDir ) );
  7901. }
  7902. // sign flip
  7903. if ( position.x < 0.0 ) offset *= - 1.0;
  7904. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  7905. // don't extend the line if we're rendering dashes because we
  7906. // won't be rendering the endcaps
  7907. #ifndef USE_DASH
  7908. // extend the line bounds to encompass endcaps
  7909. start.xyz += - worldDir * linewidth * 0.5;
  7910. end.xyz += worldDir * linewidth * 0.5;
  7911. // shift the position of the quad so it hugs the forward edge of the line
  7912. offset.xy -= dir * forwardOffset;
  7913. offset.z += 0.5;
  7914. #endif
  7915. // endcaps
  7916. if ( position.y > 1.0 || position.y < 0.0 ) {
  7917. offset.xy += dir * 2.0 * forwardOffset;
  7918. }
  7919. // adjust for linewidth
  7920. offset *= linewidth * 0.5;
  7921. // set the world position
  7922. worldPos = ( position.y < 0.5 ) ? start : end;
  7923. worldPos.xyz += offset;
  7924. // project the worldpos
  7925. vec4 clip = projectionMatrix * worldPos;
  7926. // shift the depth of the projected points so the line
  7927. // segments overlap neatly
  7928. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  7929. clip.z = clipPose.z * clip.w;
  7930. #else
  7931. vec2 offset = vec2( dir.y, - dir.x );
  7932. // undo aspect ratio adjustment
  7933. dir.x /= aspect;
  7934. offset.x /= aspect;
  7935. // sign flip
  7936. if ( position.x < 0.0 ) offset *= - 1.0;
  7937. // endcaps
  7938. if ( position.y < 0.0 ) {
  7939. offset += - dir;
  7940. } else if ( position.y > 1.0 ) {
  7941. offset += dir;
  7942. }
  7943. // adjust for linewidth
  7944. offset *= linewidth;
  7945. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  7946. offset /= resolution.y;
  7947. // select end
  7948. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  7949. // back to clip space
  7950. offset *= clip.w;
  7951. clip.xy += offset;
  7952. #endif
  7953. gl_Position = clip;
  7954. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  7955. #include <logdepthbuf_vertex>
  7956. #include <clipping_planes_vertex>
  7957. #include <fog_vertex>
  7958. }
  7959. `,fragmentShader:`
  7960. uniform vec3 diffuse;
  7961. uniform float opacity;
  7962. uniform float linewidth;
  7963. #ifdef USE_DASH
  7964. uniform float dashOffset;
  7965. uniform float dashSize;
  7966. uniform float gapSize;
  7967. #endif
  7968. varying float vLineDistance;
  7969. #ifdef WORLD_UNITS
  7970. varying vec4 worldPos;
  7971. varying vec3 worldStart;
  7972. varying vec3 worldEnd;
  7973. #ifdef USE_DASH
  7974. varying vec2 vUv;
  7975. #endif
  7976. #else
  7977. varying vec2 vUv;
  7978. #endif
  7979. #include <common>
  7980. #include <color_pars_fragment>
  7981. #include <fog_pars_fragment>
  7982. #include <logdepthbuf_pars_fragment>
  7983. #include <clipping_planes_pars_fragment>
  7984. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  7985. float mua;
  7986. float mub;
  7987. vec3 p13 = p1 - p3;
  7988. vec3 p43 = p4 - p3;
  7989. vec3 p21 = p2 - p1;
  7990. float d1343 = dot( p13, p43 );
  7991. float d4321 = dot( p43, p21 );
  7992. float d1321 = dot( p13, p21 );
  7993. float d4343 = dot( p43, p43 );
  7994. float d2121 = dot( p21, p21 );
  7995. float denom = d2121 * d4343 - d4321 * d4321;
  7996. float numer = d1343 * d4321 - d1321 * d4343;
  7997. mua = numer / denom;
  7998. mua = clamp( mua, 0.0, 1.0 );
  7999. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  8000. mub = clamp( mub, 0.0, 1.0 );
  8001. return vec2( mua, mub );
  8002. }
  8003. void main() {
  8004. #include <clipping_planes_fragment>
  8005. #ifdef USE_DASH
  8006. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  8007. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  8008. #endif
  8009. float alpha = opacity;
  8010. #ifdef WORLD_UNITS
  8011. // Find the closest points on the view ray and the line segment
  8012. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  8013. vec3 lineDir = worldEnd - worldStart;
  8014. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  8015. vec3 p1 = worldStart + lineDir * params.x;
  8016. vec3 p2 = rayEnd * params.y;
  8017. vec3 delta = p1 - p2;
  8018. float len = length( delta );
  8019. float norm = len / linewidth;
  8020. #ifndef USE_DASH
  8021. #ifdef USE_ALPHA_TO_COVERAGE
  8022. float dnorm = fwidth( norm );
  8023. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  8024. #else
  8025. if ( norm > 0.5 ) {
  8026. discard;
  8027. }
  8028. #endif
  8029. #endif
  8030. #else
  8031. #ifdef USE_ALPHA_TO_COVERAGE
  8032. // artifacts appear on some hardware if a derivative is taken within a conditional
  8033. float a = vUv.x;
  8034. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8035. float len2 = a * a + b * b;
  8036. float dlen = fwidth( len2 );
  8037. if ( abs( vUv.y ) > 1.0 ) {
  8038. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  8039. }
  8040. #else
  8041. if ( abs( vUv.y ) > 1.0 ) {
  8042. float a = vUv.x;
  8043. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  8044. float len2 = a * a + b * b;
  8045. if ( len2 > 1.0 ) discard;
  8046. }
  8047. #endif
  8048. #endif
  8049. vec4 diffuseColor = vec4( diffuse, alpha );
  8050. #include <logdepthbuf_fragment>
  8051. #include <color_fragment>
  8052. gl_FragColor = vec4( diffuseColor.rgb, alpha );
  8053. #include <tonemapping_fragment>
  8054. #include <colorspace_fragment>
  8055. #include <fog_fragment>
  8056. #include <premultiplied_alpha_fragment>
  8057. }
  8058. `};class ZY extends Kh{constructor(e){super({type:"LineMaterial",uniforms:nL.clone(Xs.line.uniforms),vertexShader:Xs.line.vertexShader,fragmentShader:Xs.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const UH=new pl,n_=new Ze;class JY extends nTe{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry",this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new Ha([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new Ha([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,r=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),r.applyMatrix4(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new mD(n,6,1);return this.setAttribute("instanceStart",new Sh(r,3,0)),this.setAttribute("instanceEnd",new Sh(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new mD(n,6,1);return this.setAttribute("instanceColorStart",new Sh(r,3,0)),this.setAttribute("instanceColorEnd",new Sh(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new XAe(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new pl);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),UH.setFromBufferAttribute(n),this.boundingBox.union(UH))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new jc),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let a=0;for(let s=0,o=e.count;s<o;s++)n_.fromBufferAttribute(e,s),a=Math.max(a,r.distanceToSquared(n_)),n_.fromBufferAttribute(n,s),a=Math.max(a,r.distanceToSquared(n_));this.boundingSphere.radius=Math.sqrt(a),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}applyMatrix(e){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(e)}}const BH=new Ze,HH=new Ze,$i=new Or,Vi=new Or,hc=new Or,aE=new Ze,iE=new Yr,qi=new rTe,$H=new Ze,r_=new pl,a_=new jc,mc=new Or;let fc,Ym;function VH(t,e,n){return mc.set(0,0,-e,1).applyMatrix4(t.projectionMatrix),mc.multiplyScalar(1/mc.w),mc.x=Ym/n.width,mc.y=Ym/n.height,mc.applyMatrix4(t.projectionMatrixInverse),mc.multiplyScalar(1/mc.w),Math.abs(Math.max(mc.x,mc.y))}class yTe extends Gl{constructor(e=new JY,n=new ZY({color:16777215*Math.random()})){super(e,n),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,n=e.attributes.instanceStart,r=e.attributes.instanceEnd,a=new Float32Array(2*n.count);for(let o=0,l=0,c=n.count;o<c;o++,l+=2)BH.fromBufferAttribute(n,o),HH.fromBufferAttribute(r,o),a[l]=l===0?0:a[l-1],a[l+1]=a[l]+BH.distanceTo(HH);const s=new mD(a,2,1);return e.setAttribute("instanceDistanceStart",new Sh(s,1,0)),e.setAttribute("instanceDistanceEnd",new Sh(s,1,1)),this}raycast(e,n){const r=this.material.worldUnits,a=e.camera;a!==null||r||console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const s=e.params.Line2!==void 0&&e.params.Line2.threshold||0;fc=e.ray;const o=this.matrixWorld,l=this.geometry,c=this.material;let u,d;Ym=c.linewidth+s,l.boundingSphere===null&&l.computeBoundingSphere(),a_.copy(l.boundingSphere).applyMatrix4(o),r?u=.5*Ym:u=VH(a,Math.max(a.near,a_.distanceToPoint(fc.origin)),c.resolution),a_.radius+=u,fc.intersectsSphere(a_)!==!1&&(l.boundingBox===null&&l.computeBoundingBox(),r_.copy(l.boundingBox).applyMatrix4(o),r?d=.5*Ym:d=VH(a,Math.max(a.near,r_.distanceToPoint(fc.origin)),c.resolution),r_.expandByScalar(d),fc.intersectsBox(r_)!==!1&&(r?(function(h,f){const p=h.matrixWorld,x=h.geometry,v=x.attributes.instanceStart,g=x.attributes.instanceEnd;for(let y=0,_=Math.min(x.instanceCount,v.count);y<_;y++){qi.start.fromBufferAttribute(v,y),qi.end.fromBufferAttribute(g,y),qi.applyMatrix4(p);const N=new Ze,k=new Ze;fc.distanceSqToSegment(qi.start,qi.end,k,N),k.distanceTo(N)<.5*Ym&&f.push({point:k,pointOnLine:N,distance:fc.origin.distanceTo(k),object:h,face:null,faceIndex:y,uv:null,uv1:null})}})(this,n):(function(h,f,p){const x=f.projectionMatrix,v=h.material.resolution,g=h.matrixWorld,y=h.geometry,_=y.attributes.instanceStart,N=y.attributes.instanceEnd,k=Math.min(y.instanceCount,_.count),A=-f.near;fc.at(1,hc),hc.w=1,hc.applyMatrix4(f.matrixWorldInverse),hc.applyMatrix4(x),hc.multiplyScalar(1/hc.w),hc.x*=v.x/2,hc.y*=v.y/2,hc.z=0,aE.copy(hc),iE.multiplyMatrices(f.matrixWorldInverse,g);for(let M=0,C=k;M<C;M++){if($i.fromBufferAttribute(_,M),Vi.fromBufferAttribute(N,M),$i.w=1,Vi.w=1,$i.applyMatrix4(iE),Vi.applyMatrix4(iE),$i.z>A&&Vi.z>A)continue;if($i.z>A){const L=$i.z-Vi.z,B=($i.z-A)/L;$i.lerp(Vi,B)}else if(Vi.z>A){const L=Vi.z-$i.z,B=(Vi.z-A)/L;Vi.lerp($i,B)}$i.applyMatrix4(x),Vi.applyMatrix4(x),$i.multiplyScalar(1/$i.w),Vi.multiplyScalar(1/Vi.w),$i.x*=v.x/2,$i.y*=v.y/2,Vi.x*=v.x/2,Vi.y*=v.y/2,qi.start.copy($i),qi.start.z=0,qi.end.copy(Vi),qi.end.z=0;const j=qi.closestPointToPointParameter(aE,!0);qi.at(j,$H);const P=EY.lerp($i.z,Vi.z,j),E=P>=-1&&P<=1,U=aE.distanceTo($H)<.5*Ym;if(E&&U){qi.start.fromBufferAttribute(_,M),qi.end.fromBufferAttribute(N,M),qi.start.applyMatrix4(g),qi.end.applyMatrix4(g);const L=new Ze,B=new Ze;fc.distanceSqToSegment(qi.start,qi.end,B,L),p.push({point:B,pointOnLine:L,distance:fc.origin.distanceTo(B),object:h,face:null,faceIndex:M,uv:null,uv1:null})}}})(this,a,n)))}}class vTe extends dk{constructor(e,n,r,a,s=4473924,o=8947848){s=new dn(s),o=new dn(o);const l=Math.round(e/n);r=Math.round(r/a)*a/2;const c=[],u=[];let d=0;for(let f=-1*(e=l*n/2);f<=e;f+=n){c.push(f,0,-1*r,f,0,r);const p=f===0?s:o;p.toArray(u,d),d+=3,p.toArray(u,d),d+=3,p.toArray(u,d),d+=3,p.toArray(u,d),d+=3}for(let f=-1*r;f<=r;f+=a){c.push(-1*e,0,f,e,0,f);const p=f===0?s:o;p.toArray(u,d),d+=3,p.toArray(u,d),d+=3,p.toArray(u,d),d+=3,p.toArray(u,d),d+=3}const h=new ys;h.setAttribute("position",new Ha(c,3)),h.setAttribute("color",new Ha(u,3)),super(h,new x0({vertexColors:!0,toneMapped:!1}))}}function wTe(t,e,n,r){const a=(function(o,l,c){o*=.5,l*=.5,c*=.5;const u=new ys,d=[];return d.push(-o,-l,-c,-o,l,-c,-o,l,-c,o,l,-c,o,l,-c,o,-l,-c,o,-l,-c,-o,-l,-c,-o,-l,c,-o,l,c,-o,l,c,o,l,c,o,l,c,o,-l,c,o,-l,c,-o,-l,c,-o,-l,-c,-o,-l,c,-o,l,-c,-o,l,c,o,l,-c,o,l,c,o,-l,-c,o,-l,c),u.setAttribute("position",new Ha(d,3)),u})(t,e,n),s=new dk(a,new QAe({color:new dn(r),dashSize:3,gapSize:1}));return s.computeLineDistances(),s}var Ky=function(){var t=0,e=document.createElement("div");function n(d){return e.appendChild(d.dom),d}function r(d){for(var h=0;h<e.children.length;h++)e.children[h].style.display=h===d?"block":"none";t=d}e.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",e.addEventListener("click",(function(d){d.preventDefault(),r(++t%e.children.length)}),!1);var a=(performance||Date).now(),s=a,o=0,l=n(new Ky.Panel("FPS","#0ff","#002")),c=n(new Ky.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var u=n(new Ky.Panel("MB","#f08","#201"));return r(0),{REVISION:16,dom:e,addPanel:n,showPanel:r,begin:function(){a=(performance||Date).now()},end:function(){o++;var d=(performance||Date).now();if(c.update(d-a,200),d>=s+1e3&&(l.update(1e3*o/(d-s),100),s=d,o=0,u)){var h=performance.memory;u.update(h.usedJSHeapSize/1048576,h.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:e,setMode:r}};Ky.Panel=function(t,e,n){var r=1/0,a=0,s=Math.round,o=s(window.devicePixelRatio||1),l=80*o,c=48*o,u=3*o,d=2*o,h=3*o,f=15*o,p=74*o,x=30*o,v=document.createElement("canvas");v.width=l,v.height=c,v.style.cssText="width:80px;height:48px";var g=v.getContext("2d");return g.font="bold "+9*o+"px Helvetica,Arial,sans-serif",g.textBaseline="top",g.fillStyle=n,g.fillRect(0,0,l,c),g.fillStyle=e,g.fillText(t,u,d),g.fillRect(h,f,p,x),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h,f,p,x),{dom:v,update:function(y,_){r=Math.min(r,y),a=Math.max(a,y),g.fillStyle=n,g.globalAlpha=1,g.fillRect(0,0,l,f),g.fillStyle=e,g.fillText(s(y)+" "+t+" ("+s(r)+"-"+s(a)+")",u,d),g.drawImage(v,h+o,f,p-o,x,h,f,p-o,x),g.fillRect(h+p-o,f,o,x),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(h+p-o,f,o,s((1-y/_)*x))}}};var STe=Ky;class qH{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new I1,this.gui.title("Dev info"),this.setup()}setup(){this.loadOpenFolders(),this.options&&!this.options.renderer||this.setupRedererFolder(),this.options&&!this.options.camera||this.setupCameraFolder(),this.options&&!this.options.parser||this.setupParserFolder(),this.options&&!this.options.buildVolume||this.setupBuildVolumeFolder(),this.options&&!this.options.devHelpers||this.setupDevHelpers()}reset(){this.gui.destroy(),this.gui=new I1,this.gui.title("Dev info"),this.setup()}loadOpenFolders(){this.openFolders=JSON.parse(localStorage.getItem("dev-gui-open")||"{}").open||[]}saveOpenFolders(){this.openFolders=this.gui.foldersRecursive().filter((e=>!e._closed)).map((e=>e._title)),console.log(this.openFolders),localStorage.setItem("dev-gui-open",JSON.stringify({open:this.openFolders}))}setupRedererFolder(){const e=this.gui.addFolder("Render Info");this.openFolders.includes("Render Info")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.renderer.info.render,"triangles").listen(),e.add(this.watchedObject.renderer.info.render,"calls").listen(),e.add(this.watchedObject.renderer.info.render,"lines").listen(),e.add(this.watchedObject.renderer.info.render,"points").listen(),e.add(this.watchedObject.renderer.info.memory,"geometries").listen(),e.add(this.watchedObject.renderer.info.memory,"textures").listen(),e.add(this.watchedObject,"_lastRenderTime").listen()}setupCameraFolder(){const e=this.gui.addFolder("Camera");this.openFolders.includes("Camera")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()}));const n=e.addFolder("Camera position");n.add(this.watchedObject.camera.position,"x").listen(),n.add(this.watchedObject.camera.position,"y").listen(),n.add(this.watchedObject.camera.position,"z").listen();const r=e.addFolder("Camera rotation");r.add(this.watchedObject.camera.rotation,"x").listen(),r.add(this.watchedObject.camera.rotation,"y").listen(),r.add(this.watchedObject.camera.rotation,"z").listen()}setupParserFolder(){const e=this.gui.addFolder("Parser");this.openFolders.includes("Parser")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.parser,"curZ").listen(),e.add(this.watchedObject.parser,"maxZ").listen(),e.add(this.watchedObject.parser,"tolerance").listen(),e.add(this.watchedObject.parser.layers,"length").name("layers.count").listen(),e.add(this.watchedObject.parser.lines,"length").name("lines.count").listen()}setupBuildVolumeFolder(){const e=this.gui.addFolder("Build Volume");this.openFolders.includes("Build Volume")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.buildVolume,"x").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"y").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"z").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()}))}setupDevHelpers(){const e=this.gui.addFolder("Dev Helpers");this.openFolders.includes("Dev Helpers")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject,"_wireframe").listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject,"render").listen(),e.add(this.watchedObject,"clear").listen()}}class _Te extends ys{constructor(e=[new Ze],n=.6,r=.2,a=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:a,closed:!1};const s=new Ze,o=new Ze,l=new _n,c=[],u=[],d=[],h=[];function f(p){const[x,v,g]=(function(y){const _=e[y],N=new Ze,k=new Ze,A=new Ze,M=new Ze;N.copy(_).sub(e[y-1]||_).normalize().add((e[y+1]||_).clone().sub(_).normalize()).normalize();let C=Number.MAX_VALUE;const j=Math.abs(N.x),P=Math.abs(N.y),E=Math.abs(N.z);return j<=C&&(C=j,k.set(1,0,0)),P<=C&&(C=P,k.set(0,1,0)),E<=C&&k.set(0,0,1),M.crossVectors(N,k).normalize(),k.crossVectors(N,M),A.crossVectors(N,k),[_,k,A]})(p);for(let y=0;y<=a;y++){const _=y/a*Math.PI*2,N=Math.sin(_),k=-Math.cos(_);o.x=k*v.x+N*g.x,o.y=k*v.y+N*g.y,o.z=k*v.z+N*g.z,o.normalize(),u.push(o.x,o.y,o.z),s.x=x.x+n*o.x*.5,s.y=x.y+n*o.y*.5,s.z=x.z+r*o.z*.5,c.push(s.x,s.y,s.z)}}(function(){for(let p=0;p<e.length;p++)f(p);f(closed===!1?e.length-1:0),(function(){for(let p=0;p<e.length;p++)for(let x=0;x<=a;x++)l.x=p/e.length,l.y=x/a,d.push(l.x,l.y)})(),(function(){for(let p=1;p<e.length;p++)for(let x=1;x<=a;x++){const v=(a+1)*(p-1)+(x-1),g=(a+1)*p+(x-1),y=(a+1)*p+x,_=(a+1)*(p-1)+x;h.push(v,g,_),h.push(g,y,_)}})()})(),this.setIndex(h),this.setAttribute("position",new Ha(c,3)),this.setAttribute("normal",new Ha(u,3)),this.setAttribute("uv",new Ha(d,2))}}class Xy{static get initial(){const e=new Xy;return Object.assign(e,{x:0,y:0,z:0,r:0,e:0,i:0,j:0,t:0}),e}}const sE={h:0,s:0,l:0};class eb{constructor(e){var n,r,a,s,o,l,c,u,d;if(this.minLayerThreshold=.05,this.renderExtrusion=!0,this.renderTravel=!1,this.renderTubes=!1,this.extrusionWidth=.6,this.singleLayerMode=!1,this.initialCameraPosition=[-100,400,450],this.debug=!1,this.inches=!1,this.nonTravelmoves=[],this.disableGradient=!1,this.state=Xy.initial,this.beyondFirstMove=!1,this.disposables=[],this._extrusionColor=eb.defaultExtrusionColor,this.renderLayerIndex=0,this._geometries={},this._backgroundColor=new dn(14737632),this._travelColor=new dn(10027008),this._toolColors={},this.devMode=!1,this._lastRenderTime=0,this._wireframe=!1,this.minLayerThreshold=(n=e.minLayerThreshold)!==null&&n!==void 0?n:this.minLayerThreshold,this.parser=new z1(this.minLayerThreshold),this.scene=new zAe,this.scene.background=this._backgroundColor,e.backgroundColor!==void 0&&(this.backgroundColor=new dn(e.backgroundColor)),this.targetId=e.targetId,this.endLayer=e.endLayer,this.startLayer=e.startLayer,this.lineWidth=e.lineWidth,this.lineHeight=e.lineHeight,this.buildVolume=e.buildVolume,this.initialCameraPosition=(r=e.initialCameraPosition)!==null&&r!==void 0?r:this.initialCameraPosition,this.debug=(a=e.debug)!==null&&a!==void 0?a:this.debug,this.renderExtrusion=(s=e.renderExtrusion)!==null&&s!==void 0?s:this.renderExtrusion,this.renderTravel=(o=e.renderTravel)!==null&&o!==void 0?o:this.renderTravel,this.nonTravelmoves=(l=e.nonTravelMoves)!==null&&l!==void 0?l:this.nonTravelmoves,this.renderTubes=(c=e.renderTubes)!==null&&c!==void 0?c:this.renderTubes,this.extrusionWidth=(u=e.extrusionWidth)!==null&&u!==void 0?u:this.extrusionWidth,this.devMode=(d=e.devMode)!==null&&d!==void 0?d:this.devMode,this.stats=this.devMode?new STe:void 0,e.extrusionColor!==void 0&&(this.extrusionColor=e.extrusionColor),e.travelColor!==void 0&&(this.travelColor=new dn(e.travelColor)),e.topLayerColor!==void 0&&(this.topLayerColor=new dn(e.topLayerColor)),e.lastSegmentColor!==void 0&&(this.lastSegmentColor=new dn(e.lastSegmentColor)),e.toolColors){this._toolColors={};for(const[p,x]of Object.entries(e.toolColors))this._toolColors[parseInt(p)]=new dn(x)}if(e.disableGradient!==void 0&&(this.disableGradient=e.disableGradient),console.info("Using THREE r"+sk),console.debug("opts",e),this.targetId&&console.warn("`targetId` is deprecated and will removed in the future. Use `canvas` instead."),e.canvas)this.canvas=e.canvas,this.renderer=new hD({canvas:this.canvas,preserveDrawingBuffer:!0});else{if(!this.targetId)throw Error("Set either opts.canvas or opts.targetId");const p=document.getElementById(this.targetId);if(!p)throw new Error("Unable to find element "+this.targetId);this.renderer=new hD({preserveDrawingBuffer:!0}),this.canvas=this.renderer.domElement,p.appendChild(this.canvas)}this.camera=new Ao(25,this.canvas.offsetWidth/this.canvas.offsetHeight,10,5e3),this.camera.position.fromArray(this.initialCameraPosition);const h=this.camera.far,f=.8*h;this.scene.fog=new iL(this._backgroundColor,f,h),this.resize(),this.controls=new xTe(this.camera,this.renderer.domElement),this.initScene(),this.animate(),e.allowDragNDrop&&this._enableDropHandler(),this.initStats()}get extrusionColor(){return this._extrusionColor}set extrusionColor(e){if(Array.isArray(e)){this._extrusionColor=[];for(const[n,r]of e.entries())this._extrusionColor[n]=new dn(r)}else this._extrusionColor=new dn(e)}get currentToolColor(){var e;return this._extrusionColor===void 0?eb.defaultExtrusionColor:this._extrusionColor instanceof dn?this._extrusionColor:(e=this._extrusionColor[this.state.t])!==null&&e!==void 0?e:eb.defaultExtrusionColor}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){this._backgroundColor=new dn(e),this.scene.background=this._backgroundColor}get travelColor(){return this._travelColor}set travelColor(e){this._travelColor=new dn(e)}get topLayerColor(){return this._topLayerColor}set topLayerColor(e){this._topLayerColor=e!==void 0?new dn(e):void 0}get lastSegmentColor(){return this._lastSegmentColor}set lastSegmentColor(e){this._lastSegmentColor=e!==void 0?new dn(e):void 0}get layers(){return[this.parser.preamble].concat(this.parser.layers.concat())}get maxLayerIndex(){var e;return((e=this.endLayer)!==null&&e!==void 0?e:this.layers.length)-1}get minLayerIndex(){var e;return this.singleLayerMode?this.maxLayerIndex:((e=this.startLayer)!==null&&e!==void 0?e:0)-1}animate(){var e;this.animationFrameId=requestAnimationFrame((()=>this.animate())),this.controls.update(),this.renderer.render(this.scene,this.camera),(e=this.stats)===null||e===void 0||e.update()}processGCode(e){this.parser.parseGCode(e),this.render()}initScene(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0]);for(;this.disposables.length>0;){const e=this.disposables.pop();e&&e.dispose()}if(this.debug&&this.buildVolume){const e=new aTe(Math.max(this.buildVolume.x/2,this.buildVolume.y/2)+20);this.scene.add(e)}if(this.buildVolume&&this.drawBuildVolume(),this.renderTubes){console.warn("Volumetric rendering is experimental. It may not work as expected or change in the future.");const e=new tTe(13421772,.3*Math.PI),n=new eTe(16777215,Math.PI,void 0,.001);n.position.set(0,500,500),this.scene.add(e),this.scene.add(n)}}createGroup(e){const n=new My;return n.name=e,n.quaternion.setFromEuler(new g0(-Math.PI/2,0,0)),this.buildVolume?n.position.set(-this.buildVolume.x/2,0,this.buildVolume.y/2):n.position.set(-100,0,100),n}render(){const e=performance.now();this.group=this.createGroup("allLayers"),this.state=Xy.initial,this.initScene();for(let n=0;n<this.layers.length;n++)this.renderLayer(n);this.batchGeometries(),this.scene.add(this.group),this.renderer.render(this.scene,this.camera),this._lastRenderTime=performance.now()-e}renderAnimated(e=1){return nE(this,void 0,void 0,(function*(){return this.initScene(),this.renderLayerIndex=0,this.renderFrameLoop(e>0?e:1)}))}renderFrameLoop(e){return new Promise((n=>{const r=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(r))};r()}))}renderFrame(e){this.group=this.createGroup("layer"+this.renderLayerIndex);for(let n=0;n<e&&this.renderLayerIndex+n<this.layers.length;n++)this.renderLayer(this.renderLayerIndex),this.renderLayerIndex++;this.batchGeometries(),this.scene.add(this.group)}renderLayer(e){var n,r,a,s,o,l,c,u;if(e>this.maxLayerIndex)return;const d=this.layers[e],h={extrusion:[],travel:[],z:this.state.z,height:d.height};for(const f of d.commands)if(f.gcode!="g20"){if(f.gcode.startsWith("t")){this.doRenderExtrusion(h,e),h.extrusion=[];const p=f;this.state.t=p.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(f.gcode)>-1){const p=f,x={x:(n=p.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=p.params.y)!==null&&r!==void 0?r:this.state.y,z:(a=p.params.z)!==null&&a!==void 0?a:this.state.z,r:(s=p.params.r)!==null&&s!==void 0?s:this.state.r,e:(o=p.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=p.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=p.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((u=p.params.e)!==null&&u!==void 0?u:0)>0||this.nonTravelmoves.indexOf(f.gcode)>-1;(x.x!=this.state.x||x.y!=this.state.y||x.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(f.gcode=="g2"||f.gcode=="g3"||f.gcode=="g02"||f.gcode=="g03"?this.addArcSegment(h,this.state,x,v,f.gcode=="g2"||f.gcode=="g02"):this.addLineSegment(h,this.state,x,v))}this.state.x=x.x,this.state.y=x.y,this.state.z=x.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(h,e)}doRenderExtrusion(e,n){var r,a;if(this.renderExtrusion){let s=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;s.getHSL(sE),s=new dn().setHSL(sE.h,sE.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:s,l=(a=this._lastSegmentColor)!==null&&a!==void 0?a:o,c=e.extrusion.splice(-3),u=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...u,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...u,...c],l.getHex()))}else this.renderTubes?this.addTubeLine(e.extrusion,s.getHex(),e.height):this.addLine(e.extrusion,s.getHex())}this.renderTravel&&this.addLine(e.travel,this._travelColor.getHex())}setInches(){this.beyondFirstMove?console.warn("Switching units after movement is already made is discouraged and is not supported."):this.inches=!0}drawBuildVolume(){if(!this.buildVolume)return;this.scene.add(new vTe(this.buildVolume.x,10,this.buildVolume.y,10));const e=wTe(this.buildVolume.x,this.buildVolume.z,this.buildVolume.y,8947848);e.position.setY(this.buildVolume.z/2),this.scene.add(e)}clear(){this.resetState(),this.parser=new z1(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=Xy.initial,(e=this.devGui)===null||e===void 0||e.reset(),this._geometries={}}resize(){const[e,n]=[this.canvas.offsetWidth,this.canvas.offsetHeight];this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,n,!1)}addLineSegment(e,n,r,a){(a?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,a,s){const o=a?e.extrusion:e.travel,l=n.x,c=n.y,u=n.z,d=r.x,h=r.y,f=r.z;let p=r.r,x=r.i,v=r.j;if(p){const $=d-l,G=h-c,z=Math.sqrt(Math.pow($/2,2)+Math.pow(G/2,2));p=Math.max(p,z);const W=Math.pow($,2)+Math.pow(G,2),X=Math.pow(p,2)-W/4;let ae=Math.sqrt(X/W);(s&&p<0||!s&&p>0)&&(ae=-ae),x=$/2+G*ae,v=G/2-$*ae}const g=l==d&&c==h,y=l+x,_=c+v,N=Math.sqrt(x*x+v*v),k=Math.atan2(-v,-x),A=Math.atan2(h-_,d-y);let M;g?M=2*Math.PI:(M=s?k-A:A-k,M<0&&(M+=2*Math.PI));let C=N*M/1.8;this.inches&&(C*=25),C<1&&(C=1);let j=M/C;j*=s?-1:1;const P=[];P.push({x:l,y:c,z:u});const E=(u-f)/C;let U=l,L=c,B=u,D=k;for(let $=0;$<C-1;$++)D+=j,U=y+N*Math.cos(D),L=_+N*Math.sin(D),B+=E,P.push({x:U,y:L,z:B});P.push({x:r.x,y:r.y,z:r.z});for(let $=0;$<P.length-1;$++)o.push(P[$].x,P[$].y,P[$].z,P[$+1].x,P[$+1].y,P[$+1].z)}addLine(e,n){var r;if(typeof this.lineWidth=="number"&&this.lineWidth>0)return void this.addThickLine(e,n);const a=new ys;a.setAttribute("position",new Ha(e,3)),this.disposables.push(a);const s=new x0({color:n});this.disposables.push(s);const o=new dk(a,s);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let a=[];const s=[];for(let o=0;o<e.length;o+=6){const l=e.slice(o,o+9),c=new Ze(l[0],l[1],l[2]),u=new Ze(l[3],l[4],l[5]),d=new Ze(l[6],l[7],l[8]);a.push(c),u.equals(d)||(a.push(u),s.push(a),a=[])}s.forEach((o=>{var l;const c=new _Te(o,this.extrusionWidth,this.lineHeight||r,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const a=new JY;this.disposables.push(a);const s=new ZY({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(s),a.setPositions(e);const o=new yTe(a,s);(r=this.group)===null||r===void 0||r.add(o)}dispose(){this.disposables.forEach((e=>e.dispose())),this.disposables=[],this.controls.dispose(),this.renderer.dispose(),this.cancelAnimation()}cancelAnimation(){this.animationFrameId!==void 0&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0}_enableDropHandler(){console.warn("Drag and drop is deprecated as a library feature. See the demo how to implement your own."),this.canvas.addEventListener("dragover",(e=>{e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),this.canvas.classList.add("dragging")})),this.canvas.addEventListener("dragleave",(e=>{e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging")})),this.canvas.addEventListener("drop",(e=>nE(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const a=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(a.stream()),this.render()}))))}batchGeometries(){if(this._geometries)for(const e in this._geometries){const n=this.createBatchMesh(parseInt(e));for(;this._geometries[e].length>0;){const r=this._geometries[e].pop();n.addGeometry(r)}}}createBatchMesh(e){var n;const r=this._geometries[e],a=new YAe({color:e,wireframe:this._wireframe});this.disposables.push(a);const s=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new WAe(r.length,s,void 0,a);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return nE(this,void 0,void 0,(function*(){const a=e.getReader();let s,o="",l=0;do{console.debug("reading from stream"),s=yield a.read(),l+=(r=(n=s.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const u=(c=s.value,new TextDecoder("utf-8").decode(c)),d=u.lastIndexOf(`
  8059. `),h=u.slice(0,d);this.parser.parseGCode(o+h),o=u.slice(d)}while(!s.done);var c;console.debug("read from stream",l)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new qH(this):typeof this.devMode=="object"&&(this.devGui=new qH(this,this.devMode))}initStats(){var e;this.stats&&(typeof this.devMode=="object"&&(this.statsContainer=this.devMode.statsContainer),((e=this.statsContainer)!==null&&e!==void 0?e:document.body).appendChild(this.stats.dom),this.stats.dom.classList.add("stats"),this.initGui())}}eb.defaultExtrusionColor=new dn("hotpink");function eQ({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:r=""}){const a=w.useRef(null),s=w.useRef(null),o=w.useRef(null),l=w.useRef(!1),[c,u]=w.useState(!0),[d,h]=w.useState(null),[f,p]=w.useState(!1),[x,v]=w.useState(0),[g,y]=w.useState(0),_=w.useMemo(()=>JSON.stringify(n),[n]);w.useEffect(()=>{if(!a.current||l.current)return;l.current=!0;const A=a.current,M=A.parentElement?.getBoundingClientRect();M&&(A.width=M.width,A.height=M.height);const C=n&&n.length>1,j=n?.[0]||"#00ae42",P=new eb({canvas:A,buildVolume:e,backgroundColor:1710618,extrusionColor:C?n:j,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});s.current=P;const E={},U=rd();U&&(E.Authorization=`Bearer ${U}`),fetch(t,{headers:E}).then(async B=>{if(!B.ok)throw B.status===404&&(await B.json().catch(()=>({}))).detail?.includes("sliced")?(p(!0),new Error("not_sliced")):new Error("Failed to load G-code");return B.text()}).then(B=>{const D=new Set,$=/^(\s*)T(\d+)(\s*;.*)?$/gim;let G;for(;(G=$.exec(B))!==null;){const K=parseInt(G[2],10);K<=15&&D.add(K)}const z=new Map,W=Array.from(D).sort((K,te)=>K-te);W.forEach((K,te)=>{z.set(K,te%8)});const X=[];W.forEach((K,te)=>{const Z=n?.[K]||"#00ae42";X[te%8]=Z});const ae=B.split(`
  8060. `).map(K=>{const te=K.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(te){const Z=parseInt(te[2],10);if(Z>15)return`; FILTERED: ${K.trim()}`;const ve=z.get(Z)??0;return`${te[1]}T${ve}${te[3]||""}`}return K}).join(`
  8061. `);X.length>0&&(P.extrusionColor=X),P.processGCode(ae);const H=P.layers?.length||0;y(H),v(H),P.render(),u(!1)}).catch(B=>{B.message!=="not_sliced"&&h(B.message),u(!1)});const L=()=>{if(A.parentElement&&s.current){const B=A.parentElement.getBoundingClientRect();A.width=B.width,A.height=B.height,s.current.resize()}};return window.addEventListener("resize",L),()=>{window.removeEventListener("resize",L),o.current&&cancelAnimationFrame(o.current),s.current&&(s.current.dispose(),s.current=null),l.current=!1}},[t,_]);const N=w.useCallback(A=>{if(!s.current)return;const M=Math.max(1,Math.min(A,g));v(M),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{s.current&&(s.current.endLayer=M,s.current.render())})},[g]),k=A=>{N(parseInt(A.target.value,10))};return i.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[i.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsx("canvas",{ref:a,className:"w-full h-full"}),c&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsxs("div",{className:"text-center",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),f&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsxs("div",{className:"text-center max-w-sm px-4",children:[i.jsx(ume,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),i.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),i.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing in Bambu Studio or Orca Slicer."})]})}),d&&!f&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:i.jsx("div",{className:"text-center text-red-400",children:i.jsx("p",{className:"text-sm",children:d})})})]}),!c&&!d&&!f&&g>0&&i.jsx("div",{className:"mt-4 px-2",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("button",{onClick:()=>N(x-1),disabled:x<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsx("input",{type:"range",min:1,max:g,value:x,onChange:k,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),i.jsx("button",{onClick:()=>N(x+1),disabled:x>=g,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[x," / ",g]})]})})]})}function ul(t){if(t===0)return"0 B";const e=["B","KB","MB","GB","TB"],n=1024,r=Math.floor(Math.log(t)/Math.log(n)),a=t/Math.pow(n,r);return r===0?`${a} ${e[r]}`:`${a.toFixed(1)} ${e[r]}`}function NTe({printerId:t,filePath:e,filename:n,onClose:r}){const[a,s]=w.useState(null),[o,l]=w.useState([]),[c,u]=w.useState(!1),[d,h]=w.useState(null),f=n.toLowerCase().split(".").pop()||"",p=f==="3mf"||f==="stl",x=f==="gcode"||f==="3mf";w.useEffect(()=>{s(p?"3d":x?"gcode":null)},[p,x]),w.useEffect(()=>{l([]),h(null),p&&(u(!0),ne.getPrinterFilePlates(t,e).then(y=>l(y.plates||[])).catch(()=>l([])).finally(()=>u(!1)))},[e,p,t]);const v=o.length>1,g=d==null?null:o.find(y=>y.index===d)??null;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-6",onClick:r,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col",onClick:y=>y.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:n}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:r,children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>p&&s("3d"),disabled:!p,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${a==="3d"?"text-bambu-green border-b-2 border-bambu-green":p?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(Ja,{className:"w-4 h-4"}),"3D Model",!p&&i.jsx("span",{className:"text-xs",children:"(not available)"})]}),i.jsxs("button",{onClick:()=>x&&s("gcode"),disabled:!x,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${a==="gcode"?"text-bambu-green border-b-2 border-bambu-green":x?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(Ms,{className:"w-4 h-4"}),"G-code Preview",!x&&i.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:a==="3d"&&p?i.jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[v&&i.jsxs("div",{className:"rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(Ja,{className:"w-4 h-4"}),"Plates",c&&i.jsx(it,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[i.jsxs("button",{type:"button",onClick:()=>h(null),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${d==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(Ja,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:"All Plates"}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[o.length," plate",o.length!==1?"s":""]})]}),d==null&&i.jsx(oo,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]}),o.map(y=>i.jsxs("button",{type:"button",onClick:()=>h(y.index),className:`flex items-center gap-2 rounded-lg border p-2 text-left transition-colors ${d===y.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[y.has_thumbnail?i.jsx("img",{src:ne.getPrinterFilePlateThumbnail(t,y.index,e),alt:`Plate ${y.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(Ja,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:y.name||`Plate ${y.index}`}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:y.objects.length>0?y.objects.slice(0,2).join(", ")+(y.objects.length>2?"…":""):`${y.filaments.length} filament${y.filaments.length!==1?"s":""}`})]}),d===y.index&&i.jsx(oo,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},y.index))]}),g&&i.jsxs("div",{className:"mt-3 text-xs text-bambu-gray flex flex-wrap gap-x-4 gap-y-1",children:[i.jsxs("span",{children:["Plate ",g.index]}),g.print_time_seconds!=null&&i.jsxs("span",{children:["ETA ",Math.round(g.print_time_seconds/60)," min"]}),g.filament_used_grams!=null&&i.jsxs("span",{children:[g.filament_used_grams.toFixed(1)," g"]}),g.filaments.length>0&&i.jsxs("span",{children:[g.filaments.length," filament",g.filaments.length!==1?"s":""]})]})]}),i.jsx("div",{className:"flex-1",children:i.jsx(xY,{url:ne.getPrinterFileDownloadUrl(t,e),fileType:f,selectedPlateId:d,className:"w-full h-full"})})]}):a==="gcode"&&x?i.jsx(eQ,{gcodeUrl:ne.getPrinterFileGcodeUrl(t,e),className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function GH(t){if(t===0)return"0 GB";const e=t/(1024*1024*1024);return e>=1?`${e.toFixed(1)} GB`:`${(t/(1024*1024)).toFixed(0)} MB`}function CTe(t,e){if(e)return pX;switch(t.toLowerCase().split(".").pop()||""){case"3mf":return hf;case"gcode":return Ms;case"mp4":case"avi":return Mh;case"png":case"jpg":case"jpeg":return Ju;default:return VC}}const kTe=[{value:"name-asc",label:"Name (A-Z)"},{value:"name-desc",label:"Name (Z-A)"},{value:"size-asc",label:"Size (smallest)"},{value:"size-desc",label:"Size (largest)"},{value:"date-asc",label:"Date (oldest)"},{value:"date-desc",label:"Date (newest)"}];function ATe({printerId:t,printerName:e,onClose:n}){const{t:r}=Ot(),{showToast:a}=an(),s=en(),[o,l]=w.useState("/"),[c,u]=w.useState(new Set),[d,h]=w.useState(""),[f,p]=w.useState([]),[x,v]=w.useState("name-asc"),[g,y]=w.useState(null),[_,N]=w.useState(null);w.useEffect(()=>{const z=W=>{W.key==="Escape"&&n()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[n]);const{data:k,isLoading:A,refetch:M}=Je({queryKey:["printerFiles",t,o],queryFn:()=>ne.getPrinterFiles(t,o)}),{data:C}=Je({queryKey:["printerStorage",t],queryFn:()=>ne.getPrinterStorage(t),staleTime:3e4}),j=st({mutationFn:async z=>{for(const W of z)await ne.deletePrinterFile(t,W)},onSuccess:()=>{a(r("printerFiles.toast.filesDeleted",{count:f.length})),s.invalidateQueries({queryKey:["printerFiles",t]}),u(new Set),p([])},onError:z=>{a(r("printerFiles.toast.deleteFailed",{error:z.message}),"error")}}),P=z=>{l(z),u(new Set)},E=()=>{if(o==="/")return;const z=o.split("/").filter(Boolean);z.pop(),l(z.length?"/"+z.join("/"):"/"),u(new Set)},U=(z,W)=>{W.stopPropagation(),u(X=>{const ae=new Set(X);return ae.has(z)?ae.delete(z):ae.add(z),ae})},L=()=>{if(!k?.files)return;const z=k.files.filter(W=>!W.is_directory&&(!d||W.name.toLowerCase().includes(d.toLowerCase()))).map(W=>W.path);u(new Set(z))},B=()=>{u(new Set)},D=async()=>{if(c.size===0)return;const z=Array.from(c);if(z.length===1){ne.downloadPrinterFile(t,z[0]).catch(W=>{console.error("Printer file download failed:",W)}),u(new Set);return}y({current:0,total:z.length});try{const W=await ne.downloadPrinterFilesAsZip(t,z),X=URL.createObjectURL(W),ae=document.createElement("a");ae.href=X,ae.download=`${e.replace(/[^a-zA-Z0-9]/g,"_")}-files.zip`,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(X),a(`Downloaded ${z.length} files as ZIP`),u(new Set)}catch(W){a(`Download failed: ${W instanceof Error?W.message:"Unknown error"}`,"error")}finally{y(null)}},$=()=>{c.size!==0&&p(Array.from(c))},G=[{path:"/",label:"Root"},{path:"/cache",label:"Cache"},{path:"/model",label:"Models"},{path:"/timelapse",label:"Timelapse"}];return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:n,children:[i.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden",onClick:z=>z.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Vb,{className:"w-5 h-5 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("printerFiles.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:e})]})]}),i.jsxs("div",{className:"flex items-center gap-4",children:[C&&(C.used_bytes!=null||C.free_bytes!=null)&&i.jsxs("div",{className:"text-sm text-bambu-gray flex items-center gap-2",children:[C.used_bytes!=null&&i.jsxs("span",{children:[r("printerFiles.storageUsed")," ",GH(C.used_bytes)]}),C.used_bytes!=null&&C.free_bytes!=null&&i.jsx("span",{className:"text-bambu-dark-tertiary",children:"|"}),C.free_bytes!=null&&i.jsxs("span",{children:[r("printerFiles.storageFree")," ",GH(C.free_bytes)]})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",title:"Close file manager","aria-label":"Close file manager",children:i.jsx(Lt,{className:"w-5 h-5"})})]})]}),i.jsxs("div",{className:"flex items-center gap-2 p-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[G.map(z=>i.jsx("button",{onClick:()=>{P(z.path),h("")},className:`px-3 py-1 text-sm rounded-full transition-colors ${o===z.path?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:z.label},z.path)),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:r("printerFiles.filterPlaceholder"),value:d,onChange:z=>h(z.target.value),className:"w-40 pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"relative flex items-center gap-1",children:[i.jsx(NF,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("select",{value:x,onChange:z=>v(z.target.value),className:"appearance-none bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm py-1.5 pl-2 pr-6 focus:border-bambu-green focus:outline-none cursor-pointer",title:"Sort files","aria-label":"Sort files",children:kTe.map(z=>i.jsx("option",{value:z.value,children:z.label},z.value))})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>M(),disabled:A,children:i.jsx(Ar,{className:`w-4 h-4 ${A?"animate-spin":""}`})})]}),i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark text-sm flex-shrink-0",children:[i.jsx("button",{onClick:E,disabled:o==="/",className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-50 disabled:cursor-not-allowed",title:"Go to parent folder","aria-label":"Go to parent folder",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsx("span",{className:"text-bambu-gray font-mono",children:o})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:A?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):k?.files?.length?i.jsx("div",{className:"space-y-1",children:[...k.files].filter(z=>!d||z.name.toLowerCase().includes(d.toLowerCase())).sort((z,W)=>{if(z.is_directory&&!W.is_directory)return-1;if(!z.is_directory&&W.is_directory)return 1;switch(x){case"name-asc":return z.name.localeCompare(W.name);case"name-desc":return W.name.localeCompare(z.name);case"size-asc":return z.size-W.size;case"size-desc":return W.size-z.size;case"date-asc":{const X=z.mtime?new Date(z.mtime).getTime():0,ae=W.mtime?new Date(W.mtime).getTime():0;return X-ae}case"date-desc":{const X=z.mtime?new Date(z.mtime).getTime():0;return(W.mtime?new Date(W.mtime).getTime():0)-X}default:return z.name.localeCompare(W.name)}}).map(z=>{const W=CTe(z.name,z.is_directory),X=c.has(z.path);return i.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${X?"bg-bambu-green/20 border border-bambu-green/50":"hover:bg-bambu-dark-tertiary"}`,onClick:()=>{z.is_directory&&P(z.path)},children:[z.is_directory?null:i.jsx("button",{onClick:ae=>U(z.path,ae),className:"flex-shrink-0 text-bambu-gray hover:text-white",children:X?i.jsx(oo,{className:"w-5 h-5 text-bambu-green"}):i.jsx(vl,{className:"w-5 h-5"})}),i.jsx(W,{className:`w-5 h-5 flex-shrink-0 ${z.is_directory?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("span",{className:"flex-1 text-white truncate",children:z.name}),!z.is_directory&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:ul(z.size)}),(z.name.toLowerCase().endsWith(".3mf")||z.name.toLowerCase().endsWith(".gcode")||z.name.toLowerCase().endsWith(".stl"))&&i.jsx("button",{onClick:ae=>{ae.stopPropagation(),N({path:z.path,name:z.name})},className:"p-1 rounded hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green",title:"3D View",children:i.jsx(Ja,{className:"w-4 h-4"})})]}),z.is_directory&&i.jsx(Xl,{className:"w-4 h-4 text-bambu-gray rotate-180"})]},z.path)})}):i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"No files in this directory"})}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary bg-bambu-dark/50 flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"text-sm text-bambu-gray",children:c.size>0?`${c.size} selected`:d?`${k?.files?.filter(z=>z.name.toLowerCase().includes(d.toLowerCase())).length||0} of ${k?.files?.length||0} items`:`${k?.files?.length||0} items`}),k?.files?.some(z=>!z.is_directory)&&i.jsx("div",{className:"flex items-center gap-2",children:c.size>0?i.jsxs("button",{onClick:B,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[i.jsx(wpe,{className:"w-4 h-4"}),"Deselect All"]}):i.jsxs("button",{onClick:L,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",children:[i.jsx(oo,{className:"w-4 h-4"}),"Select All"]})})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",disabled:c.size===0||g!==null,onClick:D,children:g?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),g.current,"/",g.total]}):i.jsxs(i.Fragment,{children:[i.jsx(da,{className:"w-4 h-4"}),"Download",c.size>1?` (${c.size})`:""]})}),i.jsxs(Ce,{variant:"secondary",disabled:c.size===0||j.isPending,onClick:$,className:"text-red-400 hover:text-red-300",children:[j.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),r("printerFiles.deleteButton"),c.size>1?` (${c.size})`:""]})]})]})]}),f.length>0&&i.jsx(gn,{title:f.length>1?r("printerFiles.deleteFiles",{count:f.length}):r("fileManager.deleteFile"),message:f.length>1?r("printerFiles.deleteFilesConfirm",{count:f.length}):r("printerFiles.deleteFileConfirm",{name:f[0].split("/").pop()}),confirmText:r("common.delete"),variant:"danger",onConfirm:()=>{j.mutate(f)},onCancel:()=>p([])}),_&&i.jsx(NTe,{printerId:t,filePath:_.path,filename:_.name,onClose:()=>N(null)})]})}function lL({on:t,className:e="w-5 h-5"}){const n=t?"#facc15":"none",r=t?"#78350f":"currentColor",a=t?1:0;return i.jsxs("svg",{viewBox:"0 0 32 32",fill:"none",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[i.jsxs("g",{stroke:r,opacity:a,children:[i.jsx("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),i.jsx("line",{x1:"6.1",y1:"6.1",x2:"8.9",y2:"8.9"}),i.jsx("line",{x1:"25.9",y1:"6.1",x2:"23.1",y2:"8.9"}),i.jsx("line",{x1:"2",y1:"16",x2:"6",y2:"16"}),i.jsx("line",{x1:"30",y1:"16",x2:"26",y2:"16"})]}),i.jsx("path",{d:"M12 24v-2.3c0-.9-.4-1.7-1-2.3C9.2 17.6 8 15.4 8 13c0-4.4 3.6-8 8-8s8 3.6 8 8c0 2.4-1.2 4.6-3 6.4-.6.6-1 1.4-1 2.3V24",fill:n,stroke:r}),i.jsx("path",{d:"M12 24h8",stroke:r}),i.jsx("path",{d:"M12 27h8",stroke:r}),i.jsx("path",{d:"M13 30h6",stroke:r})]})}const hk=({className:t})=>i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[i.jsx("rect",{x:"2",y:"15",width:"5",height:"5",rx:"0.5"}),i.jsx("rect",{x:"9.5",y:"15",width:"5",height:"5",rx:"0.5",fill:"currentColor",opacity:"0.3"}),i.jsx("rect",{x:"17",y:"15",width:"5",height:"5",rx:"0.5"}),i.jsx("path",{d:"M4 12 C4 6, 14 6, 14 12"}),i.jsx("polyline",{points:"12,10 14,12 12,14"})]});function cL({printerId:t,isOpen:e,onClose:n}){const{t:r}=Ot(),{showToast:a}=an(),{hasPermission:s}=Ir(),[o,l]=w.useState(null),[c,u]=w.useState(!1),{data:d}=Je({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4,enabled:e}),{data:h,refetch:f}=Je({queryKey:["printableObjects",t],queryFn:()=>ne.getPrintableObjects(t),enabled:e,refetchInterval:e?5e3:!1}),p=st({mutationFn:x=>ne.skipObjects(t,x),onSuccess:x=>{a(x.message||r("printers.skipObjects.objectsSkipped")),l(null),f()},onError:x=>a(x.message||r("printers.toast.failedToSkipObjects"),"error")});return e?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:n,onKeyDown:x=>{x.key==="Escape"&&(c?u(!1):n())},tabIndex:-1,ref:x=>x?.focus(),children:[i.jsx("div",{className:"absolute inset-0 bg-black/50 z-0"}),i.jsxs("div",{className:"relative z-10 bg-white dark:bg-bambu-dark border border-gray-200 dark:border-bambu-dark-tertiary rounded-xl shadow-2xl w-[560px] max-h-[85vh] flex flex-col overflow-hidden",onClick:x=>x.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hk,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-sm font-medium text-gray-900 dark:text-white",children:r("printers.skipObjects.title")})]}),i.jsx("button",{onClick:n,className:"p-1 text-gray-500 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),h?h.objects.length===0?i.jsxs("div",{className:"text-center py-8 px-4 text-bambu-gray",children:[i.jsx("p",{className:"text-sm",children:r("printers.noObjectsFound")}),i.jsx("p",{className:"text-xs mt-1 opacity-70",children:r("printers.objectsLoadedOnPrintStart")})]}):i.jsxs("div",{className:"flex flex-col overflow-hidden",children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 bg-blue-50 dark:bg-blue-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[i.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center",children:i.jsx(kfe,{className:"w-4 h-4 text-blue-500 dark:text-blue-400"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300",children:r("printers.skipObjects.matchIdsInfo")}),i.jsx("p",{className:"text-[10px] text-blue-500/70 dark:text-blue-300/60",children:r("printers.skipObjects.printerShowsIds")})]}),i.jsxs("div",{className:"flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray",children:[h.skipped_count,"/",h.total," ",r("printers.skipObjects.skipped")]})]}),(d?.layer_num??0)<=1&&i.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-50 dark:bg-amber-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary",children:[i.jsx(Ba,{className:"w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0"}),i.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:r("printers.skipObjects.waitForLayer",{layer:d?.layer_num??0})})]}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"w-52 flex-shrink-0 p-4 border-r border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark-secondary overflow-y-auto",children:i.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>u(!0),children:[d?.cover_url?i.jsx("img",{src:`${d.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full aspect-square object-contain rounded-lg bg-gray-900 dark:bg-gray-900 border border-gray-300 dark:border-gray-600"}):i.jsx("div",{className:"w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center",children:i.jsx(Ja,{className:"w-8 h-8 text-gray-300 dark:text-bambu-gray/30"})}),i.jsx("div",{className:"absolute top-2 right-2 p-1 bg-black/60 rounded opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(KC,{className:"w-3.5 h-3.5 text-white"})}),h.objects.length>0&&i.jsx("div",{className:"absolute inset-0 pointer-events-none",children:h.objects.map((x,v)=>{let g,y;if(x.x!=null&&x.y!=null&&h.bbox_all){const[_,N,k,A]=h.bbox_all,M=k-_,C=A-N,j=8,P=100-j*2;g=j+(x.x-_)/M*P,y=j+(A-x.y)/C*P,g=Math.max(5,Math.min(95,g)),y=Math.max(5,Math.min(95,y))}else if(x.x!=null&&x.y!=null)g=x.x/256*100,y=100-x.y/256*100,g=Math.max(5,Math.min(95,g)),y=Math.max(5,Math.min(95,y));else{const _=Math.ceil(Math.sqrt(h.objects.length)),N=Math.floor(v/_),k=v%_,A=Math.ceil(h.objects.length/_);g=15+k*(70/_)+35/_,y=15+N*(70/A)+35/A}return i.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${x.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${g}%`,top:`${y}%`,transform:"translate(-50%, -50%)"},title:x.name,children:x.id},x.id)})}),i.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:h.objects.filter(x=>!x.skipped).length})})]})}),i.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:h.objects.map(x=>i.jsxs("div",{className:`
  8062. flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary/50 last:border-0
  8063. ${x.skipped?"bg-red-50 dark:bg-red-500/10":"hover:bg-gray-50 dark:hover:bg-bambu-dark/50"}
  8064. `,children:[i.jsxs("div",{className:`
  8065. w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center
  8066. ${x.skipped?"bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/40":"bg-green-100 dark:bg-bambu-green/20 border border-green-300 dark:border-bambu-green/40"}
  8067. `,children:[i.jsx("span",{className:`text-lg font-mono font-bold ${x.skipped?"text-red-500 dark:text-red-400":"text-green-600 dark:text-bambu-green"}`,children:x.id}),i.jsx("span",{className:`text-[8px] uppercase tracking-wider ${x.skipped?"text-red-400/60":"text-green-500/60 dark:text-bambu-green/60"}`,children:"ID"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:`block text-sm truncate ${x.skipped?"text-red-500 dark:text-red-400 line-through":"text-gray-900 dark:text-white"}`,children:x.name}),x.skipped&&i.jsx("span",{className:"text-[10px] text-red-400/60",children:r("printers.willBeSkipped")})]}),x.skipped?i.jsx("span",{className:"px-4 py-2 text-xs text-red-500 dark:text-red-400/70 bg-red-100 dark:bg-red-500/10 rounded-lg",children:r("printers.skipObjects.skipped")}):i.jsx("button",{onClick:()=>l({id:x.id,name:x.name}),disabled:p.isPending||(d?.layer_num??0)<=1||!s("printers:control"),className:`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${(d?.layer_num??0)<=1||!s("printers:control")?"bg-gray-100 dark:bg-bambu-dark text-gray-400 dark:text-bambu-gray/50 cursor-not-allowed":"bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 border border-red-300 dark:border-red-500/30"}`,title:s("printers:control")?(d?.layer_num??0)<=1?r("printers.skipObjects.waitForLayer",{layer:d?.layer_num??0}):r("printers.skipObjects.skip"):r("printers.permission.noControl"),children:r("printers.skipObjects.skip")})]},x.id))})]})]}):i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-5 h-5 animate-spin text-bambu-gray"})})]})]}),o&&i.jsx(gn,{variant:"warning",title:r("printers.skipObjects.confirmTitle"),message:r("printers.skipObjects.confirmMessage",{name:o.name}),confirmText:r("printers.skipObjects.skip"),isLoading:p.isPending,onConfirm:()=>p.mutate([o.id]),onCancel:()=>l(null)}),c&&h&&i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>u(!1),children:[i.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 p-2 text-white/70 hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-6 h-6"})}),i.jsxs("div",{className:"relative max-w-[600px] max-h-[80vh] aspect-square",onClick:x=>x.stopPropagation(),children:[d?.cover_url?i.jsx("img",{src:`${d.cover_url}?view=top`,alt:r("printers.printPreview"),className:"w-full h-full object-contain rounded-lg bg-gray-900"}):i.jsx("div",{className:"w-full h-full rounded-lg bg-gray-800 flex items-center justify-center",children:i.jsx(Ja,{className:"w-16 h-16 text-gray-500"})}),h.objects.length>0&&i.jsx("div",{className:"absolute inset-0 pointer-events-none",children:h.objects.map((x,v)=>{let g,y;if(x.x!=null&&x.y!=null&&h.bbox_all){const[_,N,k,A]=h.bbox_all,M=k-_,C=A-N,j=8,P=100-j*2;g=j+(x.x-_)/M*P,y=j+(A-x.y)/C*P,g=Math.max(5,Math.min(95,g)),y=Math.max(5,Math.min(95,y))}else if(x.x!=null&&x.y!=null)g=x.x/256*100,y=100-x.y/256*100,g=Math.max(5,Math.min(95,g)),y=Math.max(5,Math.min(95,y));else{const _=Math.ceil(Math.sqrt(h.objects.length)),N=Math.floor(v/_),k=v%_,A=Math.ceil(h.objects.length/_);g=15+k*(70/_)+35/_,y=15+N*(70/A)+35/A}return i.jsx("div",{className:`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${x.skipped?"bg-red-500 text-white line-through":"bg-bambu-green text-black"}`,style:{left:`${g}%`,top:`${y}%`,transform:"translate(-50%, -50%)"},title:x.name,children:x.id},x.id)})}),i.jsx("div",{className:"absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm",children:r("printers.skipObjects.activeCount",{count:h.objects.filter(x=>!x.skipped).length})})]})]})]}):null}const TTe="embeddedCameraState_",WH=5,MTe=2e3,PTe=3e4,ETe=5e3,oE={x:window.innerWidth-420,y:20,width:400,height:300};function jTe({printerId:t,printerName:e,viewerIndex:n=0,onClose:r}){const{t:a}=Ot(),s=en(),{showToast:o}=an(),{hasPermission:l}=Ir(),c=`${TTe}${t}`,u=()=>{try{const Re=localStorage.getItem(c);if(Re){const $e=JSON.parse(Re);return{x:Math.min(Math.max(0,$e.x),window.innerWidth-100),y:Math.min(Math.max(0,$e.y),window.innerHeight-100),width:Math.max(200,Math.min($e.width,window.innerWidth-20)),height:Math.max(150,Math.min($e.height,window.innerHeight-20))}}}catch{}const Ae=n*30;return{...oE,x:Math.max(0,oE.x-Ae),y:Math.max(0,oE.y+Ae)}},[d,h]=w.useState(u),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState({x:0,y:0}),[_,N]=w.useState(!1),[k,A]=w.useState(!1),[M,C]=w.useState(1),[j,P]=w.useState({x:0,y:0}),[E,U]=w.useState(!1),[L,B]=w.useState({x:0,y:0}),[D,$]=w.useState(null),[G,z]=w.useState(null),[W,X]=w.useState(!1),[ae,H]=w.useState(!0),[K,te]=w.useState(Date.now()),[Z,ve]=w.useState(0),[ce,ee]=w.useState(!1),[je,he]=w.useState(0),oe=w.useRef(null),_e=w.useRef(null),ie=w.useRef(null),ze=w.useRef(null),V=w.useRef(null),[Y,me]=w.useState(!1),{data:Q}=Je({queryKey:["printer",t],queryFn:()=>ne.getPrinter(t),enabled:t>0}),{data:se}=Je({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4,enabled:t>0}),de=st({mutationFn:Ae=>ne.setChamberLight(t,Ae),onMutate:async Ae=>{await s.cancelQueries({queryKey:["printerStatus",t]});const Re=s.getQueryData(["printerStatus",t]);return s.setQueryData(["printerStatus",t],$e=>({...$e,chamber_light:Ae})),{previousStatus:Re}},onSuccess:(Ae,Re)=>{o(`Chamber light ${Re?"on":"off"}`)},onError:(Ae,Re,$e)=>{$e?.previousStatus&&s.setQueryData(["printerStatus",t],$e.previousStatus),o(Ae.message||a("printers.toast.failedToControlChamberLight"),"error")}}),Le=(se?.state==="RUNNING"||se?.state==="PAUSE")&&(se?.printable_objects_count??0)>=2;w.useEffect(()=>{const Ae=setTimeout(()=>{localStorage.setItem(c,JSON.stringify(d))},500);return()=>clearTimeout(Ae)},[d,c]);const Ne=w.useRef(!1);w.useEffect(()=>{Ne.current=!1;const Ae=`/api/v1/printers/${t}/camera/stop`,Re=()=>{if(t>0&&!Ne.current){Ne.current=!0;const ht={},At=rd();At&&(ht.Authorization=`Bearer ${At}`),fetch(Ae,{method:"POST",keepalive:!0,headers:ht}).catch(()=>{})}},$e=_e.current;return()=>{$e&&($e.src=""),Re(),ie.current&&clearTimeout(ie.current),ze.current&&clearInterval(ze.current),V.current&&clearInterval(V.current)}},[t]),w.useEffect(()=>{if(ae){const Ae=setTimeout(()=>H(!1),3e3);return()=>clearTimeout(Ae)}},[ae,K]);const be=w.useCallback(()=>{if(Z>=WH){ee(!1),X(!0);return}const Ae=Math.min(MTe*Math.pow(2,Z),PTe);ee(!0),he(Math.ceil(Ae/1e3)),ze.current=setInterval(()=>{he(Re=>Re<=1?(ze.current&&clearInterval(ze.current),0):Re-1)},1e3),ie.current=setTimeout(()=>{ve(Re=>Re+1),ee(!1),H(!0),X(!1),_e.current&&(_e.current.src=""),te(Date.now())},Ae)},[Z]);w.useEffect(()=>{if(ae||ce||_){V.current&&(clearInterval(V.current),V.current=null);return}return V.current=setInterval(async()=>{try{const Ae=await ne.getCameraStatus(t);(Ae.stalled||!Ae.active&&!W)&&(V.current&&(clearInterval(V.current),V.current=null),H(!1),be())}catch{}},ETe),()=>{V.current&&(clearInterval(V.current),V.current=null)}},[ae,W,ce,_,t,be]),w.useEffect(()=>{const Ae=()=>{const Re=!!document.fullscreenElement;A(Re),Re||(C(1),P({x:0,y:0}))};return document.addEventListener("fullscreenchange",Ae),()=>document.removeEventListener("fullscreenchange",Ae)},[]);const O=()=>{oe.current&&(document.fullscreenElement?document.exitFullscreen():oe.current.requestFullscreen())},R=()=>{C(Ae=>Math.min(Ae+.5,4))},q=()=>{C(Ae=>{const Re=Math.max(Ae-.5,1);return Re===1&&P({x:0,y:0}),Re})},J=Ae=>{Ae.preventDefault(),Ae.deltaY<0?R():q()},fe=Ae=>{M>1&&(Ae.preventDefault(),U(!0),B({x:Ae.clientX-j.x,y:Ae.clientY-j.y}))},le=w.useCallback(()=>{if(!oe.current||!_e.current)return{x:200,y:150};const Ae=oe.current.getBoundingClientRect(),Re=Ae.width*(M-1)/2,$e=Ae.height*(M-1)/2;return{x:Math.max(50,Re),y:Math.max(50,$e)}},[M]),Be=Ae=>{if(E&&M>1){const Re=Ae.clientX-L.x,$e=Ae.clientY-L.y,ht=le();P({x:Math.max(-ht.x,Math.min(ht.x,Re)),y:Math.max(-ht.y,Math.min(ht.y,$e))})}},Ie=()=>{U(!1)},Ke=Ae=>{if(Ae.length<2)return 0;const Re=Ae[0].clientX-Ae[1].clientX,$e=Ae[0].clientY-Ae[1].clientY;return Math.sqrt(Re*Re+$e*$e)},Oe=Ae=>Ae.length<2?{x:Ae[0].clientX,y:Ae[0].clientY}:{x:(Ae[0].clientX+Ae[1].clientX)/2,y:(Ae[0].clientY+Ae[1].clientY)/2},pe=Ae=>{Ae.touches.length===2?(Ae.preventDefault(),$(Ke(Ae.touches)),z(Oe(Ae.touches))):Ae.touches.length===1&&M>1&&(Ae.preventDefault(),U(!0),B({x:Ae.touches[0].clientX-j.x,y:Ae.touches[0].clientY-j.y}))},xe=Ae=>{if(Ae.touches.length===2&&D!==null){Ae.preventDefault();const Re=Ke(Ae.touches),$e=Re/D;C(At=>{const Dt=Math.max(1,Math.min(4,At*$e));return Dt===1&&P({x:0,y:0}),Dt}),$(Re);const ht=Oe(Ae.touches);if(G){const At=le();P(Dt=>({x:Math.max(-At.x,Math.min(At.x,Dt.x+(ht.x-G.x))),y:Math.max(-At.y,Math.min(At.y,Dt.y+(ht.y-G.y)))}))}z(ht)}else if(Ae.touches.length===1&&E&&M>1){Ae.preventDefault();const Re=Ae.touches[0].clientX-L.x,$e=Ae.touches[0].clientY-L.y,ht=le();P({x:Math.max(-ht.x,Math.min(ht.x,Re)),y:Math.max(-ht.y,Math.min(ht.y,$e))})}},ke=Ae=>{Ae.touches.length<2&&($(null),z(null)),Ae.touches.length===0&&U(!1)},ge=()=>{C(1),P({x:0,y:0})},we=()=>{H(!1),Z<WH?be():X(!0)},qe=()=>{H(!1),X(!1),ve(0),ee(!1),ie.current&&clearTimeout(ie.current),ze.current&&clearInterval(ze.current)},Ee=()=>{H(!0),X(!1),ve(0),ee(!1),ie.current&&clearTimeout(ie.current),ze.current&&clearInterval(ze.current);const Ae={},Re=rd();Re&&(Ae.Authorization=`Bearer ${Re}`),fetch(`/api/v1/printers/${t}/camera/stop`,{method:"POST",headers:Ae}).catch(()=>{}),_e.current&&(_e.current.src=""),setTimeout(()=>te(Date.now()),100)},tt=Ae=>{Ae.target.closest(".no-drag")||(p(!0),y({x:Ae.clientX-d.x,y:Ae.clientY-d.y}))},De=Ae=>{Ae.stopPropagation(),v(!0)};w.useEffect(()=>{const Ae=$e=>{if(f)h(ht=>({...ht,x:Math.max(0,Math.min($e.clientX-g.x,window.innerWidth-ht.width)),y:Math.max(0,Math.min($e.clientY-g.y,window.innerHeight-ht.height))}));else if(x&&oe.current){const ht=oe.current.getBoundingClientRect();h(At=>({...At,width:Math.max(200,Math.min($e.clientX-ht.left,window.innerWidth-At.x-10)),height:Math.max(150,Math.min($e.clientY-ht.top,window.innerHeight-At.y-10))}))}},Re=()=>{p(!1),v(!1)};if(f||x)return document.addEventListener("mousemove",Ae),document.addEventListener("mouseup",Re),()=>{document.removeEventListener("mousemove",Ae),document.removeEventListener("mouseup",Re)}},[f,x,g]);const We=`/api/v1/printers/${t}/camera/stream?fps=15&t=${K}`;return i.jsxs("div",{ref:oe,className:`${k?"fixed inset-0 z-[100]":"fixed z-50 rounded-lg shadow-2xl border border-bambu-dark-tertiary"} bg-bambu-dark-secondary overflow-hidden`,style:k?void 0:{left:d.x,top:d.y,width:_?200:d.width,height:_?40:d.height,cursor:f?"grabbing":"default"},children:[i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-bambu-dark border-b border-bambu-dark-tertiary cursor-grab active:cursor-grabbing",onMouseDown:tt,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-white truncate",children:[i.jsx(Eh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:Q?.name||e})]}),i.jsxs("div",{className:"flex items-center gap-1 no-drag",children:[i.jsx("button",{onClick:()=>de.mutate(!se?.chamber_light),disabled:!se?.connected||de.isPending||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${se?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:l("printers:control")?a("camera.chamberLight"):a("printers.permission.noControl"),children:i.jsx(lL,{on:se?.chamber_light??!1,className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>me(!0),disabled:!Le||!l("printers:control"),className:`p-1 rounded disabled:opacity-50 ${Le&&l("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:l("printers:control")?a(Le?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):a("printers.permission.noControl"),children:i.jsx(hk,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:Ee,disabled:ae||ce,className:"p-1 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:"Refresh stream",children:i.jsx(Ar,{className:`w-3.5 h-3.5 text-bambu-gray ${ae?"animate-spin":""}`})}),i.jsx("button",{onClick:O,className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:k?"Exit fullscreen":"Fullscreen",children:k?i.jsx(xX,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(Cme,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:()=>N(!_),className:"p-1 hover:bg-bambu-dark-tertiary rounded",title:_?"Expand":"Minimize",children:_?i.jsx(KC,{className:"w-3.5 h-3.5 text-bambu-gray"}):i.jsx(kF,{className:"w-3.5 h-3.5 text-bambu-gray"})}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-red-500/20 rounded",title:"Close",children:i.jsx(Lt,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-red-400"})})]})]}),!_&&i.jsxs("div",{className:"relative w-full bg-black flex items-center justify-center overflow-hidden h-[calc(100%-40px)]",onWheel:J,onMouseMove:Be,onMouseUp:Ie,onMouseLeave:Ie,onTouchStart:pe,onTouchMove:xe,onTouchEnd:ke,style:{touchAction:"none"},children:[ae&&!ce&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsx(Ar,{className:"w-6 h-6 text-bambu-gray animate-spin"})}),ce&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(jf,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Reconnecting in ",je,"s..."]})]})}),W&&!ce&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-2",children:[i.jsx(Tn,{className:"w-6 h-6 text-orange-400 mx-auto mb-2"}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Camera unavailable"}),i.jsx("button",{onClick:Ee,className:"px-2 py-1 text-xs bg-bambu-green text-white rounded hover:bg-bambu-green/80",children:"Retry"})]})}),i.jsx("img",{ref:_e,src:We,alt:"Camera stream",className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${M}) translate(${j.x/M}px, ${j.y/M}px)`,cursor:M>1?E?"grabbing":"grab":"default"},onError:we,onLoad:qe,onMouseDown:fe,draggable:!1},K),i.jsxs("div",{className:"absolute bottom-2 left-2 flex items-center gap-1 bg-black/60 rounded px-1.5 py-1 no-drag",children:[i.jsx("button",{onClick:q,disabled:M<=1,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom out",children:i.jsx(jF,{className:"w-3.5 h-3.5 text-white"})}),i.jsxs("button",{onClick:ge,className:"px-1.5 py-0.5 text-xs text-white hover:bg-white/10 rounded min-w-[32px]",title:"Reset zoom",children:[Math.round(M*100),"%"]}),i.jsx("button",{onClick:R,disabled:M>=4,className:"p-1 hover:bg-white/10 rounded disabled:opacity-30",title:"Zoom in",children:i.jsx(EF,{className:"w-3.5 h-3.5 text-white"})})]}),!k&&i.jsx("div",{className:"absolute bottom-0 right-0 w-6 h-6 cursor-se-resize no-drag hover:bg-white/10 rounded-tl transition-colors",onMouseDown:De,title:"Drag to resize",children:i.jsx("svg",{className:"w-6 h-6 text-bambu-gray/70 hover:text-bambu-gray",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22ZM22 10H20V8H22V10ZM18 14H16V12H18V14ZM14 18H12V16H14V18ZM10 22H8V20H10V22Z"})})})]}),i.jsx(cL,{printerId:t,isOpen:Y,onClose:()=>me(!1)})]})}function DTe({printerId:t,printerName:e,onClose:n}){const{t:r}=Ot(),a=en(),[s,o]=w.useState(!0),[l,c]=w.useState(new Set),[u,d]=w.useState(""),[h,f]=w.useState("all"),p=w.useRef(null),{data:x,isLoading:v,refetch:g}=Je({queryKey:["mqtt-logs",t],queryFn:()=>ne.getMQTTLogs(t),refetchInterval:1e3}),y=st({mutationFn:()=>ne.enableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),_=st({mutationFn:()=>ne.disableMQTTLogging(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}}),N=st({mutationFn:()=>ne.clearMQTTLogs(t),onSuccess:()=>{a.invalidateQueries({queryKey:["mqtt-logs",t]})}});w.useEffect(()=>{const E=U=>{U.key==="Escape"&&n()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[n]),w.useEffect(()=>{s&&p.current&&(p.current.scrollTop=p.current.scrollHeight)},[x?.logs,s]);const k=E=>{c(U=>{const L=new Set(U);return L.has(E)?L.delete(E):L.add(E),L})},A=E=>new Date(E).toLocaleTimeString("en-US",{hour12:!1,fractionalSecondDigits:3}),M=(E,U)=>{if(E==null)return"<empty>";const L=typeof E=="string"?JSON.parse(E):E,B=JSON.stringify(L,null,U?2:0);return!U&&B.length>100?B.substring(0,100)+"...":B},C=x?.logging_enabled??!1,j=w.useMemo(()=>x?.logs??[],[x?.logs]),P=w.useMemo(()=>j.filter(E=>{if(h!=="all"&&E.direction!==h)return!1;if(u.trim()){const U=u.toLowerCase(),L=E.topic.toLowerCase().includes(U),D=JSON.stringify(E.payload).toLowerCase().includes(U);return L||D}return!0}),[j,u,h]);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[85vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("mqttDebug.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:e})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[C?i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>_.mutate(),disabled:_.isPending,children:[i.jsx(vl,{className:"w-4 h-4"}),r("mqttDebug.stopLogging")]}):i.jsxs(Ce,{size:"sm",onClick:()=>y.mutate(),disabled:y.isPending,children:[i.jsx(io,{className:"w-4 h-4"}),r("mqttDebug.startLogging")]}),i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>N.mutate(),disabled:N.isPending||j.length===0,children:[i.jsx(Jt,{className:"w-4 h-4"}),r("mqttDebug.clearLog")]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:v,children:i.jsx(Ar,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:E=>o(E.target.checked),className:"rounded border-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[P.length,"/",j.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(xr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:r("mqttDebug.searchPlaceholder"),value:u,onChange:E=>d(E.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),u&&i.jsx("button",{onClick:()=>d(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>f("all"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${h==="all"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:r("mqttDebug.all")}),i.jsxs("button",{onClick:()=>f("in"),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${h==="in"?"bg-blue-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(lb,{className:"w-3 h-3"}),r("mqttDebug.incoming")]}),i.jsxs("button",{onClick:()=>f("out"),className:`px-2 py-1.5 text-xs rounded-r transition-colors flex items-center gap-1 ${h==="out"?"bg-green-500 text-white":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Mf,{className:"w-3 h-3"}),r("mqttDebug.outgoing")]})]})]})]}),i.jsx("div",{ref:p,className:"flex-1 overflow-auto p-4 font-mono text-xs bg-black min-h-[400px]",children:j.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessages")}),!C&&i.jsx("p",{className:"text-sm",children:r("mqttDebug.startLoggingHint")})]}):P.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:r("mqttDebug.noMessagesMatch")}),i.jsx("p",{className:"text-sm",children:r("mqttDebug.adjustFilterHint")})]}):i.jsx("div",{className:"space-y-1",children:P.map((E,U)=>{const L=l.has(U),B=E.direction==="in";return i.jsxs("div",{className:`p-2 rounded cursor-pointer hover:bg-bambu-dark-secondary transition-colors ${L?"bg-bambu-dark-secondary":""}`,onClick:()=>k(U),children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray shrink-0",children:A(E.timestamp)}),i.jsx("span",{className:`shrink-0 ${B?"text-blue-400":"text-green-400"}`,title:r(B?"mqttDebug.incoming":"mqttDebug.outgoing"),children:B?i.jsx(lb,{className:"w-3 h-3"}):i.jsx(Mf,{className:"w-3 h-3"})}),i.jsx("span",{className:"text-purple-400 shrink-0",children:E.topic})]}),L?i.jsx("pre",{className:"mt-2 p-3 bg-gray-900 border border-gray-700 rounded text-green-400 overflow-x-auto whitespace-pre-wrap break-all max-h-96 overflow-y-auto text-xs",children:M(E.payload,!0)}):i.jsx("pre",{className:"mt-1 text-white/80 truncate",children:M(E.payload,!1)})]},U)})})}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-sm text-bambu-gray",children:C?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),r("mqttDebug.loggingActive")]}):i.jsx("span",{children:r("mqttDebug.loggingStopped")})}),i.jsx(Ce,{variant:"secondary",onClick:n,children:r("common.close")})]})]})})}const pD={"0300_4000":"Z axis homing failed; the task has been stopped.","0300_4001":"The printer timed out waiting for the nozzle to cool down before homing.","0300_4002":"Auto Bed Leveling failed; the task has been stopped.","0300_4005":"The hotend cooling fan speed is abnormal.","0300_4006":"The nozzle is clogged.","0300_4008":"The AMS failed to change filament.","0300_4009":"Homing XY axis failed.","0300_400A":"Mechanical resonance frequency identification failed.","0300_400B":"Internal communication exception","0300_400C":"The task was canceled.","0300_400D":"Resume failed after power loss.","0300_400E":"The motor self-check failed.","0300_400F":"The power supply voltage does not match the printer.","0300_4010":"Nozzle offset calibration failed.","0300_4011":"Flow Dynamics Calibration failed; please reinitiate printing or calibration.","0300_4013":"Printing cannot be initiated while AMS is drying.","0300_4014":"Homing Z axis failed: temperature control abnormality.","0300_4015":"Nozzle clumping detection calibration failed. Please go to 'Assistant' for troubleshooting.","0300_4016":"Nozzle cleaning failed. Please click the Assistant for troubleshooting.","0300_401F":"The hotend is not installed, and the toolhead cannot perform homing. Please install the hotend and then continue.","0300_4020":"The nozzle presence detection failed. Please check the Assistant for details.","0300_4021":"Nozzle offset calibration sensor signal abnormality detected. Please check the sensor and retry.","0300_4042":"The Laser Safety Window is not properly installed. The task has been stopped.","0300_4044":"The Flame Sensor is abnormal. The sensor may be short-circuited. Please troubleshoot the issue before starting a print job.","0300_404B":"Task aborted because the front door or top cover is open.","0300_404D":"The current temperature of the hotend, heatbed, or chamber is too high. Please wait for it to cool down to room temperature before restarting the task.","0300_4050":"Liveview Camera calibration timeout; please restart the printer.","0300_4052":"Blade Z-axis homing failed","0300_4057":"Z-axis step loss detected. The task has stopped. Please check if there are any obstructions beneath the heatbed.","0300_4066":"Calibration of motion precision failed.","0300_4067":"Calibration result is over the threshold.","0300_4068":"Step loss occurred during the motion accuracy enhancement process. Please try again.","0300_8000":"Printing was paused for unknown reason. You can select 'Resume' to resume the print job.","0300_8001":"Printing was paused by the user. You can select 'Resume' to continue printing.","0300_8002":"First layer defects were detected by the Micro Lidar. Please check the quality of the printed model before continuing your print.","0300_8003":"Spaghetti defects were detected by the AI Print Monitoring. Please check the quality of the printed model before continuing your print.","0300_8004":"Filament ran out. Please load new filament.","0300_8005":"Toolhead front cover fell off. Please remount the front cover and check to make sure your print is going okay.","0300_8006":"The build plate marker was not detected. Please confirm the build plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible.","0300_8007":"There was an unfinished print job when the printer lost power. If the model is still adhered to the build plate, you can try resuming the print job.","0300_8008":"Nozzle temperature malfunction","0300_8009":"Heatbed temperature malfunction","0300_800A":"A Filament pile-up was detected by AI Print Monitoring. Please clean filament from the waste chute.","0300_800B":"The cutter is stuck. Please make sure the cutter handle is out and check the filament sensor cable connection.","0300_800C":"Skipped step detected: auto-recover complete; please resume print and check if there are any layer shift problems.","0300_800D":"Detected that the extruder is not extruding normally. If the defects are acceptable, select 'Resume' to resume the print job.","0300_800E":"The print file is not available. Please check to see if the storage media has been removed.","0300_800F":"The door seems to be open, so printing was paused.","0300_8010":"The hotend cooling fan speed is abnormal.","0300_8011":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0300_8013":"Printing paused due to the pause command added to the printing file.","0300_8014":"The nozzle is covered with filament, or the build plate is installed incorrectly. Please cancel this print and clean the nozzle or adjust the build plate according to the actual status. You can als...","0300_8015":"The filament on external spool has run out; please load new filament. If the filament is loaded, please select 'Resume'.","0300_8016":"The nozzle is clogged with filament. Please cancel this print and clean the nozzle or select 'Resume' to resume the print job.","0300_8017":"Foreign objects detected on heatbed. Please check and clean the heatbed. Then, select 'Resume' to resume the print job.","0300_8018":"Chamber temperature malfunction.","0300_8019":"No build plate is placed.","0300_801A":"Filament extrusion error; please check the assistant for troubleshooting. After resolving the issue, decide whether to cancel or resume the print job based on the actual print status.","0300_801B":"Nozzle temperature problem detected. Refer to Assistant to re-connect the hotend connector. POWER OFF the printer before this operation to avoid short circuits.","0300_801C":"The extrusion resistance is abnormal. The extruder may be clogged; please refer to the assistant. After trouble shooting, you can select 'Resume' to resume the print job.","0300_801D":"The extruder servo motor position sensor is malfunctioning. Please power off the printer first and check if the connection cable is loose.","0300_801E":"The extrusion motor is overloaded, please check the Assistant for details.","0300_8021":"The nozzle may not be installed or not properly installed. Please ensure the nozzle is correctly installed before proceeding.","0300_8022":"The heatbed may be obstructed while moving downward. Please clear any objects beneath the heatbed and check for any resistance or jamming during its movement.","0300_8028":"Nozzle offset calibration sensor error. If using a single hotend or the calibration function is disabled, you may ignore this and continue printing; otherwise, it is recommended to check the sensor...","0300_8041":"Platform detection timeout: please restart the printer.","0300_8042":"Task paused because the door is open.","0300_8043":"The laser module is abnormal.","0300_8044":"Fire was detected inside the chamber.","0300_8045":"Material detection timeout: please restart the printer.","0300_8046":"Foreign object detect timeout: please restart the printer.","0300_8047":"Quick-release lever detection time out: please restart the printer.","0300_8048":"Laser Module unlock has timed out, and the task cannot proceed. Please restart the printer and try again.","0300_8049":"The current plate is invalid.","0300_804A":"Emergency stop button improperly installed. Please reinstall according to the Wiki before proceeding.","0300_804B":"Task paused. The Laser Safety Window is open.","0300_804E":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0300_804F":"The loading/unloading process is currently ongoing. Please stop the process or remove the laser/cutting module.","0300_8050":"This device does not support the 40W Laser Module. Please remove it or replace it with a 10W Laser Module.","0300_8051":"The cutting module has dropped or the cutting module cable is disconnected; please check the module.","0300_8053":"Laser module detected. Please install the right nozzle correctly to ensure proper Laser Module Mounting Calibration.","0300_8054":"Please place the paper required for Print Then Cut.","0300_8055":"The module mounted on the toolhead does not match the task. Please install the correct module.","0300_8057":"The rotary attachment is disconnected. Please ensure it is properly installed and the cable is securely plugged in.","0300_8058":"The rotary attachment is detected. Please remove it before continuing.","0300_8061":"The mode of Airflow System failed to activate; check the air door condition.","0300_8062":"The chamber temperature is too high. It may be due to high environmental temperature.","0300_8063":"The chamber temperature is too high. Please open the top cover and front door to cool down.","0300_8064":"The chamber temperature is too high. Please open the top cover and front door to cool down. (Open door detection for this print job will be set to 'Notification' level)","0300_8065":"The temperature of the MC module is too high. Please check the Wiki for possible explanations.","0300_8071":"The Toolhead Enhanced Cooling Fan module is malfunctioning.","0300_807D":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807E":"Fire Extinguisher not detected, the automatic extinguishing function will be unavailable.","0300_807F":"Fire Extinguisher is malfunctioning.","0300_8080":"Fire extinguisher motor reset failed.","0300_8081":"Fire extinguisher cylinder not installed. Please confirm on the extinguisher page.","0300_8082":"The Fire Extinguisher Gas Cylinder is empty.","0300_C012":"Please heat the nozzle to above 170°C.","0300_C056":"A minor fire was detected inside the chamber, and the Auto Fire Extinguishing process has been aborted.","0300_C070":"The fire extinguisher has been detected and is ready for use after the laser module is connected.","0500_4001":"Failed to connect to Bambu Cloud. Please check your network connection.","0500_4002":"Unsupported print file path or name. Please resend the print job.","0500_4003":"Printing stopped because the printer was unable to parse the file. Please resend your print job.","0500_4004":"Device is busy and cannot start new task. Please wait for current task to complete before sending new task.","0500_4005":"Print jobs are not allowed to be sent while updating firmware.","0500_4006":"There is not enough free storage space for the print job. Restoring to factory settings can free up available space.","0500_4007":"The device requires a repair upgrade, and printing is currently unavailable.","0500_4008":"Starting printing failed; please power cycle the printer and resend the print job.","0500_4009":"Print jobs are not allowed to be sent while updating logs.","0500_400A":"The file name is not supported. Please rename and restart the print job.","0500_400B":"There was a problem downloading a file. Please check your network connection and resend the print job.","0500_400C":"Please insert a MicroSD card and restart the print job.","0500_400D":"Please run a self-test and restart the print job.","0500_400E":"Printing was cancelled.","0500_400F":"AMS is initializing and cannot be upgraded at the moment. Please try again later.","0500_4010":"AMS is drying and cannot be upgraded at the moment. Please try again later.","0500_4011":"The printer is loading or unloading filament and cannot be upgraded at the moment. Please try again later.","0500_4012":"The device is printing and cannot be upgraded at the moment. Please try again later.","0500_4013":"AMS is in operation and cannot be upgraded at the moment. Please try again when it is idle.","0500_4014":"Slicing for the print job failed. Please check your settings and restart the print job.","0500_4015":"There is not enough free storage space for the print job. Please format or clear files from the MicroSD card to free up space.","0500_4016":"The MicroSD Card is write-protected. Please replace the MicroSD Card.","0500_4017":"Binding failed. Please retry or restart the printer and retry.","0500_4018":"Binding configuration information parsing failed; please try again.","0500_4019":"The printer has already been bound. Please unbind it and try again.","0500_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0500_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0500_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0500_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0500_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0500_402A":"Failed to connect to the router, which may be caused by wireless interference or being too far away from the router. Please try again or move the printer closer to the router and try again.","0500_402B":"Router connection failed due to incorrect password. Please check the password and try again.","0500_402C":"Failed to obtain IP address, which may be caused by wireless interference resulting in data transmission failure or the DHCP address pool of the router being full. Please move the printer closer to...","0500_402D":"System exception","0500_402E":"System does not support the file system currently used by the USB flash drive. Please replace or format the USB flash drive to FAT32.","0500_402F":"The MicroSD card sector data is damaged. Please use the SD card repair tool to repair or format it. If it still cannot be identified, please replace the MicroSD card.","0500_4030":"The device is currently upgrading. Please try again when it is idle.","0500_4031":"The accessory firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4033":"The AMS firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4034":"The Laser Module firmware does not match the printer. Please update it on the 'Firmware' page.","0500_4035":"The BirdsEye Camera is malfunctioning. Please try restarting the device. If the issue persists after multiple restarts, check the camera connection status or contact customer support.","0500_4037":"Your sliced file is not compatible with current printer model. This file can't be printed on this printer.","0500_4038":"The nozzle diameter in sliced file is not consistent with the current nozzle setting. This file can't be printed.","0500_4039":"The current task does not allow the installation of the laser/cutting module, and the task has been halted.","0500_403A":"The current temperature is too low. In order to protect you and your printer, printing tasks, moving an axis and other operations are disabled. Please move the printer to an environment above 10 de...","0500_403B":"Laser/cutting tasks cannot be initiated on the machine at the moment. Please use the computer software to start the task.","0500_403C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_403D":"The toolhead module is not set up. Please set it up before initiating the task.","0500_403E":"The current tool head does not support initialization.","0500_403F":"Failed to download print job; please check your network connection.","0500_4040":"The printer has reached its power limit. Please connect a dedicated power adapter to this AMS to enable drying.","0500_4041":"The AMS drying cannot be started during printing.","0500_4042":"Due to power limitations, starting AMS drying will pause current operations such as nozzle heating and fan running. Do you want to proceed with drying?","0500_4043":"Due to power limitations, only one AMS is allowed to use the device's power for drying.","0500_4044":"BirdsEye Camera malfunction: please contact customer support.","0500_4045":"Hotend check in progress. This operation is temporarily unavailable. Please wait.","0500_4050":"Error detected on the print board.","0500_4052":"Error detected on the hot end.","0500_4054":"Error detected on the mat.","0500_405D":"Laser module Serial Number error: unable to calibrate or make project.","0500_4065":"The task requires a Laser Platform, but the current one is a Cutting Platform. Please replace it, measure the material thickness in the software, and then restart the task.","0500_4070":"The laser or cutter module is connected, so the device cannot initiate a 3D printing task.","0500_4075":"No Laser Platform was detected, which may affect thickness measurement accuracy. Please place the laser platform correctly and ensure the rear markers are not blocked, then restart the thickness me...","0500_4076":"Please place the Laser Platform correctly and ensure the rear markers are not blocked, then restart the thickness measurement in the software before initiating the task.","0500_4097":"The device cannot detect the Laser Module. Please reconnect the module cable or restart the printer.","0500_4098":"The device cannot detect AMS A. Please reconnect the AMS cable or restart the printer.","0500_4099":"The firmware of Cutting Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409A":"The firmware of the Air Pump does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409B":"The firmware of the Laser Module does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0500_409D":"The firmware of AMS A does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0500_409E":"The device cannot detect the Cutting Module. Please reconnect the module cable or restart the printer.","0500_409F":"The device cannot detect the Air Pump. Please reconnect the module cable or restart the printer.","0500_40A0":"The Rotary Attachment module is not detected. Please reconnect the cable or restart the printer.","0500_40A1":"The Auto Fire Extinguishing System is not detected. Please reconnect the module cable or restart the printer.","0500_40A3":"AMS(or AMS lite) A communication is abnormal. Please reconnect the module cable or restart the printer.","0500_40A4":"The current firmware only supports 1 AMS Lite. Please remove all AMS units before reconnecting the supported AMS Lite device.","0500_40A5":"The current firmware only supports AMS/AMS 2 Pro/AMS HT, with a maximum of 4 units. Please remove all AMS units before reconnecting the supported one.","0500_8013":"The print file is not available. Please check to see if the storage media has been removed.","0500_8036":"Your sliced file is not consistent with the current printer model. Continue?","0500_803C":"The current nozzle setting does not match the slicing file. Continuing to print may affect print quality. It is recommended to re-slice before starting the print.","0500_8040":"Toolhead front cover is detached. Moving the toolhead may damage the printer. Do you want to continue?","0500_8041":"The filament in hotend is too cold. Extrusion may damage the extruder. Still feeding in/out the filament?","0500_8048":"The module on the toolhead is not calibrated. Please cancel the task to perform calibration or switch to a calibrated module.","0500_8051":"Detected build plate is not the same as the Gcode file. Please adjust slicer settings or use the correct plate.","0500_8053":"Nozzle mismatch was detected during printing. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","0500_8055":"Laser module is installed, but a Cutting Platform is detected. Please place a Laser Platform and perform laser calibration.","0500_8056":"Cutting module is installed, but the laser platform is detected. Please place the cutting platform for calibration.","0500_8058":"Please place the light grip cutting mat correctly and ensure the marker is exposed.","0500_8059":"Cutting platform base is not correctly aligned. Please ensure that the four corners of the platform are aligned with the heatbed.","0500_805A":"Please place the cutting mat on cutting protection base.","0500_805B":"The cutting mat type is unknown; please replace it with the correct cutting mat.","0500_805C":"The grip cutting mat type does not match; please place a LightGrip cutting mat.","0500_805E":"Cutting module Serial Number error: unable to calibrate or make project.","0500_8060":"The current module on toolhead does not meet requirements. Please replace the module as per the on-screen instructions.","0500_8061":"No print plate detected. Please make sure it is placed correctly.","0500_8062":"The print plate marker was not detected. Please confirm the print plate is correctly positioned on the heatbed with all four corners aligned, and the marker is visible. If strong light is shining o...","0500_8063":"The platform is not detected during calibration; please make sure the Laser Platform is properly placed.","0500_8064":"Please place the Laser Platform correctly and ensure the rear markers are not blocked for laser calibration.","0500_8066":"The task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + LightGrip cutting mat).","0500_8067":"Please place a LightGrip cutting mat on the cutting protection base.","0500_8068":"Please place the strong grip cutting mat correctly and ensure the marker is exposed.","0500_8069":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please manually set the hotend types.","0500_806A":"Unable to recognize the left and right hotends. They might be third party hotends, or the hotend marks may be dirty. Please set hotend types on printer screen before next print.","0500_806B":"Quick-release Lever is not locked. Please press down the external toolhead module to ensure it is properly seated, then push down the level to lock it in place.","0500_806C":"Please place the cutting platform correctly and ensure the marker is exposed.","0500_806D":"Material not detected. Please confirm placement and continue.","0500_806E":"Foreign objects detected on heatbed; please check and clean up the heatbed.","0500_806F":"The grip cutting mat type does not match; please place a StrongGrip cutting mat.","0500_8071":"No cutting platform was detected. Please confirm that it has been correctly placed.","0500_8072":"Live View camera is blocked","0500_8073":"Heatbed limit block is obstructed or contaminated. Please clean and ensure the limit block is visible, otherwise platform position offset detection may be inaccurate.","0500_8074":"The Laser Platform is offset. Please ensure that the four corners of the platform are aligned with the heatbed, and the marker is not obstructed.","0500_8077":"The visual marker was not detected. Please ensure the paper is properly placed.","0500_8078":"Current material does not match the sliced file settings. Please load the correct material and ensure the QR code on the material is not damaged or dirty.","0500_8079":"Please place the Laser Test Material (350g paperboard) and position support strips underneath to prevent material warping.","0500_807A":"The foreign object detection function is not working. You can continue the task or check the assistant for troubleshooting.","0500_807B":"Please place the cutting platform (cutting protection base + LightGrip cutting mat).","0500_807C":"Please place the cutting platform (cutting protection base + StrongGrip cutting mat).","0500_807D":"This task requires a Cutting Platform, but the current one is a Laser Platform. Please replace it with a Cutting Platform (Cutting Protection Base + StrongGrip Cutting Mat).","0500_807E":"Please place a StrongGrip cutting mat on the cutting protection base.","0500_8080":"The left and right hotends are not installed.","0500_8081":"The left and right hotends are not installed.","0500_8082":"Please remove the protective film on the Opaque Glossy Acrylic before processing","0500_8083":"Material is not allowed in Mounting Calibration. Please remove the material from the platform.","0500_8084":"The Live View Camera is dirty; please clean it and continue.","0500_8085":"Toolhead camera is obstructed","0500_8086":"Toolhead Camera is dirty, which affects the AI function; please clean the lens surface.","0500_8087":"BirdsEye camera is obstructed","0500_8088":"The Birdseye Camera is dirty","0500_8089":"Task paused due to Presence Check failed. Please check the printer to continue.","0500_808A":"The BirdsEye Camera is installed offset. Please refer to the assistant to reinstall it.","0500_808B":"The BirdsEye Camera setup failed. Please remove all objects and the mat on the heatbed to ensure the heatbed markers are visible. Meanwhile, please ensure the BirdsEye Camera is installed correctly...","0500_808C":"Detected build plate offset. Please align the build plate with the heatbed, and then continue.","0500_808D":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the cutting material is properly positioned and check whether the cutting blade tip is worn.","0500_808E":"BirdsEye Camera initialization failed. The toolhead camera did not detect the Heatbed features. Please clean the Heatbed, remove all objects and pads, and ensure the bed markings are visible. Check...","0500_808F":"Nozzle camera lens is dirty, affecting AI monitoring. Clean the lens with a non-woven cloth and a small amount of alcohol. Beware of hotend heat; wait for it to cool before handling.","0500_8090":"Please attach the 80g White Printing Paper to the center area of the platform.","0500_8091":"The Cutting Module offset calibration failed, which may result in inaccurate cuts. Please ensure the 80g white printer paper(letter paper thickness) is properly positioned and check whether the cut...","0500_8092":"Toolhead Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0500_8093":"The nozzle silicone sleeve is not installed; there is a risk of temperature control failure. Please install it correctly and try again.","0500_80A0":"The visual encoder board was not detected. Please check if the board is properly placed and aligned at all four corners, and ensure the positioning markings are clear and free from wear.","0500_C010":"MicroSD Card read/write exception: please reinsert or replace the MicroSD Card.","0500_C032":"Laser/Cutting module connected to the toolhead. The drying process has been automatically stopped.","0500_C036":"This is a printing task. Please detach the Laser/Cutting Module from the Toolhead.","0500_C07F":"Device is busy and cannot perform this operation. To proceed, please pause or stop the current task.","0501_4017":"Binding failed. Please retry or restart the printer and retry.","0501_4018":"Binding configuration information parsing failed; please try again.","0501_4019":"The printer has already been bound. Please unbind it and try again.","0501_401A":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_401B":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401C":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_401D":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_401E":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_401F":"Authorization timed out. Please make sure that your phone or PC has access to the internet, and ensure that the Bambu Studio/Bambu Handy APP is running in the foreground during the binding operation.","0501_4020":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4021":"Cloud access failed, which may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4022":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4023":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4024":"Cloud access failed. Possible reasons include network instability caused by interference, inability to access the internet, or router firewall configuration restrictions. You can try moving the pri...","0501_4025":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4026":"Cloud access rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4027":"Cloud access failed; this may be caused by network instability due to interference. You can try moving the printer closer to the router before you try again.","0501_4028":"Cloud response is invalid. If you have tried multiple times and are still failing, please contact customer support.","0501_4029":"Cloud access is rejected. If you have tried multiple times and are still failing, please contact customer support.","0501_4031":"Device discovery binding is in progress, and the QR code cannot be displayed on the screen. You can wait for the binding to finish or abort the device discovery binding process in the APP/Studio an...","0501_4032":"QR code binding is in progress, so device discovery binding cannot be performed. You can scan the QR code on the screen for binding or exit the QR code display page on screen and try device discove...","0501_4033":"Your APP region does not match with your printer; please download the APP in the corresponding region and register your account again.","0501_4034":"The slicing progress has not been updated for a long time, and the printing task has exited. Please confirm the parameters and reinitiate printing.","0501_4035":"The device is in the process of binding and cannot respond to new binding requests.","0501_4038":"The regional settings do not match the printer; please check the printer's regional settings.","0501_4039":"Device login has expired; please try to bind again.","0501_4098":"The device cannot detect AMS B. Please reconnect the AMS cable or restart the printer.","0501_409D":"The firmware of AMS B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0501_40A3":"AMS(or AMS lite) B communication is abnormal. Please reconnect the module cable or restart the printer.","0502_4001":"Current filament will be used in this print job. Settings cannot be changed.","0502_4002":"Please go to “Settings > Calibration” to run the Motion Accuracy Enhancement Calibration before turning on Motion Accuracy Enhancement mode.","0502_4003":"The printer is currently printing and the motion accuracy enhancement feature cannot be turned on or off.","0502_4004":"Some features are not supported by the current device. Please check the Studio feature settings or update the firmware to the latest version.","0502_4005":"The AMS has not been calibrated yet, so printing cannot be initiated.","0502_4006":"Unknown module detected; please try updating the firmware to the latest version.","0502_400D":"Failed to start a new task: filament loading/unloading not completed.","0502_400E":"Failed to start a new task: The nozzle cold pull was not completed.","0502_4013":"This device is not compatible with the 40W laser module. Please replace it with a 10W laser module or remove it.","0502_4098":"The device cannot detect AMS C. Please reconnect the AMS cable or restart the printer.","0502_409D":"The firmware of AMS C does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0502_40A3":"AMS(or AMS lite) C communication is abnormal. Please reconnect the module cable or restart the printer.","0502_C00F":"The device is busy and cannot perform nozzle identification.","0502_C010":"Due to printer power limitations, printing, calibration, controls and other actions cannot be performed during AMS drying. Please stop the drying process before proceeding with any other operation.","0502_C011":"Currently in 2D production mode. Please continue the operation on the printer","0502_C012":"The task cannot be paused.","0502_C014":"The AMS Remaining Filament Estimation is enabled by default and cannot be disabled.","0502_C024":"The flow dynamic calibration records have exceeded the storage limit. Please delete some historical records in the slicer software before adding new calibration data.","0503_4098":"The device cannot detect AMS D. Please reconnect the AMS cable or restart the printer.","0503_409D":"The firmware of AMS D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0503_40A3":"AMS(or AMS lite) D communication is abnormal. Please reconnect the module cable or restart the printer.","0580_4096":"The device cannot detect AMS-HT A. Please reconnect the AMS-HT cable or restart the printer.","0580_409C":"The firmware of AMS-HT A does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0580_40A2":"AMS-HT A communication is abnormal. Please reconnect the module cable or restart the printer.","0581_4096":"The device cannot detect AMS-HT B. Please reconnect the AMS-HT cable or restart the printer.","0581_409C":"The firmware of AMS-HT B does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0581_40A2":"AMS-HT B communication is abnormal. Please reconnect the module cable or restart the printer.","0582_4096":"The device cannot detect AMS-HT C. Please reconnect the AMS-HT cable or restart the printer.","0582_409C":"The firmware of AMS-HT C does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0582_40A2":"AMS-HT C communication is abnormal. Please reconnect the module cable or restart the printer.","0583_4096":"The device cannot detect AMS-HT D. Please reconnect the AMS-HT cable or restart the printer.","0583_409C":"The firmware of AMS-HT D does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0583_40A2":"AMS-HT D communication is abnormal. Please reconnect the module cable or restart the printer.","0584_4096":"The device cannot detect AMS-HT F. Please reconnect the AMS-HT cable or restart the printer.","0584_409C":"The firmware of AMS-HT E does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0584_40A2":"AMS-HT E communication is abnormal. Please reconnect the module cable or restart the printer.","0585_4096":"The device cannot detect AMS-HT E. Please reconnect the AMS-HT cable or restart the printer.","0585_409C":"The firmware of AMS-HT F does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0585_40A2":"AMS-HT F communication is abnormal. Please reconnect the module cable or restart the printer.","0586_4096":"The device cannot detect AMS-HT G. Please reconnect the AMS-HT cable or restart the printer.","0586_409C":"The firmware of AMS-HT G does not match the printer; the device cannot continue working. Please update it on the 'Firmware' page.","0586_40A2":"AMS-HT G communication is abnormal. Please reconnect the module cable or restart the printer.","0587_4096":"The device cannot detect AMS-HT H. Please reconnect the AMS-HT cable or restart the printer.","0587_409C":"The firmware of AMS-HT H does not match the printer; the device cannot continue working. Please upgrade it on the 'Firmware' page.","0587_40A2":"AMS-HT H communication is abnormal. Please reconnect the module cable or restart the printer.","05FE_8053":"The left nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FE_8069":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FE_806A":"Unable to recognize the left hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FE_8080":"The left hotend is not installed.","05FE_8081":"The left hotend is not installed.","05FF_8053":"The right nozzle is not matched with slicing file. Please initiate the print after re-slicing, or continue printing after replacing with the correct nozzle. Caution: the hotend temperature is high.","05FF_8069":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please manually set the hotend type.","05FF_806A":"Unable to recognize the right hotend. It might be a third party hotend, or the hotend mark may be dirty. Please set hotend type on printer screen before next print.","05FF_8080":"The right hotend is not installed.","05FF_8081":"The right hotend is not installed.","0700_4001":"The AMS has been disabled for a print, but it still has filament loaded. Please unload the AMS filament and switch to the spool holder filament for printing.","0700_4025":"Failed to read the filament information.","0700_8001":"Failed to cut the filament. Please check the cutter.","0700_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0700_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0700_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0700_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0700_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0700_8007":"Extruding filament failed. The extruder might be clogged.","0700_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS A to the extruder is properly connected.","0700_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0700_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0700_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0700_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0700_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0700_8017":"AMS A is drying. Please stop drying process before loading/unloading material.","0700_8021":"AMS setup failed; please refer to the assistant.","0700_8023":"AMS A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0700_C069":"An error occurred during AMS A drying. Please go to Assistant for more details.","0700_C06A":"AMS A is reading RFID. Unable to start drying. Please try again later.","0700_C06B":"AMS A is changing filament. Unable to start drying. Please try again later.","0700_C06C":"AMS A is in Feed Assist Mode. Unable to start drying. Please try again later.","0700_C06D":"AMS A is assisting in filament insertion. Unable to start drying. Please try again later.","0700_C06E":"AMS A motor is performing self-test. Unable to start drying. Please try again later.","0701_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0701_4025":"Failed to read the filament information.","0701_8001":"Failed to cut the filament. Please check the cutter.","0701_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0701_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0701_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0701_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0701_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0701_8007":"Extruding filament failed. The extruder might be clogged.","0701_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS B to the extruder is properly connected.","0701_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0701_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0701_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0701_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0701_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0701_8017":"AMS B is drying. Please stop drying process before loading/unloading material.","0701_8021":"AMS setup failed; please refer to the assistant.","0701_8023":"AMS B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0701_C069":"An error occurred during AMS B drying. Please go to Assistant for more details.","0701_C06A":"AMS B is reading RFID. Unable to start drying. Please try again later.","0701_C06B":"AMS B is changing filament. Unable to start drying. Please try again later.","0701_C06C":"AMS B is in Feed Assist Mode. Unable to start drying. Please try again later.","0701_C06D":"AMS B is assisting in filament insertion. Unable to start drying. Please try again later.","0701_C06E":"AMS B motor is performing self-test. Unable to start drying. Please try again later.","0702_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0702_4025":"Failed to read the filament information.","0702_8001":"Failed to cut the filament. Please check the cutter.","0702_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0702_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0702_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0702_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0702_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0702_8007":"Extruding filament failed. The extruder might be clogged.","0702_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS C to the extruder is properly connected.","0702_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0702_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0702_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0702_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0702_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0702_8017":"AMS C is drying. Please stop drying process before loading/unloading material.","0702_8021":"AMS setup failed; please refer to the assistant.","0702_8023":"AMS C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0702_C069":"An error occurred during AMS C drying. Please go to Assistant for more details.","0702_C06A":"AMS C is reading RFID. Unable to start drying. Please try again later.","0702_C06B":"AMS C is changing filament. Unable to start drying. Please try again later.","0702_C06C":"AMS C is in Feed Assist Mode. Unable to start drying. Please try again later.","0702_C06D":"AMS C is assisting in filament insertion. Unable to start drying. Please try again later.","0702_C06E":"AMS C motor is performing self-test. Unable to start drying. Please try again later.","0703_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","0703_4025":"Failed to read the filament information.","0703_8001":"Failed to cut the filament. Please check the cutter.","0703_8002":"The cutter is stuck. Please make sure the cutter handle is out.","0703_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0703_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0703_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0703_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0703_8007":"Extruding filament failed. The extruder might be clogged.","0703_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS D to the extruder is properly connected.","0703_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0703_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0703_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0703_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0703_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0703_8017":"AMS D is drying. Please stop drying process before loading/unloading material.","0703_8021":"AMS setup failed; please refer to the assistant.","0703_8023":"AMS D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0703_C069":"An error occurred during AMS D drying. Please go to Assistant for more details.","0703_C06A":"AMS D is reading RFID. Unable to start drying. Please try again later.","0703_C06B":"AMS D is changing filament. Unable to start drying. Please try again later.","0703_C06C":"AMS D is in Feed Assist Mode. Unable to start drying. Please try again later.","0703_C06D":"AMS D is assisting in filament insertion. Unable to start drying. Please try again later.","0703_C06E":"AMS D motor is performing self-test. Unable to start drying. Please try again later.","0704_4025":"Failed to read the filament information.","0704_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0704_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0704_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0704_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0704_8007":"Extruding filament failed. The extruder might be clogged.","0704_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS E to the extruder is properly connected.","0704_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0704_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0704_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0704_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0704_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0704_8021":"AMS setup failed; please refer to the assistant.","0704_8023":"AMS E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0705_4025":"Failed to read the filament information.","0705_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0705_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0705_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0705_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0705_8007":"Extruding filament failed. The extruder might be clogged.","0705_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS F to the extruder is properly connected.","0705_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0705_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0705_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0705_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0705_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0705_8021":"AMS setup failed; please refer to the assistant.","0705_8023":"AMS F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0706_4025":"Failed to read the filament information.","0706_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0706_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0706_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0706_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0706_8007":"Extruding filament failed. The extruder might be clogged.","0706_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS G to the extruder is properly connected.","0706_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0706_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0706_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0706_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0706_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0706_8021":"AMS setup failed; please refer to the assistant.","0706_8023":"AMS G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","0707_4025":"Failed to read the filament information.","0707_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","0707_8004":"AMS failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","0707_8005":"The AMS failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","0707_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","0707_8007":"Extruding filament failed. The extruder might be clogged.","0707_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS H to the extruder is properly connected.","0707_8010":"The AMS assist motor is overloaded. This could be due to entangled filament or a stuck spool.","0707_8011":"AMS filament ran out. Please insert a new filament into the same AMS slot.","0707_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","0707_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","0707_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","0707_8021":"AMS setup failed; please refer to the assistant.","0707_8023":"AMS H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","07FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","07FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","07FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","07FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","07FE_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FE_8010":"Check if the left external filament spool or filament is stuck.","07FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","07FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","07FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","07FE_8020":"Extruder change failed; please refer to the assistant.","07FE_8021":"AMS setup failed; please refer to the assistant.","07FE_8024":"Extruder position calibration failed; please refer to the assistant.","07FE_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FE_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","07FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","07FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FE_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FE_C011":"Please manually and slowly pull out the filament from the extruder. Then click “Continue”.","07FE_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","07FF_4001":"Filament is still loaded from the AMS after it has been disabled. Please unload the filament, load from the spool holder, and restart printing.","07FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","07FF_8002":"The cutter is stuck. Please make sure the cutter handle is out.","07FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","07FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","07FF_8005":"Failed to feed the filament outside the AMS. Please clip the end of the filament flat and check to see if the spool is stuck.","07FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","07FF_8010":"Check if the external filament spool or filament is stuck.","07FF_8011":"External filament has run out; please load a new filament.","07FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","07FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","07FF_8020":"Extruder change failed; please refer to the assistant.","07FF_8021":"AMS setup failed; please refer to the assistant.","07FF_8024":"Extruder position calibration failed; please refer to the assistant.","07FF_8025":"Cold pull timed out. Please promptly operate or check whether the filament is broken inside the extruder, and click the Assistant for details.","07FF_8030":"The filament specified in the slicer has been used up. Printing is paused. Please go to the machine to replace the material and resume printing.","07FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","07FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","07FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","07FF_C010":"Insert the filament (over 30cm long) until it stops. You might see slight smoke during flushing. After insertion, close the front door and top cover.","07FF_C011":"Hold the driven wheel bracket, slowly pull the filament from the extruder, then press 'Continue'.","07FF_C012":"Press the black PTFE tube coupler and unplug the PTFE tube. After completing the operation, click 'Continue.'","0C00_4020":"The setup of BirdsEye Camera failed. Please clear all objects and remove the mat. Make sure the marker is not obstructed. Meanwhile, clean both the BirdsEye Camera and Toolhead Camera, and remove a...","0C00_4021":"The setup of BirdsEye Camera failed; please reboot the printer.","0C00_4022":"The setup of BirdsEye Camera failed. Please check if the laser module is working properly.","0C00_4024":"The Birdseye Camera is installed offset. Please refer to the assistant to reinstall it.","0C00_4025":"The Birdseye Camera is dirty. Please clean it and restart the process.","0C00_4026":"The Live View Camera initialization failed; please reboot the printer.","0C00_4027":"The Live View Camera calibration failed. Please refer to the assistant for details and recalibrate the camera after processing.","0C00_4029":"Material not detected. Please confirm placement and continue.","0C00_402A":"The visual marker was not detected. Please re-paste the paper in the correct position.","0C00_402C":"Device data link error. Please reboot the printer","0C00_402D":"The toolhead camera is not working properly; please reboot the device.","0C00_403D":"The vision encoder plate was not detected. Please confirm it is correctly positioned on the heatbed.","0C00_403E":"The high-precision nozzle offset calibration has failed, possibly due to a damaged pattern or the similarity of the colors of the two selected filaments. Please clear the printed pattern and replac...","0C00_4041":"Toolhead camera calibration failed. Please ensure the Calibration Marker on the heatbed or Height Calibration Marker on the homing area is clean and undamaged, then re-run the calibration process.","0C00_8001":"First layer defects were detected. If the defects are acceptable, select 'Resume' to resume the print job.","0C00_8005":"Purged filament has piled up in the waste chute, which may cause a tool head collision.","0C00_8009":"Build plate localization marker was not found.","0C00_800B":"The heatbed marker was not detected. Please clear all objects and remove the mat. Make sure the marker is not obstructed.","0C00_8015":"Objects detected on the platform; please clean them up in a timely manner.","0C00_8016":"The foreign object detection function is not working. You can continue the task or check assistant for solutions.","0C00_8017":"Foreign objects detected on the platform; please clean them up on time.","0C00_8018":"The foreign object detection function is not working. You can continue the task or view the assistant for troubleshooting.","0C00_8033":"Quick-release Lever is not locked. Please push it down to secure.","0C00_8034":"Liveview Camera initialization failed. This print can still continue, but some AI functions will be disabled. If you encounter this issue again after restarting, please contact customer support.","0C00_803F":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_8040":"AI detected air-printing defect. Please check the hotend extrusion status. Refer to assistant for solutions.","0C00_8042":"The AI print monitor has detected a spaghetti defect. Please check the print and take the necessary action.","0C00_8043":"AI detected nozzle clumping. Please check the nozzle condition. Refer to assistant for solutions.","0C00_C003":"Possible defects were detected in the first layer.","0C00_C004":"Possible spaghetti failure was detected.","0C00_C006":"Purged filament may have piled up in the waste chute.","1000_C001":"High bed temperature may lead to filament clogging in the nozzle. You may open the chamber door.","1000_C002":"Printing CF material with stainless steel may cause nozzle damage.","1000_C003":"Enabling Timelapse in traditional mode may cause defects; please activate this feature as needed.","1001_4001":"Timelapse is not supported as Spiral Vase mode is enabled in slicing presets.","1001_4002":"Timelapse is not supported as the Print sequence is set to 'By object'.","1001_8003":"The time-lapse mode is set to Traditional in the slicing file. This may cause surface defects. Would you like to enable it?","1001_8004":"Prime Tower is not enabled and time-lapse mode is set to Smooth in slicing file. This may cause surface defects. Would you like to enable it?","1200_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1200_8001":"Cutting the filament failed. Please check to see if the cutter is stuck. Refer to the Assistant for solutions.","1200_8002":"The cutter is stuck. Please pull out the cutter handle.","1200_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1200_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1200_8005":"The filament is not inserted. Please insert the filament.","1200_8006":"Unable to feed filament into the extruder. This could be due to tangled filament or a stuck spool. If not, please check if the AMS PTFE tube is connected.","1200_8007":"Failed to extrude the filament. This might be caused by clogged extruder or stuck filament. Refer to the Assistant for solutions.","1200_8010":"Filament or spool may be stuck.","1200_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1200_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1200_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1200_8014":"The filament location in the toolhead was not found. Refer to the Assistant for solutions.","1200_8015":"Failed to pull out the filament from the toolhead. Please check if the filament is stuck, or if it is broken inside the extruder or PTFE tube.","1200_8016":"The extruder is not extruding normally. Refer to the Assistant for troubleshooting. There may be defects in this layer, but you may resume if the defects are acceptable.","1201_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1201_8001":"Failed to cut the filament. Please check the cutter.","1201_8002":"The cutter is stuck. Please pull out the cutter handle.","1201_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1201_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1201_8005":"Failed to feed the filament. Please load the filament and then select 'Retry'.","1201_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1201_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1201_8010":"Please check if the spool or filament is stuck.","1201_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1201_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1201_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1201_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1201_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or the filament is broken inside the extruder.","1201_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1202_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1202_8001":"Failed to cut the filament. Please check the cutter.","1202_8002":"The cutter is stuck. Please pull out the cutter handle.","1202_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1202_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1202_8005":"The filament is not inserted. Please insert the filament.","1202_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1202_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1202_8010":"Please check if the spool or filament is stuck.","1202_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1202_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1202_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1202_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1202_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1202_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","1203_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","1203_8001":"Failed to cut the filament. Please check the cutter.","1203_8002":"The cutter is stuck. Please pull out the cutter handle.","1203_8003":"Failed to pull out the filament from the extruder. Please check whether the extruder is clogged or whether the filament is broken inside the extruder.","1203_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","1203_8005":"The filament is not inserted. Please insert the filament.","1203_8006":"Failed to feed the filament into the toolhead. Please check whether the filament is stuck.","1203_8007":"Failed to extrude the filament. The extruder may be clogged or the filament may be stuck; please refer to HMS.","1203_8010":"Please check if the spool or filament is stuck.","1203_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","1203_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1203_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","1203_8014":"Failed to check the filament location in the tool head; please refer to the HMS.","1203_8015":"Failed to pull back the filament from the toolhead. Please check if the filament is stuck or is broken inside the extruder.","1203_8016":"The extruder is not extruding normally; please refer to the HMS. After trouble shooting, if the defects are acceptable, please resume printing.","12FF_4001":"Filament is still loaded from the AMS when it has been disabled. Please unload AMS filament, load from spool holder, and restart print job.","12FF_8001":"Failed to cut the filament. Please check the cutter.","12FF_8002":"The cutter is stuck. Please pull out the cutter handle.","12FF_8003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube if you are about to us...","12FF_8004":"Failed to pull back the filament from the toolhead. Please check whether the filament is stuck.","12FF_8005":"The filament is not inserted. Please insert the filament.","12FF_8006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","12FF_8007":"Check nozzle. Select 'Done' if filament was extruded, otherwise push filament forward slightly and select 'Retry.'","12FF_8010":"Please check if the filament or the spool is stuck.","12FF_8011":"AMS filament has run out. Please insert a new filament into the same AMS slot.","12FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","12FF_8013":"Timeout while purging old filament. Please check if the filament is stuck or the extruder clogged.","12FF_C003":"Please pull out the filament on the spool holder. If this message persists, please check to see if there is filament broken in the extruder or PTFE Tube. (Connect a PTFE tube if you are about to us...","12FF_C006":"Please feed filament into the PTFE tube until it can not be pushed any farther.","1800_4025":"Failed to read the filament information.","1800_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1800_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1800_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1800_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1800_8007":"Extruding filament failed. The extruder might be clogged.","1800_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT A to the extruder is properly connected.","1800_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1800_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1800_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1800_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1800_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1800_8017":"AMS-HT A is drying. Please stop drying process before loading/unloading material.","1800_8021":"AMS setup failed; please refer to the assistant.","1800_8023":"AMS-HT A cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1800_C069":"An error occurred during AMS-HT A drying. Please go to Assistant for more details.","1800_C06A":"AMS-HT A is reading RFID. Unable to start drying. Please try again later.","1800_C06B":"AMS-HT A is changing filament. Unable to start drying. Please try again later.","1800_C06C":"AMS-HT A is in Feed Assist Mode. Unable to start drying. Please try again later.","1800_C06D":"AMS-HT A is assisting in filament insertion. Unable to start drying. Please try again later.","1800_C06E":"AMS-HT A motor is performing self-test. Unable to start drying. Please try again later.","1801_4025":"Failed to read the filament information.","1801_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1801_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1801_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1801_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1801_8007":"Extruding filament failed. The extruder might be clogged.","1801_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT B to the extruder is properly connected.","1801_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1801_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1801_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1801_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1801_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1801_8017":"AMS-HT B is drying. Please stop drying process before loading/unloading material.","1801_8021":"AMS setup failed; please refer to the assistant.","1801_8023":"AMS-HT B cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1801_C069":"An error occurred during AMS-HT B drying. Please go to Assistant for more details.","1801_C06A":"AMS-HT B is reading RFID. Unable to start drying. Please try again later.","1801_C06B":"AMS-HT B is changing filament. Unable to start drying. Please try again later.","1801_C06C":"AMS-HT B is in Feed Assist Mode. Unable to start drying. Please try again later.","1801_C06D":"AMS-HT B is assisting in filament insertion. Unable to start drying. Please try again later.","1801_C06E":"AMS-HT B motor is performing self-test. Unable to start drying. Please try again later.","1802_4025":"Failed to read the filament information.","1802_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1802_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1802_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1802_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1802_8007":"Extruding filament failed. The extruder might be clogged.","1802_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT C to the extruder is properly connected.","1802_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1802_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1802_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1802_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1802_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1802_8017":"AMS-HT C is drying. Please stop drying process before loading/unloading material.","1802_8021":"AMS setup failed; please refer to the assistant.","1802_8023":"AMS-HT C cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1802_C069":"An error occurred during AMS-HT C drying. Please go to Assistant for more details.","1802_C06A":"AMS-HT C is reading RFID. Unable to start drying. Please try again later.","1802_C06B":"AMS-HT C is changing filament. Unable to start drying. Please try again later.","1802_C06C":"AMS-HT C is in Feed Assist Mode. Unable to start drying. Please try again later.","1802_C06D":"AMS-HT C is assisting in filament insertion. Unable to start drying. Please try again later.","1802_C06E":"AMS-HT C motor is performing self-test. Unable to start drying. Please try again later.","1803_4025":"Failed to read the filament information.","1803_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1803_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1803_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1803_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1803_8007":"Extruding filament failed. The extruder might be clogged.","1803_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT D to the extruder is properly connected.","1803_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1803_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1803_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1803_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1803_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1803_8017":"AMS-HT D is drying. Please stop drying process before loading/unloading material.","1803_8021":"AMS setup failed; please refer to the assistant.","1803_8023":"AMS-HT D cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1803_C069":"An error occurred during AMS-HT D drying. Please go to Assistant for more details.","1803_C06A":"AMS-HT D is reading RFID. Unable to start drying. Please try again later.","1803_C06B":"AMS-HT D is changing filament. Unable to start drying. Please try again later.","1803_C06C":"AMS-HT D is in Feed Assist Mode. Unable to start drying. Please try again later.","1803_C06D":"AMS-HT D is assisting in filament insertion. Unable to start drying. Please try again later.","1803_C06E":"AMS-HT D motor is performing self-test. Unable to start drying. Please try again later.","1804_4025":"Failed to read the filament information.","1804_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1804_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1804_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1804_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1804_8007":"Extruding filament failed. The extruder might be clogged.","1804_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT E to the extruder is properly connected.","1804_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1804_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1804_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1804_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1804_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1804_8021":"AMS setup failed; please refer to the assistant.","1804_8023":"AMS-HT E cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1804_C069":"An error occurred during AMS-HT E drying. Please go to Assistant for more details.","1804_C06A":"AMS-HT E is reading RFID. Unable to start drying. Please try again later.","1804_C06B":"AMS-HT E is changing filament. Unable to start drying. Please try again later.","1804_C06C":"AMS-HT E is in Feed Assist Mode. Unable to start drying. Please try again later.","1804_C06D":"AMS-HT E is assisting in filament insertion. Unable to start drying. Please try again later.","1804_C06E":"AMS-HT E motor is performing self-test. Unable to start drying. Please try again later.","1805_4025":"Failed to read the filament information.","1805_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1805_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1805_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1805_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1805_8007":"Extruding filament failed. The extruder might be clogged.","1805_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT F to the extruder is properly connected.","1805_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1805_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1805_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1805_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1805_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1805_8021":"AMS setup failed; please refer to the assistant.","1805_8023":"AMS-HT F cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1805_C069":"An error occurred during AMS-HT F drying. Please go to Assistant for more details.","1805_C06A":"AMS-HT F is reading RFID. Unable to start drying. Please try again later.","1805_C06B":"AMS-HT F is changing filament. Unable to start drying. Please try again later.","1805_C06C":"AMS-HT F is in Feed Assist Mode. Unable to start drying. Please try again later.","1805_C06D":"AMS-HT F is assisting in filament insertion. Unable to start drying. Please try again later.","1805_C06E":"AMS-HT F motor is performing self-test. Unable to start drying. Please try again later.","1806_4025":"Failed to read the filament information.","1806_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1806_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1806_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1806_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1806_8007":"Extruding filament failed. The extruder might be clogged.","1806_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT G to the extruder is properly connected.","1806_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1806_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1806_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1806_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1806_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1806_8021":"AMS setup failed; please refer to the assistant.","1806_8023":"AMS-HT G cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1806_C069":"An error occurred during AMS-HT G drying. Please go to Assistant for more details.","1806_C06A":"AMS-HT G is reading RFID. Unable to start drying. Please try again later.","1806_C06B":"AMS-HT G is changing filament. Unable to start drying. Please try again later.","1806_C06C":"AMS-HT G is in Feed Assist Mode. Unable to start drying. Please try again later.","1806_C06D":"AMS-HT G is assisting in filament insertion. Unable to start drying. Please try again later.","1806_C06E":"AMS-HT G motor is performing self-test. Unable to start drying. Please try again later.","1807_4025":"Failed to read the filament information.","1807_8003":"Failed to pull out the filament from the extruder. This might be caused by clogged extruder or filament broken inside the extruder.","1807_8004":"AMS-HT failed to pull back filament. This could be due to a stuck spool or the end of the filament being stuck in the path.","1807_8005":"The AMS-HT failed to send out filament. You can clip the end of your filament flat, and reinsert. If this message persists, please check the PTFE tubes in AMS for any signs of wear and tear.","1807_8006":"Unable to feed filament into the extruder. The AMS may be mismatched with the extruder. You can rerun the AMS Setup. This could also be due to an entangled filament or a stuck spool. If not, please...","1807_8007":"Extruding filament failed. The extruder might be clogged.","1807_800A":"PTFE tube disconnection detected. Please check if the PTFE tube from AMS-HT H to the extruder is properly connected.","1807_8010":"The AMS-HT assist motor is overloaded. This could be due to entangled filament or a stuck spool.","1807_8011":"AMS-HT filament ran out. Please insert a new filament into the same AMS-HT slot.","1807_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","1807_8013":"Timeout purging old filament: Please check if the filament is stuck or the extruder is clogged.","1807_8016":"The extruder is not extruding normally; please refer to the Assistant. After trouble shooting. If the defects are acceptable, please resume.","1807_8021":"AMS setup failed; please refer to the assistant.","1807_8023":"AMS-HT H cooling failed. The ambient temperature may be too high. Please operate the device in a suitable environment.","1807_C069":"An error occurred during AMS-HT H drying. Please go to Assistant for more details.","1807_C06A":"AMS-HT H is reading RFID. Unable to start drying. Please try again later.","1807_C06B":"AMS-HT H is changing filament. Unable to start drying. Please try again later.","1807_C06C":"AMS-HT H is in Feed Assist Mode. Unable to start drying. Please try again later.","1807_C06D":"AMS-HT H is assisting in filament insertion. Unable to start drying. Please try again later.","1807_C06E":"AMS-HT H motor is performing self-test. Unable to start drying. Please try again later.","18FE_8001":"Failed to cut the filament of the left extruder. Please check the cutter.","18FE_8002":"The cutter of the left extruder is stuck. Please pull out the cutter handle.","18FE_8003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are ab...","18FE_8004":"Failed to pull back the filament from the left extruder. Please check whether the filament is stuck inside the extruder.","18FE_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FE_8006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_8007":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FE_8011":"The external filament connected to the left extruder has run out; please load a new filament.","18FE_8012":"Failed to get mapping table; please select 'Resume' to retry.","18FE_8013":"Timeout purging old filament of the left extruder: Please check if the filament is stuck or the extruder is clogged.","18FE_8020":"Extruder change failed; please refer to the assistant.","18FE_8021":"AMS setup failed; please refer to the assistant.","18FE_8024":"Extruder position calibration failed; please refer to the assistant.","18FE_C003":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C006":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C008":"Please pull out the filament on the spool holder of the left extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube i...","18FE_C009":"Please feed filament into the PTFE tube of the left extruder until it can not be pushed any farther.","18FE_C00A":"Please observe the nozzle of the left extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'.","18FF_8001":"Failed to cut the filament of the right extruder. Please check the cutter.","18FF_8002":"The cutter of the right extruder is stuck. Please pull out the cutter handle.","18FF_8003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder. (Connect a PTFE tube if you are a...","18FF_8004":"Failed to pull back the filament from the right extruder. Please check whether the filament is stuck inside the extruder.","18FF_8005":"Failed to feed the filament outside the AMS-HT. Please clip the end of the filament flat and check to see if the spool is stuck.","18FF_8006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_8007":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if it has not, please push the filament forward slightly, and then select 'Retry'.","18FF_8011":"The external filament connected to the right extruder has run out; please load a new filament.","18FF_8012":"Failed to get AMS mapping table; please select 'Resume' to retry.","18FF_8013":"Timeout purging old filament of the right extruder: Please check if the filament is stuck or the extruder is clogged.","18FF_8020":"Extruder change failed; please refer to the assistant.","18FF_8021":"AMS setup failed; please refer to the assistant.","18FF_8024":"Extruder position calibration failed; please refer to the assistant.","18FF_C003":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C006":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C008":"Please pull out the filament on the spool holder of the right extruder. If this message persists, please check to see if there is filament broken in the extruder or PTFE tube. (Connect a PTFE tube ...","18FF_C009":"Please feed filament into the PTFE tube of the right extruder until it can not be pushed any farther.","18FF_C00A":"Please observe the nozzle of the right extruder. If the filament has been extruded, select 'Continue'; if not, please push the filament forward slightly and then select 'Retry'."};function RTe(t){switch(t){case 1:return{label:"Fatal",color:"text-red-500",bgColor:"bg-red-500/20",Icon:Tn};case 2:return{label:"Serious",color:"text-red-400",bgColor:"bg-red-500/15",Icon:Tn};case 3:return{label:"Warning",color:"text-orange-400",bgColor:"bg-orange-500/20",Icon:Ba};default:return{label:"Info",color:"text-blue-400",bgColor:"bg-blue-500/20",Icon:Zs}}}function gD(t,e){const n=t>>16&65535||(t>>8&255)<<8|t&255,r=e&65535;return`${n.toString(16).padStart(4,"0").toUpperCase()}_${r.toString(16).padStart(4,"0").toUpperCase()}`}function FTe(t){return t.filter(e=>{const n=parseInt(e.code.replace("0x",""),16)||0,r=gD(e.attr,n);return pD[r]!==void 0})}function LTe(){return"https://wiki.bambulab.com/en/hms/home"}function OTe({printerName:t,errors:e,onClose:n,printerId:r,hasPermission:a}){const{t:s}=Ot(),{showToast:o}=an(),l=st({mutationFn:()=>ne.clearHMSErrors(r),onSuccess:()=>{o(s("hmsErrors.clearSuccess"),"success"),n()},onError:()=>{o(s("hmsErrors.clearFailed"),"error")}}),c=e.filter(u=>{const d=parseInt(u.code.replace("0x",""),16)||0,h=gD(u.attr,d);return pD[h]!==void 0});return w.useEffect(()=>{const u=d=>{d.key==="Escape"&&n()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Tn,{className:"w-5 h-5 text-orange-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:s("hmsErrors.title",{name:t})})]}),i.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:c.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Ba,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{children:s("hmsErrors.noErrors")})]}):i.jsx("div",{className:"space-y-3",children:c.map((u,d)=>{const{label:h,color:f,bgColor:p,Icon:x}=RTe(u.severity),v=parseInt(u.code.replace("0x",""),16)||0,g=gD(u.attr,v),y=pD[g],_=LTe(),N=g.replace("_","-");return i.jsx("div",{className:`p-4 rounded-lg ${p} border border-white/10`,children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(x,{className:`w-5 h-5 ${f} flex-shrink-0 mt-0.5`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsxs("span",{className:`font-mono text-sm ${f}`,children:["[",N,"]"]}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${p} ${f}`,children:h})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:y}),i.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-bambu-green hover:underline",children:[i.jsx(Xr,{className:"w-3 h-3"}),s("hmsErrors.viewOnWiki")]})]})]})},`${u.code}-${d}`)})})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:s("hmsErrors.clearInstructions")}),c.length>0&&i.jsxs("button",{onClick:()=>l.mutate(),disabled:!a("printers:control")||l.isPending,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex-shrink-0",children:[l.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),s("hmsErrors.clearErrors")]})]})]})})}function ITe({printerId:t,printerModel:e,printerState:n,plateCleared:r}){const{t:a}=Ot(),s=en(),{showToast:o}=an(),{hasPermission:l}=Ir(),{data:c}=Je({queryKey:["queue",t,"pending",e],queryFn:()=>ne.getQueue(t,"pending",e||void 0),refetchInterval:3e4}),u=st({mutationFn:()=>ne.clearPlate(t),onSuccess:()=>{s.invalidateQueries({queryKey:["queue",t]}),s.invalidateQueries({queryKey:["printerStatus",t]}),o(a("queue.clearPlateSuccess"),"success")},onError:p=>{o(p.message,"error")}}),d=c?.[0],h=c?.length||0;return h===0?null:(n==="FINISH"||n==="FAILED")&&!r?i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[i.jsx(ra,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:a("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:d?.archive_name||d?.library_file_name||`File #${d?.archive_id||d?.library_file_id}`})]}),h>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0",children:["+",h-1]})]}),u.isSuccess?i.jsxs("div",{className:"w-full py-2 px-3 rounded-lg bg-bambu-green/10 border border-bambu-green/20 text-bambu-green text-sm flex items-center justify-center gap-2",children:[i.jsx(ub,{className:"w-4 h-4"}),a("queue.plateReady")]}):i.jsxs("button",{onClick:()=>u.mutate(),disabled:u.isPending||!l("printers:clear_plate"),className:"w-full py-2 px-3 rounded-lg bg-bambu-green/20 border border-bambu-green/40 text-bambu-green hover:bg-bambu-green/30 transition-colors text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50",children:[u.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ub,{className:"w-4 h-4"}),a("queue.clearPlate")]})]}):i.jsx(Ks,{to:"/queue",className:"block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx(ra,{className:"w-5 h-5 text-yellow-400 flex-shrink-0"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:a("queue.nextInQueue")}),i.jsx("p",{className:"text-sm text-white truncate",children:d?.archive_name||d?.library_file_name||`File #${d?.archive_id||d?.library_file_id}`})]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),d?.scheduled_time?yv(d.scheduled_time,"system",a):a("time.waiting")]}),h>1&&i.jsxs("span",{className:"text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded",children:["+",h-1]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"})]})]})})}function tQ(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var a=t.length;for(e=0;e<a;e++)t[e]&&(n=tQ(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function ir(){for(var t,e,n=0,r="",a=arguments.length;n<a;n++)(t=arguments[n])&&(e=tQ(t))&&(r&&(r+=" "),r+=e);return r}var zTe=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"];function uL(t){if(typeof t!="string")return!1;var e=zTe;return e.includes(t)}var UTe=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],BTe=new Set(UTe);function nQ(t){return typeof t!="string"?!1:BTe.has(t)}function rQ(t){return typeof t=="string"&&t.startsWith("data-")}function Fs(t){if(typeof t!="object"||t===null)return{};var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(nQ(n)||rQ(n))&&(e[n]=t[n]);return e}function Uf(t){if(t==null)return null;if(w.isValidElement(t)&&typeof t.props=="object"&&t.props!==null){var e=t.props;return Fs(e)}return typeof t=="object"&&!Array.isArray(t)?Fs(t):null}function ts(t){var e={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(nQ(n)||rQ(n)||uL(n))&&(e[n]=t[n]);return e}function HTe(t){return t==null?null:w.isValidElement(t)?ts(t.props):typeof t=="object"&&!Array.isArray(t)?ts(t):null}var $Te=["children","width","height","viewBox","className","style","title","desc"];function bD(){return bD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},bD.apply(null,arguments)}function VTe(t,e){if(t==null)return{};var n,r,a=qTe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function qTe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var dL=w.forwardRef((t,e)=>{var{children:n,width:r,height:a,viewBox:s,className:o,style:l,title:c,desc:u}=t,d=VTe(t,$Te),h=s||{width:r,height:a,x:0,y:0},f=ir("recharts-surface",o);return w.createElement("svg",bD({},ts(d),{className:f,width:r,height:a,style:l,viewBox:"".concat(h.x," ").concat(h.y," ").concat(h.width," ").concat(h.height),ref:e}),w.createElement("title",null,c),w.createElement("desc",null,u),n)}),GTe=["children","className"];function xD(){return xD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},xD.apply(null,arguments)}function WTe(t,e){if(t==null)return{};var n,r,a=KTe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function KTe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var ga=w.forwardRef((t,e)=>{var{children:n,className:r}=t,a=WTe(t,GTe),s=ir("recharts-layer",r);return w.createElement("g",xD({className:s},ts(a),{ref:e}),n)}),aQ=w.createContext(null),XTe=()=>w.useContext(aQ);function Kr(t){return function(){return t}}const iQ=Math.cos,U1=Math.sin,ic=Math.sqrt,B1=Math.PI,mk=2*B1,yD=Math.PI,vD=2*yD,$m=1e-6,YTe=vD-$m;function sQ(t){this._+=t[0];for(let e=1,n=t.length;e<n;++e)this._+=arguments[e]+t[e]}function QTe(t){let e=Math.floor(t);if(!(e>=0))throw new Error(`invalid digits: ${t}`);if(e>15)return sQ;const n=10**e;return function(r){this._+=r[0];for(let a=1,s=r.length;a<s;++a)this._+=Math.round(arguments[a]*n)/n+r[a]}}class ZTe{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?sQ:QTe(e)}moveTo(e,n){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,n){this._append`L${this._x1=+e},${this._y1=+n}`}quadraticCurveTo(e,n,r,a){this._append`Q${+e},${+n},${this._x1=+r},${this._y1=+a}`}bezierCurveTo(e,n,r,a,s,o){this._append`C${+e},${+n},${+r},${+a},${this._x1=+s},${this._y1=+o}`}arcTo(e,n,r,a,s){if(e=+e,n=+n,r=+r,a=+a,s=+s,s<0)throw new Error(`negative radius: ${s}`);let o=this._x1,l=this._y1,c=r-e,u=a-n,d=o-e,h=l-n,f=d*d+h*h;if(this._x1===null)this._append`M${this._x1=e},${this._y1=n}`;else if(f>$m)if(!(Math.abs(h*c-u*d)>$m)||!s)this._append`L${this._x1=e},${this._y1=n}`;else{let p=r-o,x=a-l,v=c*c+u*u,g=p*p+x*x,y=Math.sqrt(v),_=Math.sqrt(f),N=s*Math.tan((yD-Math.acos((v+f-g)/(2*y*_)))/2),k=N/_,A=N/y;Math.abs(k-1)>$m&&this._append`L${e+k*d},${n+k*h}`,this._append`A${s},${s},0,0,${+(h*p>d*x)},${this._x1=e+A*c},${this._y1=n+A*u}`}}arc(e,n,r,a,s,o){if(e=+e,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(a),c=r*Math.sin(a),u=e+l,d=n+c,h=1^o,f=o?a-s:s-a;this._x1===null?this._append`M${u},${d}`:(Math.abs(this._x1-u)>$m||Math.abs(this._y1-d)>$m)&&this._append`L${u},${d}`,r&&(f<0&&(f=f%vD+vD),f>YTe?this._append`A${r},${r},0,1,${h},${e-l},${n-c}A${r},${r},0,1,${h},${this._x1=u},${this._y1=d}`:f>$m&&this._append`A${r},${r},0,${+(f>=yD)},${h},${this._x1=e+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(e,n,r,a){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function hL(t){let e=3;return t.digits=function(n){if(!arguments.length)return e;if(n==null)e=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);e=r}return t},()=>new ZTe(e)}function mL(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function oQ(t){this._context=t}oQ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function fk(t){return new oQ(t)}function lQ(t){return t[0]}function cQ(t){return t[1]}function uQ(t,e){var n=Kr(!0),r=null,a=fk,s=null,o=hL(l);t=typeof t=="function"?t:t===void 0?lQ:Kr(t),e=typeof e=="function"?e:e===void 0?cQ:Kr(e);function l(c){var u,d=(c=mL(c)).length,h,f=!1,p;for(r==null&&(s=a(p=o())),u=0;u<=d;++u)!(u<d&&n(h=c[u],u,c))===f&&((f=!f)?s.lineStart():s.lineEnd()),f&&s.point(+t(h,u,c),+e(h,u,c));if(p)return s=null,p+""||null}return l.x=function(c){return arguments.length?(t=typeof c=="function"?c:Kr(+c),l):t},l.y=function(c){return arguments.length?(e=typeof c=="function"?c:Kr(+c),l):e},l.defined=function(c){return arguments.length?(n=typeof c=="function"?c:Kr(!!c),l):n},l.curve=function(c){return arguments.length?(a=c,r!=null&&(s=a(r)),l):a},l.context=function(c){return arguments.length?(c==null?r=s=null:s=a(r=c),l):r},l}function i_(t,e,n){var r=null,a=Kr(!0),s=null,o=fk,l=null,c=hL(u);t=typeof t=="function"?t:t===void 0?lQ:Kr(+t),e=typeof e=="function"?e:Kr(e===void 0?0:+e),n=typeof n=="function"?n:n===void 0?cQ:Kr(+n);function u(h){var f,p,x,v=(h=mL(h)).length,g,y=!1,_,N=new Array(v),k=new Array(v);for(s==null&&(l=o(_=c())),f=0;f<=v;++f){if(!(f<v&&a(g=h[f],f,h))===y)if(y=!y)p=f,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),x=f-1;x>=p;--x)l.point(N[x],k[x]);l.lineEnd(),l.areaEnd()}y&&(N[f]=+t(g,f,h),k[f]=+e(g,f,h),l.point(r?+r(g,f,h):N[f],n?+n(g,f,h):k[f]))}if(_)return l=null,_+""||null}function d(){return uQ().defined(a).curve(o).context(s)}return u.x=function(h){return arguments.length?(t=typeof h=="function"?h:Kr(+h),r=null,u):t},u.x0=function(h){return arguments.length?(t=typeof h=="function"?h:Kr(+h),u):t},u.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Kr(+h),u):r},u.y=function(h){return arguments.length?(e=typeof h=="function"?h:Kr(+h),n=null,u):e},u.y0=function(h){return arguments.length?(e=typeof h=="function"?h:Kr(+h),u):e},u.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Kr(+h),u):n},u.lineX0=u.lineY0=function(){return d().x(t).y(e)},u.lineY1=function(){return d().x(t).y(n)},u.lineX1=function(){return d().x(r).y(e)},u.defined=function(h){return arguments.length?(a=typeof h=="function"?h:Kr(!!h),u):a},u.curve=function(h){return arguments.length?(o=h,s!=null&&(l=o(s)),u):o},u.context=function(h){return arguments.length?(h==null?s=l=null:l=o(s=h),u):s},u}class dQ{constructor(e,n){this._context=e,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,n){switch(e=+e,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,n):this._context.moveTo(e,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,n,e,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,e,this._y0,e,n);break}}this._x0=e,this._y0=n}}function JTe(t){return new dQ(t,!0)}function eMe(t){return new dQ(t,!1)}const fL={draw(t,e){const n=ic(e/B1);t.moveTo(n,0),t.arc(0,0,n,0,mk)}},tMe={draw(t,e){const n=ic(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}},hQ=ic(1/3),nMe=hQ*2,rMe={draw(t,e){const n=ic(e/nMe),r=n*hQ;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}},aMe={draw(t,e){const n=ic(e),r=-n/2;t.rect(r,r,n,n)}},iMe=.8908130915292852,mQ=U1(B1/10)/U1(7*B1/10),sMe=U1(mk/10)*mQ,oMe=-iQ(mk/10)*mQ,lMe={draw(t,e){const n=ic(e*iMe),r=sMe*n,a=oMe*n;t.moveTo(0,-n),t.lineTo(r,a);for(let s=1;s<5;++s){const o=mk*s/5,l=iQ(o),c=U1(o);t.lineTo(c*n,-l*n),t.lineTo(l*r-c*a,c*r+l*a)}t.closePath()}},lE=ic(3),cMe={draw(t,e){const n=-ic(e/(lE*3));t.moveTo(0,n*2),t.lineTo(-lE*n,-n),t.lineTo(lE*n,-n),t.closePath()}},Xo=-.5,Yo=ic(3)/2,wD=1/ic(12),uMe=(wD/2+1)*3,dMe={draw(t,e){const n=ic(e/uMe),r=n/2,a=n*wD,s=r,o=n*wD+n,l=-s,c=o;t.moveTo(r,a),t.lineTo(s,o),t.lineTo(l,c),t.lineTo(Xo*r-Yo*a,Yo*r+Xo*a),t.lineTo(Xo*s-Yo*o,Yo*s+Xo*o),t.lineTo(Xo*l-Yo*c,Yo*l+Xo*c),t.lineTo(Xo*r+Yo*a,Xo*a-Yo*r),t.lineTo(Xo*s+Yo*o,Xo*o-Yo*s),t.lineTo(Xo*l+Yo*c,Xo*c-Yo*l),t.closePath()}};function hMe(t,e){let n=null,r=hL(a);t=typeof t=="function"?t:Kr(t||fL),e=typeof e=="function"?e:Kr(e===void 0?64:+e);function a(){let s;if(n||(n=s=r()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),s)return n=null,s+""||null}return a.type=function(s){return arguments.length?(t=typeof s=="function"?s:Kr(s),a):t},a.size=function(s){return arguments.length?(e=typeof s=="function"?s:Kr(+s),a):e},a.context=function(s){return arguments.length?(n=s??null,a):n},a}function H1(){}function $1(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function fQ(t){this._context=t}fQ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:$1(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:$1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function mMe(t){return new fQ(t)}function pQ(t){this._context=t}pQ.prototype={areaStart:H1,areaEnd:H1,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:$1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function fMe(t){return new pQ(t)}function gQ(t){this._context=t}gQ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:$1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function pMe(t){return new gQ(t)}function bQ(t){this._context=t}bQ.prototype={areaStart:H1,areaEnd:H1,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function gMe(t){return new bQ(t)}function KH(t){return t<0?-1:1}function XH(t,e,n){var r=t._x1-t._x0,a=e-t._x1,s=(t._y1-t._y0)/(r||a<0&&-0),o=(n-t._y1)/(a||r<0&&-0),l=(s*a+o*r)/(r+a);return(KH(s)+KH(o))*Math.min(Math.abs(s),Math.abs(o),.5*Math.abs(l))||0}function YH(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function cE(t,e,n){var r=t._x0,a=t._y0,s=t._x1,o=t._y1,l=(s-r)/3;t._context.bezierCurveTo(r+l,a+l*e,s-l,o-l*n,s,o)}function V1(t){this._context=t}V1.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:cE(this,this._t0,YH(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var n=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,cE(this,YH(this,n=XH(this,t,e)),n);break;default:cE(this,this._t0,n=XH(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n}}};function xQ(t){this._context=new yQ(t)}(xQ.prototype=Object.create(V1.prototype)).point=function(t,e){V1.prototype.point.call(this,e,t)};function yQ(t){this._context=t}yQ.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,n,r,a,s){this._context.bezierCurveTo(e,t,r,n,s,a)}};function bMe(t){return new V1(t)}function xMe(t){return new xQ(t)}function vQ(t){this._context=t}vQ.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),n===2)this._context.lineTo(t[1],e[1]);else for(var r=QH(t),a=QH(e),s=0,o=1;o<n;++s,++o)this._context.bezierCurveTo(r[0][s],a[0][s],r[1][s],a[1][s],t[o],e[o]);(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(t,e){this._x.push(+t),this._y.push(+e)}};function QH(t){var e,n=t.length-1,r,a=new Array(n),s=new Array(n),o=new Array(n);for(a[0]=0,s[0]=2,o[0]=t[0]+2*t[1],e=1;e<n-1;++e)a[e]=1,s[e]=4,o[e]=4*t[e]+2*t[e+1];for(a[n-1]=2,s[n-1]=7,o[n-1]=8*t[n-1]+t[n],e=1;e<n;++e)r=a[e]/s[e-1],s[e]-=r,o[e]-=r*o[e-1];for(a[n-1]=o[n-1]/s[n-1],e=n-2;e>=0;--e)a[e]=(o[e]-a[e+1])/s[e];for(s[n-1]=(t[n]+a[n-1])/2,e=0;e<n-1;++e)s[e]=2*t[e+1]-a[e+1];return[a,s]}function yMe(t){return new vQ(t)}function pk(t,e){this._context=t,this._t=e}pk.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}break}}this._x=t,this._y=e}};function vMe(t){return new pk(t,.5)}function wMe(t){return new pk(t,0)}function SMe(t){return new pk(t,1)}function Bf(t,e){if((o=t.length)>1)for(var n=1,r,a,s=t[e[0]],o,l=s.length;n<o;++n)for(a=s,s=t[e[n]],r=0;r<l;++r)s[r][1]+=s[r][0]=isNaN(a[r][1])?a[r][0]:a[r][1]}function SD(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function _Me(t,e){return t[e]}function NMe(t){const e=[];return e.key=t,e}function CMe(){var t=Kr([]),e=SD,n=Bf,r=_Me;function a(s){var o=Array.from(t.apply(this,arguments),NMe),l,c=o.length,u=-1,d;for(const h of s)for(l=0,++u;l<c;++l)(o[l][u]=[0,+r(h,o[l].key,u,s)]).data=h;for(l=0,d=mL(e(o));l<c;++l)o[d[l]].index=l;return n(o,d),o}return a.keys=function(s){return arguments.length?(t=typeof s=="function"?s:Kr(Array.from(s)),a):t},a.value=function(s){return arguments.length?(r=typeof s=="function"?s:Kr(+s),a):r},a.order=function(s){return arguments.length?(e=s==null?SD:typeof s=="function"?s:Kr(Array.from(s)),a):e},a.offset=function(s){return arguments.length?(n=s??Bf,a):n},a}function kMe(t,e){if((r=t.length)>0){for(var n,r,a=0,s=t[0].length,o;a<s;++a){for(o=n=0;n<r;++n)o+=t[n][a][1]||0;if(o)for(n=0;n<r;++n)t[n][a][1]/=o}Bf(t,e)}}function AMe(t,e){if((a=t.length)>0){for(var n=0,r=t[e[0]],a,s=r.length;n<s;++n){for(var o=0,l=0;o<a;++o)l+=t[o][n][1]||0;r[n][1]+=r[n][0]=-l/2}Bf(t,e)}}function TMe(t,e){if(!(!((o=t.length)>0)||!((s=(a=t[e[0]]).length)>0))){for(var n=0,r=1,a,s,o;r<s;++r){for(var l=0,c=0,u=0;l<o;++l){for(var d=t[e[l]],h=d[r][1]||0,f=d[r-1][1]||0,p=(h-f)/2,x=0;x<l;++x){var v=t[e[x]],g=v[r][1]||0,y=v[r-1][1]||0;p+=g-y}c+=h,u+=p*h}a[r-1][1]+=a[r-1][0]=n,c&&(n-=u/c)}a[r-1][1]+=a[r-1][0]=n,Bf(t,e)}}var uE={},dE={},ZH;function MMe(){return ZH||(ZH=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==="__proto__"}t.isUnsafeProperty=e})(dE)),dE}var hE={},JH;function wQ(){return JH||(JH=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){switch(typeof n){case"number":case"symbol":return!1;case"string":return n.includes(".")||n.includes("[")||n.includes("]")}}t.isDeepKey=e})(hE)),hE}var mE={},e$;function pL(){return e$||(e$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="string"||typeof n=="symbol"?n:Object.is(n?.valueOf?.(),-0)?"-0":String(n)}t.toKey=e})(mE)),mE}var fE={},pE={},t$;function PMe(){return t$||(t$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(n==null)return"";if(typeof n=="string")return n;if(Array.isArray(n))return n.map(e).join(",");const r=String(n);return r==="0"&&Object.is(Number(n),-0)?"-0":r}t.toString=e})(pE)),pE}var n$;function gL(){return n$||(n$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=PMe(),n=pL();function r(a){if(Array.isArray(a))return a.map(n.toKey);if(typeof a=="symbol")return[a];a=e.toString(a);const s=[],o=a.length;if(o===0)return s;let l=0,c="",u="",d=!1;for(a.charCodeAt(0)===46&&(s.push(""),l++);l<o;){const h=a[l];u?h==="\\"&&l+1<o?(l++,c+=a[l]):h===u?u="":c+=h:d?h==='"'||h==="'"?u=h:h==="]"?(d=!1,s.push(c),c=""):c+=h:h==="["?(d=!0,c&&(s.push(c),c="")):h==="."?c&&(s.push(c),c=""):c+=h,l++}return c&&s.push(c),s}t.toPath=r})(fE)),fE}var r$;function bL(){return r$||(r$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=MMe(),n=wQ(),r=pL(),a=gL();function s(l,c,u){if(l==null)return u;switch(typeof c){case"string":{if(e.isUnsafeProperty(c))return u;const d=l[c];return d===void 0?n.isDeepKey(c)?s(l,a.toPath(c),u):u:d}case"number":case"symbol":{typeof c=="number"&&(c=r.toKey(c));const d=l[c];return d===void 0?u:d}default:{if(Array.isArray(c))return o(l,c,u);if(Object.is(c?.valueOf(),-0)?c="-0":c=String(c),e.isUnsafeProperty(c))return u;const d=l[c];return d===void 0?u:d}}}function o(l,c,u){if(c.length===0)return u;let d=l;for(let h=0;h<c.length;h++){if(d==null||e.isUnsafeProperty(c[h]))return u;d=d[c[h]]}return d===void 0?u:d}t.get=s})(uE)),uE}var gE,a$;function EMe(){return a$||(a$=1,gE=bL().get),gE}var jMe=EMe();const Hf=nc(jMe);var DMe=4;function _h(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:DMe,n=10**e,r=Math.round(t*n)/n;return Object.is(r,-0)?0:r}function Ta(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return t.reduce((a,s,o)=>{var l=n[o-1];return typeof l=="string"?a+l+s:l!==void 0?a+_h(l)+s:a+s},"")}var Ri=t=>t===0?0:t>0?1:-1,Jl=t=>typeof t=="number"&&t!=+t,$f=t=>typeof t=="string"&&t.indexOf("%")===t.length-1,qt=t=>(typeof t=="number"||t instanceof Number)&&!Jl(t),_l=t=>qt(t)||typeof t=="string",RMe=0,Pv=t=>{var e=++RMe;return"".concat(t||"").concat(e)},bs=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!qt(e)&&typeof e!="string")return r;var s;if($f(e)){if(n==null)return r;var o=e.indexOf("%");s=n*parseFloat(e.slice(0,o))/100}else s=+e;return Jl(s)&&(s=r),a&&n!=null&&s>n&&(s=n),s},SQ=t=>{if(!Array.isArray(t))return!1;for(var e=t.length,n={},r=0;r<e;r++)if(!n[String(t[r])])n[String(t[r])]=!0;else return!0;return!1};function br(t,e,n){return qt(t)&&qt(e)?_h(t+n*(e-t)):e}function _Q(t,e,n){if(!(!t||!t.length))return t.find(r=>r&&(typeof e=="function"?e(r):Hf(r,e))===n)}var ha=t=>t===null||typeof t>"u",y0=t=>ha(t)?t:"".concat(t.charAt(0).toUpperCase()).concat(t.slice(1));function Js(t){return t!=null}function em(){}var FMe=["type","size","sizeType"];function _D(){return _D=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},_D.apply(null,arguments)}function i$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function s$(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?i$(Object(n),!0).forEach(function(r){LMe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):i$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function LMe(t,e,n){return(e=OMe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function OMe(t){var e=IMe(t,"string");return typeof e=="symbol"?e:e+""}function IMe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zMe(t,e){if(t==null)return{};var n,r,a=UMe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function UMe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var NQ={symbolCircle:fL,symbolCross:tMe,symbolDiamond:rMe,symbolSquare:aMe,symbolStar:lMe,symbolTriangle:cMe,symbolWye:dMe},BMe=Math.PI/180,HMe=t=>{var e="symbol".concat(y0(t));return NQ[e]||fL},$Me=(t,e,n)=>{if(e==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var r=18*BMe;return 1.25*t*t*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},VMe=(t,e)=>{NQ["symbol".concat(y0(t))]=e},xL=t=>{var{type:e="circle",size:n=64,sizeType:r="area"}=t,a=zMe(t,FMe),s=s$(s$({},a),{},{type:e,size:n,sizeType:r}),o="circle";typeof e=="string"&&(o=e);var l=()=>{var f=HMe(o),p=hMe().type(f).size($Me(n,r,o)),x=p();if(x!==null)return x},{className:c,cx:u,cy:d}=s,h=ts(s);return qt(u)&&qt(d)&&qt(n)?w.createElement("path",_D({},h,{className:ir("recharts-symbols",c),transform:"translate(".concat(u,", ").concat(d,")"),d:l()})):null};xL.registerSymbol=VMe;var CQ=t=>"radius"in t&&"startAngle"in t&&"endAngle"in t,yL=(t,e)=>{if(!t||typeof t=="function"||typeof t=="boolean")return null;var n=t;if(w.isValidElement(t)&&(n=t.props),typeof n!="object"&&typeof n!="function")return null;var r={};return Object.keys(n).forEach(a=>{uL(a)&&(r[a]=(s=>n[a](n,s)))}),r},qMe=(t,e,n)=>r=>(t(e,n,r),null),v0=(t,e,n)=>{if(t===null||typeof t!="object"&&typeof t!="function")return null;var r=null;return Object.keys(t).forEach(a=>{var s=t[a];uL(a)&&typeof s=="function"&&(r||(r={}),r[a]=qMe(s,e,n))}),r};function o$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function GMe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?o$(Object(n),!0).forEach(function(r){WMe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):o$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function WMe(t,e,n){return(e=KMe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function KMe(t){var e=XMe(t,"string");return typeof e=="symbol"?e:e+""}function XMe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ba(t,e){var n=GMe({},t),r=e,a=Object.keys(e),s=a.reduce((o,l)=>(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return s}function q1(){return q1=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},q1.apply(null,arguments)}function l$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function YMe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?l$(Object(n),!0).forEach(function(r){QMe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):l$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function QMe(t,e,n){return(e=ZMe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ZMe(t){var e=JMe(t,"string");return typeof e=="symbol"?e:e+""}function JMe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Jo=32,ePe={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle"};function tPe(t){var{data:e,iconType:n,inactiveColor:r}=t,a=Jo/2,s=Jo/6,o=Jo/3,l=e.inactive?r:e.color,c=n??e.type;if(c==="none")return null;if(c==="plainline"){var u;return w.createElement("line",{strokeWidth:4,fill:"none",stroke:l,strokeDasharray:(u=e.payload)===null||u===void 0?void 0:u.strokeDasharray,x1:0,y1:a,x2:Jo,y2:a,className:"recharts-legend-icon"})}if(c==="line")return w.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(a,"h").concat(o,`
  8068. A`).concat(s,",").concat(s,",0,1,1,").concat(2*o,",").concat(a,`
  8069. H`).concat(Jo,"M").concat(2*o,",").concat(a,`
  8070. A`).concat(s,",").concat(s,",0,1,1,").concat(o,",").concat(a),className:"recharts-legend-icon"});if(c==="rect")return w.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Jo/8,"h").concat(Jo,"v").concat(Jo*3/4,"h").concat(-Jo,"z"),className:"recharts-legend-icon"});if(w.isValidElement(e.legendIcon)){var d=YMe({},e);return delete d.legendIcon,w.cloneElement(e.legendIcon,d)}return w.createElement(xL,{fill:l,cx:a,cy:a,size:Jo,sizeType:"diameter",type:c})}function nPe(t){var{payload:e,iconSize:n,layout:r,formatter:a,inactiveColor:s,iconType:o}=t,l={x:0,y:0,width:Jo,height:Jo},c={display:r==="horizontal"?"inline-block":"block",marginRight:10},u={display:"inline-block",verticalAlign:"middle",marginRight:4};return e.map((d,h)=>{var f=d.formatter||a,p=ir({"recharts-legend-item":!0,["legend-item-".concat(h)]:!0,inactive:d.inactive});if(d.type==="none")return null;var x=d.inactive?s:d.color,v=f?f(d.value,d,h):d.value;return w.createElement("li",q1({className:p,style:c,key:"legend-item-".concat(h)},v0(t,d,h)),w.createElement(dL,{width:n,height:n,viewBox:l,style:u,"aria-label":"".concat(v," legend icon")},w.createElement(tPe,{data:d,iconType:o,inactiveColor:s})),w.createElement("span",{className:"recharts-legend-item-text",style:{color:x}},v))})}var rPe=t=>{var e=ba(t,ePe),{payload:n,layout:r,align:a}=e;if(!n||!n.length)return null;var s={padding:0,margin:0,textAlign:r==="horizontal"?a:"left"};return w.createElement("ul",{className:"recharts-default-legend",style:s},w.createElement(nPe,q1({},e,{payload:n})))},bE={},xE={},c$;function aPe(){return c$||(c$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){const a=new Map;for(let s=0;s<n.length;s++){const o=n[s],l=r(o,s,n);a.has(l)||a.set(l,o)}return Array.from(a.values())}t.uniqBy=e})(xE)),xE}var yE={},u$;function iPe(){return u$||(u$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return function(...a){return n.apply(this,a.slice(0,r))}}t.ary=e})(yE)),yE}var vE={},d$;function kQ(){return d$||(d$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n}t.identity=e})(vE)),vE}var wE={},SE={},_E={},h$;function sPe(){return h$||(h$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Number.isSafeInteger(n)&&n>=0}t.isLength=e})(_E)),_E}var m$;function vL(){return m$||(m$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=sPe();function n(r){return r!=null&&typeof r!="function"&&e.isLength(r.length)}t.isArrayLike=n})(SE)),SE}var NE={},f$;function oPe(){return f$||(f$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="object"&&n!==null}t.isObjectLike=e})(NE)),NE}var p$;function lPe(){return p$||(p$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=vL(),n=oPe();function r(a){return n.isObjectLike(a)&&e.isArrayLike(a)}t.isArrayLikeObject=r})(wE)),wE}var CE={},kE={},g$;function cPe(){return g$||(g$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=bL();function n(r){return function(a){return e.get(a,r)}}t.property=n})(kE)),kE}var AE={},TE={},ME={},PE={},b$;function AQ(){return b$||(b$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n!==null&&(typeof n=="object"||typeof n=="function")}t.isObject=e})(PE)),PE}var EE={},x$;function TQ(){return x$||(x$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null||typeof n!="object"&&typeof n!="function"}t.isPrimitive=e})(EE)),EE}var jE={},y$;function MQ(){return y$||(y$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}t.isEqualsSameValueZero=e})(jE)),jE}var v$;function uPe(){return v$||(v$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=AQ(),n=TQ(),r=MQ();function a(d,h,f){return typeof f!="function"?a(d,h,()=>{}):s(d,h,function p(x,v,g,y,_,N){const k=f(x,v,g,y,_,N);return k!==void 0?!!k:s(x,v,p,N)},new Map)}function s(d,h,f,p){if(h===d)return!0;switch(typeof h){case"object":return o(d,h,f,p);case"function":return Object.keys(h).length>0?s(d,{...h},f,p):r.isEqualsSameValueZero(d,h);default:return e.isObject(d)?typeof h=="string"?h==="":!0:r.isEqualsSameValueZero(d,h)}}function o(d,h,f,p){if(h==null)return!0;if(Array.isArray(h))return c(d,h,f,p);if(h instanceof Map)return l(d,h,f,p);if(h instanceof Set)return u(d,h,f,p);const x=Object.keys(h);if(d==null||n.isPrimitive(d))return x.length===0;if(x.length===0)return!0;if(p?.has(h))return p.get(h)===d;p?.set(h,d);try{for(let v=0;v<x.length;v++){const g=x[v];if(!n.isPrimitive(d)&&!(g in d)||h[g]===void 0&&d[g]!==void 0||h[g]===null&&d[g]!==null||!f(d[g],h[g],g,d,h,p))return!1}return!0}finally{p?.delete(h)}}function l(d,h,f,p){if(h.size===0)return!0;if(!(d instanceof Map))return!1;for(const[x,v]of h.entries()){const g=d.get(x);if(f(g,v,x,d,h,p)===!1)return!1}return!0}function c(d,h,f,p){if(h.length===0)return!0;if(!Array.isArray(d))return!1;const x=new Set;for(let v=0;v<h.length;v++){const g=h[v];let y=!1;for(let _=0;_<d.length;_++){if(x.has(_))continue;const N=d[_];let k=!1;if(f(N,g,v,d,h,p)&&(k=!0),k){x.add(_),y=!0;break}}if(!y)return!1}return!0}function u(d,h,f,p){return h.size===0?!0:d instanceof Set?c([...d],[...h],f,p):!1}t.isMatchWith=a,t.isSetMatch=u})(ME)),ME}var w$;function PQ(){return w$||(w$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=uPe();function n(r,a){return e.isMatchWith(r,a,()=>{})}t.isMatch=n})(TE)),TE}var DE={},RE={},FE={},S$;function dPe(){return S$||(S$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Object.getOwnPropertySymbols(n).filter(r=>Object.prototype.propertyIsEnumerable.call(n,r))}t.getSymbols=e})(FE)),FE}var LE={},_$;function wL(){return _$||(_$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}t.getTag=e})(LE)),LE}var OE={},N$;function EQ(){return N$||(N$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e="[object RegExp]",n="[object String]",r="[object Number]",a="[object Boolean]",s="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",u="[object Set]",d="[object Array]",h="[object Function]",f="[object ArrayBuffer]",p="[object Object]",x="[object Error]",v="[object DataView]",g="[object Uint8Array]",y="[object Uint8ClampedArray]",_="[object Uint16Array]",N="[object Uint32Array]",k="[object BigUint64Array]",A="[object Int8Array]",M="[object Int16Array]",C="[object Int32Array]",j="[object BigInt64Array]",P="[object Float32Array]",E="[object Float64Array]";t.argumentsTag=s,t.arrayBufferTag=f,t.arrayTag=d,t.bigInt64ArrayTag=j,t.bigUint64ArrayTag=k,t.booleanTag=a,t.dataViewTag=v,t.dateTag=l,t.errorTag=x,t.float32ArrayTag=P,t.float64ArrayTag=E,t.functionTag=h,t.int16ArrayTag=M,t.int32ArrayTag=C,t.int8ArrayTag=A,t.mapTag=c,t.numberTag=r,t.objectTag=p,t.regexpTag=e,t.setTag=u,t.stringTag=n,t.symbolTag=o,t.uint16ArrayTag=_,t.uint32ArrayTag=N,t.uint8ArrayTag=g,t.uint8ClampedArrayTag=y})(OE)),OE}var IE={},C$;function hPe(){return C$||(C$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}t.isTypedArray=e})(IE)),IE}var k$;function jQ(){return k$||(k$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=dPe(),n=wL(),r=EQ(),a=TQ(),s=hPe();function o(d,h){return l(d,void 0,d,new Map,h)}function l(d,h,f,p=new Map,x=void 0){const v=x?.(d,h,f,p);if(v!==void 0)return v;if(a.isPrimitive(d))return d;if(p.has(d))return p.get(d);if(Array.isArray(d)){const g=new Array(d.length);p.set(d,g);for(let y=0;y<d.length;y++)g[y]=l(d[y],y,f,p,x);return Object.hasOwn(d,"index")&&(g.index=d.index),Object.hasOwn(d,"input")&&(g.input=d.input),g}if(d instanceof Date)return new Date(d.getTime());if(d instanceof RegExp){const g=new RegExp(d.source,d.flags);return g.lastIndex=d.lastIndex,g}if(d instanceof Map){const g=new Map;p.set(d,g);for(const[y,_]of d)g.set(y,l(_,y,f,p,x));return g}if(d instanceof Set){const g=new Set;p.set(d,g);for(const y of d)g.add(l(y,void 0,f,p,x));return g}if(typeof Buffer<"u"&&Buffer.isBuffer(d))return d.subarray();if(s.isTypedArray(d)){const g=new(Object.getPrototypeOf(d)).constructor(d.length);p.set(d,g);for(let y=0;y<d.length;y++)g[y]=l(d[y],y,f,p,x);return g}if(d instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&d instanceof SharedArrayBuffer)return d.slice(0);if(d instanceof DataView){const g=new DataView(d.buffer.slice(0),d.byteOffset,d.byteLength);return p.set(d,g),c(g,d,f,p,x),g}if(typeof File<"u"&&d instanceof File){const g=new File([d],d.name,{type:d.type});return p.set(d,g),c(g,d,f,p,x),g}if(typeof Blob<"u"&&d instanceof Blob){const g=new Blob([d],{type:d.type});return p.set(d,g),c(g,d,f,p,x),g}if(d instanceof Error){const g=new d.constructor;return p.set(d,g),g.message=d.message,g.name=d.name,g.stack=d.stack,g.cause=d.cause,c(g,d,f,p,x),g}if(d instanceof Boolean){const g=new Boolean(d.valueOf());return p.set(d,g),c(g,d,f,p,x),g}if(d instanceof Number){const g=new Number(d.valueOf());return p.set(d,g),c(g,d,f,p,x),g}if(d instanceof String){const g=new String(d.valueOf());return p.set(d,g),c(g,d,f,p,x),g}if(typeof d=="object"&&u(d)){const g=Object.create(Object.getPrototypeOf(d));return p.set(d,g),c(g,d,f,p,x),g}return d}function c(d,h,f=d,p,x){const v=[...Object.keys(h),...e.getSymbols(h)];for(let g=0;g<v.length;g++){const y=v[g],_=Object.getOwnPropertyDescriptor(d,y);(_==null||_.writable)&&(d[y]=l(h[y],y,f,p,x))}}function u(d){switch(n.getTag(d)){case r.argumentsTag:case r.arrayTag:case r.arrayBufferTag:case r.dataViewTag:case r.booleanTag:case r.dateTag:case r.float32ArrayTag:case r.float64ArrayTag:case r.int8ArrayTag:case r.int16ArrayTag:case r.int32ArrayTag:case r.mapTag:case r.numberTag:case r.objectTag:case r.regexpTag:case r.setTag:case r.stringTag:case r.symbolTag:case r.uint8ArrayTag:case r.uint8ClampedArrayTag:case r.uint16ArrayTag:case r.uint32ArrayTag:return!0;default:return!1}}t.cloneDeepWith=o,t.cloneDeepWithImpl=l,t.copyProperties=c})(RE)),RE}var A$;function mPe(){return A$||(A$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=jQ();function n(r){return e.cloneDeepWithImpl(r,void 0,r,new Map,void 0)}t.cloneDeep=n})(DE)),DE}var T$;function fPe(){return T$||(T$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=PQ(),n=mPe();function r(a){return a=n.cloneDeep(a),s=>e.isMatch(s,a)}t.matches=r})(AE)),AE}var zE={},UE={},BE={},M$;function pPe(){return M$||(M$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=jQ(),n=wL(),r=EQ();function a(s,o){return e.cloneDeepWith(s,(l,c,u,d)=>{const h=o?.(l,c,u,d);if(h!==void 0)return h;if(typeof s=="object"){if(n.getTag(s)===r.objectTag&&typeof s.constructor!="function"){const f={};return d.set(s,f),e.copyProperties(f,s,u,d),f}switch(Object.prototype.toString.call(s)){case r.numberTag:case r.stringTag:case r.booleanTag:{const f=new s.constructor(s?.valueOf());return e.copyProperties(f,s),f}case r.argumentsTag:{const f={};return e.copyProperties(f,s),f.length=s.length,f[Symbol.iterator]=s[Symbol.iterator],f}default:return}}})}t.cloneDeepWith=a})(BE)),BE}var P$;function gPe(){return P$||(P$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=pPe();function n(r){return e.cloneDeepWith(r)}t.cloneDeep=n})(UE)),UE}var HE={},$E={},E$;function DQ(){return E$||(E$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=/^(?:0|[1-9]\d*)$/;function n(r,a=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&r<a;case"symbol":return!1;case"string":return e.test(r)}}t.isIndex=n})($E)),$E}var VE={},j$;function bPe(){return j$||(j$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=wL();function n(r){return r!==null&&typeof r=="object"&&e.getTag(r)==="[object Arguments]"}t.isArguments=n})(VE)),VE}var D$;function xPe(){return D$||(D$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=wQ(),n=DQ(),r=bPe(),a=gL();function s(o,l){let c;if(Array.isArray(l)?c=l:typeof l=="string"&&e.isDeepKey(l)&&o?.[l]==null?c=a.toPath(l):c=[l],c.length===0)return!1;let u=o;for(let d=0;d<c.length;d++){const h=c[d];if((u==null||!Object.hasOwn(u,h))&&!((Array.isArray(u)||r.isArguments(u))&&n.isIndex(h)&&h<u.length))return!1;u=u[h]}return!0}t.has=s})(HE)),HE}var R$;function yPe(){return R$||(R$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=PQ(),n=pL(),r=gPe(),a=bL(),s=xPe();function o(l,c){switch(typeof l){case"object":{Object.is(l?.valueOf(),-0)&&(l="-0");break}case"number":{l=n.toKey(l);break}}return c=r.cloneDeep(c),function(u){const d=a.get(u,l);return d===void 0?s.has(u,l):c===void 0?d===void 0:e.isMatch(d,c)}}t.matchesProperty=o})(zE)),zE}var F$;function vPe(){return F$||(F$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=kQ(),n=cPe(),r=fPe(),a=yPe();function s(o){if(o==null)return e.identity;switch(typeof o){case"function":return o;case"object":return Array.isArray(o)&&o.length===2?a.matchesProperty(o[0],o[1]):r.matches(o);case"string":case"symbol":case"number":return n.property(o)}}t.iteratee=s})(CE)),CE}var L$;function wPe(){return L$||(L$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=aPe(),n=iPe(),r=kQ(),a=lPe(),s=vPe();function o(l,c=r.identity){return a.isArrayLikeObject(l)?e.uniqBy(Array.from(l),n.ary(s.iteratee(c),1)):[]}t.uniqBy=o})(bE)),bE}var qE,O$;function SPe(){return O$||(O$=1,qE=wPe().uniqBy),qE}var _Pe=SPe();const I$=nc(_Pe);function RQ(t,e,n){return e===!0?I$(t,n):typeof e=="function"?I$(t,e):t}var GE={exports:{}},WE={};var z$;function NPe(){if(z$)return WE;z$=1;var t=zb(),e=_K();function n(u,d){return u===d&&(u!==0||1/u===1/d)||u!==u&&d!==d}var r=typeof Object.is=="function"?Object.is:n,a=e.useSyncExternalStore,s=t.useRef,o=t.useEffect,l=t.useMemo,c=t.useDebugValue;return WE.useSyncExternalStoreWithSelector=function(u,d,h,f,p){var x=s(null);if(x.current===null){var v={hasValue:!1,value:null};x.current=v}else v=x.current;x=l(function(){function y(M){if(!_){if(_=!0,N=M,M=f(M),p!==void 0&&v.hasValue){var C=v.value;if(p(C,M))return k=C}return k=M}if(C=k,r(N,M))return C;var j=f(M);return p!==void 0&&p(C,j)?(N=M,C):(N=M,k=j)}var _=!1,N,k,A=h===void 0?null:h;return[function(){return y(d())},A===null?void 0:function(){return y(A())}]},[d,h,f,p]);var g=a(u,x[0],x[1]);return o(function(){v.hasValue=!0,v.value=g},[g]),c(g),g},WE}var U$;function CPe(){return U$||(U$=1,GE.exports=NPe()),GE.exports}var FQ=CPe(),SL=w.createContext(null),kPe=t=>t,qr=()=>{var t=w.useContext(SL);return t?t.store.dispatch:kPe},J_=()=>{},APe=()=>J_,TPe=(t,e)=>t===e;function Kt(t){var e=w.useContext(SL),n=w.useMemo(()=>e?r=>{if(r!=null)return t(r)}:J_,[e,t]);return FQ.useSyncExternalStoreWithSelector(e?e.subscription.addNestedSub:APe,e?e.store.getState:J_,e?e.store.getState:J_,n,TPe)}function MPe(t,e=`expected a function, instead received ${typeof t}`){if(typeof t!="function")throw new TypeError(e)}function PPe(t,e=`expected an object, instead received ${typeof t}`){if(typeof t!="object")throw new TypeError(e)}function EPe(t,e="expected all items to be functions, instead received the following types: "){if(!t.every(n=>typeof n=="function")){const n=t.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${e}[${n}]`)}}var B$=t=>Array.isArray(t)?t:[t];function jPe(t){const e=Array.isArray(t[0])?t[0]:t;return EPe(e,"createSelector expects all input-selectors to be functions, but received the following types: "),e}function DPe(t,e){const n=[],{length:r}=t;for(let a=0;a<r;a++)n.push(t[a].apply(null,e));return n}var RPe=class{constructor(t){this.value=t}deref(){return this.value}},FPe=typeof WeakRef<"u"?WeakRef:RPe,LPe=0,H$=1;function s_(){return{s:LPe,v:void 0,o:null,p:null}}function LQ(t,e={}){let n=s_();const{resultEqualityCheck:r}=e;let a,s=0;function o(){let l=n;const{length:c}=arguments;for(let h=0,f=c;h<f;h++){const p=arguments[h];if(typeof p=="function"||typeof p=="object"&&p!==null){let x=l.o;x===null&&(l.o=x=new WeakMap);const v=x.get(p);v===void 0?(l=s_(),x.set(p,l)):l=v}else{let x=l.p;x===null&&(l.p=x=new Map);const v=x.get(p);v===void 0?(l=s_(),x.set(p,l)):l=v}}const u=l;let d;if(l.s===H$)d=l.v;else if(d=t.apply(null,arguments),s++,r){const h=a?.deref?.()??a;h!=null&&r(h,d)&&(d=h,s!==0&&s--),a=typeof d=="object"&&d!==null||typeof d=="function"?new FPe(d):d}return u.s=H$,u.v=d,d}return o.clearCache=()=>{n=s_(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function OPe(t,...e){const n=typeof t=="function"?{memoize:t,memoizeOptions:e}:t,r=(...a)=>{let s=0,o=0,l,c={},u=a.pop();typeof u=="object"&&(c=u,u=a.pop()),MPe(u,`createSelector expects an output function after the inputs, but received: [${typeof u}]`);const d={...n,...c},{memoize:h,memoizeOptions:f=[],argsMemoize:p=LQ,argsMemoizeOptions:x=[]}=d,v=B$(f),g=B$(x),y=jPe(a),_=h(function(){return s++,u.apply(null,arguments)},...v),N=p(function(){o++;const A=DPe(y,arguments);return l=_.apply(null,A),l},...g);return Object.assign(N,{resultFunc:u,memoizedResultFunc:_,dependencies:y,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>s,resetRecomputations:()=>{s=0},memoize:h,argsMemoize:p})};return Object.assign(r,{withTypes:()=>r}),r}var ct=OPe(LQ),IPe=Object.assign((t,e=ct)=>{PPe(t,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof t}`);const n=Object.keys(t),r=n.map(s=>t[s]);return e(r,(...s)=>s.reduce((o,l,c)=>(o[n[c]]=l,o),{}))},{withTypes:()=>IPe}),KE={},XE={},YE={},$$;function zPe(){return $$||($$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(r){return typeof r=="symbol"?1:r===null?2:r===void 0?3:r!==r?4:0}const n=(r,a,s)=>{if(r!==a){const o=e(r),l=e(a);if(o===l&&o===0){if(r<a)return s==="desc"?1:-1;if(r>a)return s==="desc"?-1:1}return s==="desc"?l-o:o-l}return 0};t.compareValues=n})(YE)),YE}var QE={},ZE={},V$;function OQ(){return V$||(V$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return typeof n=="symbol"||n instanceof Symbol}t.isSymbol=e})(ZE)),ZE}var q$;function UPe(){return q$||(q$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=OQ(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function a(s,o){return Array.isArray(s)?!1:typeof s=="number"||typeof s=="boolean"||s==null||e.isSymbol(s)?!0:typeof s=="string"&&(r.test(s)||!n.test(s))||o!=null&&Object.hasOwn(o,s)}t.isKey=a})(QE)),QE}var G$;function BPe(){return G$||(G$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=zPe(),n=UPe(),r=gL();function a(s,o,l,c){if(s==null)return[];l=c?void 0:l,Array.isArray(s)||(s=Object.values(s)),Array.isArray(o)||(o=o==null?[null]:[o]),o.length===0&&(o=[null]),Array.isArray(l)||(l=l==null?[]:[l]),l=l.map(p=>String(p));const u=(p,x)=>{let v=p;for(let g=0;g<x.length&&v!=null;++g)v=v[x[g]];return v},d=(p,x)=>x==null||p==null?x:typeof p=="object"&&"key"in p?Object.hasOwn(x,p.key)?x[p.key]:u(x,p.path):typeof p=="function"?p(x):Array.isArray(p)?u(x,p):typeof x=="object"?x[p]:x,h=o.map(p=>(Array.isArray(p)&&p.length===1&&(p=p[0]),p==null||typeof p=="function"||Array.isArray(p)||n.isKey(p)?p:{key:p,path:r.toPath(p)}));return s.map(p=>({original:p,criteria:h.map(x=>d(x,p))})).slice().sort((p,x)=>{for(let v=0;v<h.length;v++){const g=e.compareValues(p.criteria[v],x.criteria[v],l[v]);if(g!==0)return g}return 0}).map(p=>p.original)}t.orderBy=a})(XE)),XE}var JE={},W$;function HPe(){return W$||(W$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r=1){const a=[],s=Math.floor(r),o=(l,c)=>{for(let u=0;u<l.length;u++){const d=l[u];Array.isArray(d)&&c<s?o(d,c+1):a.push(d)}};return o(n,0),a}t.flatten=e})(JE)),JE}var ej={},K$;function IQ(){return K$||(K$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=DQ(),n=vL(),r=AQ(),a=MQ();function s(o,l,c){return r.isObject(c)&&(typeof l=="number"&&n.isArrayLike(c)&&e.isIndex(l)&&l<c.length||typeof l=="string"&&l in c)?a.isEqualsSameValueZero(c[l],o):!1}t.isIterateeCall=s})(ej)),ej}var X$;function $Pe(){return X$||(X$=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=BPe(),n=HPe(),r=IQ();function a(s,...o){const l=o.length;return l>1&&r.isIterateeCall(s,o[0],o[1])?o=[]:l>2&&r.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),e.orderBy(s,n.flatten(o),["asc"])}t.sortBy=a})(KE)),KE}var tj,Y$;function VPe(){return Y$||(Y$=1,tj=$Pe().sortBy),tj}var qPe=VPe();const gk=nc(qPe);var zQ=t=>t.legend.settings,GPe=t=>t.legend.size,WPe=t=>t.legend.payload,KPe=ct([WPe,zQ],(t,e)=>{var{itemSorter:n}=e,r=t.flat(1);return n?gk(r,n):r});function XPe(){return Kt(KPe)}var o_=1;function UQ(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],[e,n]=w.useState({height:0,left:0,top:0,width:0}),r=w.useCallback(a=>{if(a!=null){var s=a.getBoundingClientRect(),o={height:s.height,left:s.left,top:s.top,width:s.width};(Math.abs(o.height-e.height)>o_||Math.abs(o.left-e.left)>o_||Math.abs(o.top-e.top)>o_||Math.abs(o.width-e.width)>o_)&&n({height:o.height,left:o.left,top:o.top,width:o.width})}},[e.width,e.height,e.top,e.left,...t]);return[e,r]}function Gi(t){return`Minified Redux error #${t}; visit https://redux.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var YPe=typeof Symbol=="function"&&Symbol.observable||"@@observable",Q$=YPe,nj=()=>Math.random().toString(36).substring(7).split("").join("."),QPe={INIT:`@@redux/INIT${nj()}`,REPLACE:`@@redux/REPLACE${nj()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${nj()}`},G1=QPe;function _L(t){if(typeof t!="object"||t===null)return!1;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e||Object.getPrototypeOf(t)===null}function BQ(t,e,n){if(typeof t!="function")throw new Error(Gi(2));if(typeof e=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Gi(0));if(typeof e=="function"&&typeof n>"u"&&(n=e,e=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Gi(1));return n(BQ)(t,e)}let r=t,a=e,s=new Map,o=s,l=0,c=!1;function u(){o===s&&(o=new Map,s.forEach((g,y)=>{o.set(y,g)}))}function d(){if(c)throw new Error(Gi(3));return a}function h(g){if(typeof g!="function")throw new Error(Gi(4));if(c)throw new Error(Gi(5));let y=!0;u();const _=l++;return o.set(_,g),function(){if(y){if(c)throw new Error(Gi(6));y=!1,u(),o.delete(_),s=null}}}function f(g){if(!_L(g))throw new Error(Gi(7));if(typeof g.type>"u")throw new Error(Gi(8));if(typeof g.type!="string")throw new Error(Gi(17));if(c)throw new Error(Gi(9));try{c=!0,a=r(a,g)}finally{c=!1}return(s=o).forEach(_=>{_()}),g}function p(g){if(typeof g!="function")throw new Error(Gi(10));r=g,f({type:G1.REPLACE})}function x(){const g=h;return{subscribe(y){if(typeof y!="object"||y===null)throw new Error(Gi(11));function _(){const k=y;k.next&&k.next(d())}return _(),{unsubscribe:g(_)}},[Q$](){return this}}}return f({type:G1.INIT}),{dispatch:f,subscribe:h,getState:d,replaceReducer:p,[Q$]:x}}function ZPe(t){Object.keys(t).forEach(e=>{const n=t[e];if(typeof n(void 0,{type:G1.INIT})>"u")throw new Error(Gi(12));if(typeof n(void 0,{type:G1.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Gi(13))})}function HQ(t){const e=Object.keys(t),n={};for(let s=0;s<e.length;s++){const o=e[s];typeof t[o]=="function"&&(n[o]=t[o])}const r=Object.keys(n);let a;try{ZPe(n)}catch(s){a=s}return function(o={},l){if(a)throw a;let c=!1;const u={};for(let d=0;d<r.length;d++){const h=r[d],f=n[h],p=o[h],x=f(p,l);if(typeof x>"u")throw l&&l.type,new Error(Gi(14));u[h]=x,c=c||x!==p}return c=c||r.length!==Object.keys(o).length,c?u:o}}function W1(...t){return t.length===0?e=>e:t.length===1?t[0]:t.reduce((e,n)=>(...r)=>e(n(...r)))}function JPe(...t){return e=>(n,r)=>{const a=e(n,r);let s=()=>{throw new Error(Gi(15))};const o={getState:a.getState,dispatch:(c,...u)=>s(c,...u)},l=t.map(c=>c(o));return s=W1(...l)(a.dispatch),{...a,dispatch:s}}}function $Q(t){return _L(t)&&"type"in t&&typeof t.type=="string"}var VQ=Symbol.for("immer-nothing"),Z$=Symbol.for("immer-draftable"),Ls=Symbol.for("immer-state");function Bl(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Po=Object,_b=Po.getPrototypeOf,K1="constructor",bk="prototype",ND="configurable",X1="enumerable",e1="writable",Ev="value",sd=t=>!!t&&!!t[Ls];function ec(t){return t?qQ(t)||yk(t)||!!t[Z$]||!!t[K1]?.[Z$]||vk(t)||wk(t):!1}var eEe=Po[bk][K1].toString(),J$=new WeakMap;function qQ(t){if(!t||!NL(t))return!1;const e=_b(t);if(e===null||e===Po[bk])return!0;const n=Po.hasOwnProperty.call(e,K1)&&e[K1];if(n===Object)return!0;if(!Dg(n))return!1;let r=J$.get(n);return r===void 0&&(r=Function.toString.call(n),J$.set(n,r)),r===eEe}function xk(t,e,n=!0){w0(t)===0?(n?Reflect.ownKeys(t):Po.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function w0(t){const e=t[Ls];return e?e.type_:yk(t)?1:vk(t)?2:wk(t)?3:0}var eV=(t,e,n=w0(t))=>n===2?t.has(e):Po[bk].hasOwnProperty.call(t,e),CD=(t,e,n=w0(t))=>n===2?t.get(e):t[e],Y1=(t,e,n,r=w0(t))=>{r===2?t.set(e,n):r===3?t.add(n):t[e]=n};function tEe(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}var yk=Array.isArray,vk=t=>t instanceof Map,wk=t=>t instanceof Set,NL=t=>typeof t=="object",Dg=t=>typeof t=="function",rj=t=>typeof t=="boolean";function nEe(t){const e=+t;return Number.isInteger(e)&&String(e)===t}var ju=t=>t.copy_||t.base_,CL=t=>t.modified_?t.copy_:t.base_;function kD(t,e){if(vk(t))return new Map(t);if(wk(t))return new Set(t);if(yk(t))return Array[bk].slice.call(t);const n=qQ(t);if(e===!0||e==="class_only"&&!n){const r=Po.getOwnPropertyDescriptors(t);delete r[Ls];let a=Reflect.ownKeys(r);for(let s=0;s<a.length;s++){const o=a[s],l=r[o];l[e1]===!1&&(l[e1]=!0,l[ND]=!0),(l.get||l.set)&&(r[o]={[ND]:!0,[e1]:!0,[X1]:l[X1],[Ev]:t[o]})}return Po.create(_b(t),r)}else{const r=_b(t);if(r!==null&&n)return{...t};const a=Po.create(r);return Po.assign(a,t)}}function kL(t,e=!1){return Sk(t)||sd(t)||!ec(t)||(w0(t)>1&&Po.defineProperties(t,{set:l_,add:l_,clear:l_,delete:l_}),Po.freeze(t),e&&xk(t,(n,r)=>{kL(r,!0)},!1)),t}function rEe(){Bl(2)}var l_={[Ev]:rEe};function Sk(t){return t===null||!NL(t)?!0:Po.isFrozen(t)}var Q1="MapSet",AD="Patches",tV="ArrayMethods",GQ={};function Vf(t){const e=GQ[t];return e||Bl(0,t),e}var nV=t=>!!GQ[t],jv,WQ=()=>jv,aEe=(t,e)=>({drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:nV(Q1)?Vf(Q1):void 0,arrayMethodsPlugin_:nV(tV)?Vf(tV):void 0});function rV(t,e){e&&(t.patchPlugin_=Vf(AD),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function TD(t){MD(t),t.drafts_.forEach(iEe),t.drafts_=null}function MD(t){t===jv&&(jv=t.parent_)}var aV=t=>jv=aEe(jv,t);function iEe(t){const e=t[Ls];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function iV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];if(t!==void 0&&t!==n){n[Ls].modified_&&(TD(e),Bl(4)),ec(t)&&(t=sV(e,t));const{patchPlugin_:a}=e;a&&a.generateReplacementPatches_(n[Ls].base_,t,e)}else t=sV(e,n);return sEe(e,t,!0),TD(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==VQ?t:void 0}function sV(t,e){if(Sk(e))return e;const n=e[Ls];if(!n)return Z1(e,t.handledSet_,t);if(!_k(n,t))return e;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:r}=n;if(r)for(;r.length>0;)r.pop()(t);YQ(n,t)}return n.copy_}function sEe(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&kL(e,n)}function KQ(t){t.finalized_=!0,t.scope_.unfinalizedDrafts_--}var _k=(t,e)=>t.scope_===e,oEe=[];function XQ(t,e,n,r){const a=ju(t),s=t.type_;if(r!==void 0&&CD(a,r,s)===e){Y1(a,r,n,s);return}if(!t.draftLocations_){const l=t.draftLocations_=new Map;xk(a,(c,u)=>{if(sd(u)){const d=l.get(u)||[];d.push(c),l.set(u,d)}})}const o=t.draftLocations_.get(e)??oEe;for(const l of o)Y1(a,l,n,s)}function lEe(t,e,n){t.callbacks_.push(function(a){const s=e;if(!s||!_k(s,a))return;a.mapSetPlugin_?.fixSetContents(s);const o=CL(s);XQ(t,s.draft_??s,o,n),YQ(s,a)})}function YQ(t,e){if(t.modified_&&!t.finalized_&&(t.type_===3||t.type_===1&&t.allIndicesReassigned_||(t.assigned_?.size??0)>0)){const{patchPlugin_:r}=e;if(r){const a=r.getPath(t);a&&r.generatePatches_(t,a,e)}KQ(t)}}function cEe(t,e,n){const{scope_:r}=t;if(sd(n)){const a=n[Ls];_k(a,r)&&a.callbacks_.push(function(){t1(t);const o=CL(a);XQ(t,n,o,e)})}else ec(n)&&t.callbacks_.push(function(){const s=ju(t);t.type_===3?s.has(n)&&Z1(n,r.handledSet_,r):CD(s,e,t.type_)===n&&r.drafts_.length>1&&(t.assigned_.get(e)??!1)===!0&&t.copy_&&Z1(CD(t.copy_,e,t.type_),r.handledSet_,r)})}function Z1(t,e,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||sd(t)||e.has(t)||!ec(t)||Sk(t)||(e.add(t),xk(t,(r,a)=>{if(sd(a)){const s=a[Ls];if(_k(s,n)){const o=CL(s);Y1(t,r,o,t.type_),KQ(s)}}else ec(a)&&Z1(a,e,n)})),t}function uEe(t,e){const n=yk(t),r={type_:n?1:0,scope_:e?e.scope_:WQ(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,s=J1;n&&(a=[r],s=Dv);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,[l,r]}var J1={get(t,e){if(e===Ls)return t;let n=t.scope_.arrayMethodsPlugin_;const r=t.type_===1&&typeof e=="string";if(r&&n?.isArrayOperationMethod(e))return n.createMethodInterceptor(t,e);const a=ju(t);if(!eV(a,e,t.type_))return dEe(t,a,e);const s=a[e];if(t.finalized_||!ec(s)||r&&t.operationMethod&&n?.isMutatingArrayMethod(t.operationMethod)&&nEe(e))return s;if(s===aj(t.base_,e)){t1(t);const o=t.type_===1?+e:e,l=ED(t.scope_,s,t,o);return t.copy_[o]=l}return s},has(t,e){return e in ju(t)},ownKeys(t){return Reflect.ownKeys(ju(t))},set(t,e,n){const r=QQ(ju(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=aj(ju(t),e),s=a?.[Ls];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_.set(e,!1),!0;if(tEe(n,a)&&(n!==void 0||eV(t.base_,e,t.type_)))return!0;t1(t),PD(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_.set(e,!0),cEe(t,e,n)),!0},deleteProperty(t,e){return t1(t),aj(t.base_,e)!==void 0||e in t.base_?(t.assigned_.set(e,!1),PD(t)):t.assigned_.delete(e),t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=ju(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{[e1]:!0,[ND]:t.type_!==1||e!=="length",[X1]:r[X1],[Ev]:n[e]}},defineProperty(){Bl(11)},getPrototypeOf(t){return _b(t.base_)},setPrototypeOf(){Bl(12)}},Dv={};for(let t in J1){let e=J1[t];Dv[t]=function(){const n=arguments;return n[0]=n[0][0],e.apply(this,n)}}Dv.deleteProperty=function(t,e){return Dv.set.call(this,t,e,void 0)};Dv.set=function(t,e,n){return J1.set.call(this,t[0],e,n,t[0])};function aj(t,e){const n=t[Ls];return(n?ju(n):t)[e]}function dEe(t,e,n){const r=QQ(e,n);return r?Ev in r?r[Ev]:r.get?.call(t.draft_):void 0}function QQ(t,e){if(!(e in t))return;let n=_b(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=_b(n)}}function PD(t){t.modified_||(t.modified_=!0,t.parent_&&PD(t.parent_))}function t1(t){t.copy_||(t.assigned_=new Map,t.copy_=kD(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var hEe=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(n,r,a)=>{if(Dg(n)&&!Dg(r)){const o=r;r=n;const l=this;return function(u=o,...d){return l.produce(u,h=>r.call(this,h,...d))}}Dg(r)||Bl(6),a!==void 0&&!Dg(a)&&Bl(7);let s;if(ec(n)){const o=aV(this),l=ED(o,n,void 0);let c=!0;try{s=r(l),c=!1}finally{c?TD(o):MD(o)}return rV(o,a),iV(s,o)}else if(!n||!NL(n)){if(s=r(n),s===void 0&&(s=n),s===VQ&&(s=void 0),this.autoFreeze_&&kL(s,!0),a){const o=[],l=[];Vf(AD).generateReplacementPatches_(n,s,{patches_:o,inversePatches_:l}),a(o,l)}return s}else Bl(1,n)},this.produceWithPatches=(n,r)=>{if(Dg(n))return(l,...c)=>this.produceWithPatches(l,u=>n(u,...c));let a,s;return[this.produce(n,r,(l,c)=>{a=l,s=c}),a,s]},rj(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),rj(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),rj(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ec(e)||Bl(8),sd(e)&&(e=Kl(e));const n=aV(this),r=ED(n,e,void 0);return r[Ls].isManual_=!0,MD(n),r}finishDraft(e,n){const r=e&&e[Ls];(!r||!r.isManual_)&&Bl(9);const{scope_:a}=r;return rV(a,n),iV(void 0,a)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,n){let r;for(r=n.length-1;r>=0;r--){const s=n[r];if(s.path.length===0&&s.op==="replace"){e=s.value;break}}r>-1&&(n=n.slice(r+1));const a=Vf(AD).applyPatches_;return sd(e)?a(e,n):this.produce(e,s=>a(s,n))}};function ED(t,e,n,r){const[a,s]=vk(e)?Vf(Q1).proxyMap_(e,n):wk(e)?Vf(Q1).proxySet_(e,n):uEe(e,n);return(n?.scope_??WQ()).drafts_.push(a),s.callbacks_=n?.callbacks_??[],s.key_=r,n&&r!==void 0?lEe(n,s,r):s.callbacks_.push(function(c){c.mapSetPlugin_?.fixSetContents(s);const{patchPlugin_:u}=c;s.modified_&&u&&u.generatePatches_(s,[],c)}),a}function Kl(t){return sd(t)||Bl(10,t),ZQ(t)}function ZQ(t){if(!ec(t)||Sk(t))return t;const e=t[Ls];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=kD(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=kD(t,!0);return xk(n,(a,s)=>{Y1(n,a,ZQ(s))},r),e&&(e.finalized_=!1),n}var mEe=new hEe,JQ=mEe.produce;function eZ(t){return({dispatch:n,getState:r})=>a=>s=>typeof s=="function"?s(n,r,t):a(s)}var fEe=eZ(),pEe=eZ,gEe=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?W1:W1.apply(null,arguments)};function Nl(t,e){function n(...r){if(e){let a=e(...r);if(!a)throw new Error(Ro(0));return{type:t,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:t,payload:r[0]}}return n.toString=()=>`${t}`,n.type=t,n.match=r=>$Q(r)&&r.type===t,n}var tZ=class Py extends Array{constructor(...e){super(...e),Object.setPrototypeOf(this,Py.prototype)}static get[Symbol.species](){return Py}concat(...e){return super.concat.apply(this,e)}prepend(...e){return e.length===1&&Array.isArray(e[0])?new Py(...e[0].concat(this)):new Py(...e.concat(this))}};function oV(t){return ec(t)?JQ(t,()=>{}):t}function c_(t,e,n){return t.has(e)?t.get(e):t.set(e,n(e)).get(e)}function bEe(t){return typeof t=="boolean"}var xEe=()=>function(e){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:a=!0,actionCreatorCheck:s=!0}=e??{};let o=new tZ;return n&&(bEe(n)?o.push(fEe):o.push(pEe(n.extraArgument))),o},nZ="RTK_autoBatch",la=()=>t=>({payload:t,meta:{[nZ]:!0}}),lV=t=>e=>{setTimeout(e,t)},rZ=(t={type:"raf"})=>e=>(...n)=>{const r=e(...n);let a=!0,s=!1,o=!1;const l=new Set,c=t.type==="tick"?queueMicrotask:t.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:lV(10):t.type==="callback"?t.queueNotification:lV(t.timeout),u=()=>{o=!1,s&&(s=!1,l.forEach(d=>d()))};return Object.assign({},r,{subscribe(d){const h=()=>a&&d(),f=r.subscribe(h);return l.add(d),()=>{f(),l.delete(d)}},dispatch(d){try{return a=!d?.meta?.[nZ],s=!a,s&&(o||(o=!0,c(u))),r.dispatch(d)}finally{a=!0}}})},yEe=t=>function(n){const{autoBatch:r=!0}=n??{};let a=new tZ(t);return r&&a.push(rZ(typeof r=="object"?r:void 0)),a};function vEe(t){const e=xEe(),{reducer:n=void 0,middleware:r,devTools:a=!0,preloadedState:s=void 0,enhancers:o=void 0}=t||{};let l;if(typeof n=="function")l=n;else if(_L(n))l=HQ(n);else throw new Error(Ro(1));let c;typeof r=="function"?c=r(e):c=e();let u=W1;a&&(u=gEe({trace:!1,...typeof a=="object"&&a}));const d=JPe(...c),h=yEe(d);let f=typeof o=="function"?o(h):h();const p=u(...f);return BQ(l,s,p)}function aZ(t){const e={},n=[];let r;const a={addCase(s,o){const l=typeof s=="string"?s:s.type;if(!l)throw new Error(Ro(28));if(l in e)throw new Error(Ro(29));return e[l]=o,a},addAsyncThunk(s,o){return o.pending&&(e[s.pending.type]=o.pending),o.rejected&&(e[s.rejected.type]=o.rejected),o.fulfilled&&(e[s.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:s.settled,reducer:o.settled}),a},addMatcher(s,o){return n.push({matcher:s,reducer:o}),a},addDefaultCase(s){return r=s,a}};return t(a),[e,n,r]}function wEe(t){return typeof t=="function"}function SEe(t,e){let[n,r,a]=aZ(e),s;if(wEe(t))s=()=>oV(t());else{const l=oV(t);s=()=>l}function o(l=s(),c){let u=[n[c.type],...r.filter(({matcher:d})=>d(c)).map(({reducer:d})=>d)];return u.filter(d=>!!d).length===0&&(u=[a]),u.reduce((d,h)=>{if(h)if(sd(d)){const p=h(d,c);return p===void 0?d:p}else{if(ec(d))return JQ(d,f=>h(f,c));{const f=h(d,c);if(f===void 0){if(d===null)return d;throw Error("A case reducer on a non-draftable value must not return undefined")}return f}}return d},l)}return o.getInitialState=s,o}var _Ee="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",NEe=(t=21)=>{let e="",n=t;for(;n--;)e+=_Ee[Math.random()*64|0];return e},CEe=Symbol.for("rtk-slice-createasyncthunk");function kEe(t,e){return`${t}/${e}`}function AEe({creators:t}={}){const e=t?.asyncThunk?.[CEe];return function(r){const{name:a,reducerPath:s=a}=r;if(!a)throw new Error(Ro(11));const o=(typeof r.reducers=="function"?r.reducers(MEe()):r.reducers)||{},l=Object.keys(o),c={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},u={addCase(N,k){const A=typeof N=="string"?N:N.type;if(!A)throw new Error(Ro(12));if(A in c.sliceCaseReducersByType)throw new Error(Ro(13));return c.sliceCaseReducersByType[A]=k,u},addMatcher(N,k){return c.sliceMatchers.push({matcher:N,reducer:k}),u},exposeAction(N,k){return c.actionCreators[N]=k,u},exposeCaseReducer(N,k){return c.sliceCaseReducersByName[N]=k,u}};l.forEach(N=>{const k=o[N],A={reducerName:N,type:kEe(a,N),createNotation:typeof r.reducers=="function"};EEe(k)?DEe(A,k,u,e):PEe(A,k,u)});function d(){const[N={},k=[],A=void 0]=typeof r.extraReducers=="function"?aZ(r.extraReducers):[r.extraReducers],M={...N,...c.sliceCaseReducersByType};return SEe(r.initialState,C=>{for(let j in M)C.addCase(j,M[j]);for(let j of c.sliceMatchers)C.addMatcher(j.matcher,j.reducer);for(let j of k)C.addMatcher(j.matcher,j.reducer);A&&C.addDefaultCase(A)})}const h=N=>N,f=new Map,p=new WeakMap;let x;function v(N,k){return x||(x=d()),x(N,k)}function g(){return x||(x=d()),x.getInitialState()}function y(N,k=!1){function A(C){let j=C[N];return typeof j>"u"&&k&&(j=c_(p,A,g)),j}function M(C=h){const j=c_(f,k,()=>new WeakMap);return c_(j,C,()=>{const P={};for(const[E,U]of Object.entries(r.selectors??{}))P[E]=TEe(U,C,()=>c_(p,C,g),k);return P})}return{reducerPath:N,getSelectors:M,get selectors(){return M(A)},selectSlice:A}}const _={name:a,reducer:v,actions:c.actionCreators,caseReducers:c.sliceCaseReducersByName,getInitialState:g,...y(s),injectInto(N,{reducerPath:k,...A}={}){const M=k??s;return N.inject({reducerPath:M,reducer:v},A),{..._,...y(M,!0)}}};return _}}function TEe(t,e,n,r){function a(s,...o){let l=e(s);return typeof l>"u"&&r&&(l=n()),t(l,...o)}return a.unwrapped=t,a}var lo=AEe();function MEe(){function t(e,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...n}}return t.withTypes=()=>t,{reducer(e){return Object.assign({[e.name](...n){return e(...n)}}[e.name],{_reducerDefinitionType:"reducer"})},preparedReducer(e,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:n}},asyncThunk:t}}function PEe({type:t,reducerName:e,createNotation:n},r,a){let s,o;if("reducer"in r){if(n&&!jEe(r))throw new Error(Ro(17));s=r.reducer,o=r.prepare}else s=r;a.addCase(t,s).exposeCaseReducer(e,s).exposeAction(e,o?Nl(t,o):Nl(t))}function EEe(t){return t._reducerDefinitionType==="asyncThunk"}function jEe(t){return t._reducerDefinitionType==="reducerWithPrepare"}function DEe({type:t,reducerName:e},n,r,a){if(!a)throw new Error(Ro(18));const{payloadCreator:s,fulfilled:o,pending:l,rejected:c,settled:u,options:d}=n,h=a(t,s,d);r.exposeAction(e,h),o&&r.addCase(h.fulfilled,o),l&&r.addCase(h.pending,l),c&&r.addCase(h.rejected,c),u&&r.addMatcher(h.settled,u),r.exposeCaseReducer(e,{fulfilled:o||u_,pending:l||u_,rejected:c||u_,settled:u||u_})}function u_(){}var REe="task",iZ="listener",sZ="completed",AL="cancelled",FEe=`task-${AL}`,LEe=`task-${sZ}`,jD=`${iZ}-${AL}`,OEe=`${iZ}-${sZ}`,Nk=class{constructor(t){this.code=t,this.message=`${REe} ${AL} (reason: ${t})`}name="TaskAbortError";message},TL=(t,e)=>{if(typeof t!="function")throw new TypeError(Ro(32))},eN=()=>{},oZ=(t,e=eN)=>(t.catch(e),t),lZ=(t,e)=>(t.addEventListener("abort",e,{once:!0}),()=>t.removeEventListener("abort",e)),gf=t=>{if(t.aborted)throw new Nk(t.reason)};function cZ(t,e){let n=eN;return new Promise((r,a)=>{const s=()=>a(new Nk(t.reason));if(t.aborted){s();return}n=lZ(t,s),e.finally(()=>n()).then(r,a)}).finally(()=>{n=eN})}var IEe=async(t,e)=>{try{return await Promise.resolve(),{status:"ok",value:await t()}}catch(n){return{status:n instanceof Nk?"cancelled":"rejected",error:n}}finally{e?.()}},tN=t=>e=>oZ(cZ(t,e).then(n=>(gf(t),n))),uZ=t=>{const e=tN(t);return n=>e(new Promise(r=>setTimeout(r,n)))},{assign:tb}=Object,cV={},Ck="listenerMiddleware",zEe=(t,e)=>{const n=r=>lZ(t,()=>r.abort(t.reason));return(r,a)=>{TL(r);const s=new AbortController;n(s);const o=IEe(async()=>{gf(t),gf(s.signal);const l=await r({pause:tN(s.signal),delay:uZ(s.signal),signal:s.signal});return gf(s.signal),l},()=>s.abort(LEe));return a?.autoJoin&&e.push(o.catch(eN)),{result:tN(t)(o),cancel(){s.abort(FEe)}}}},UEe=(t,e)=>{const n=async(r,a)=>{gf(e);let s=()=>{};const l=[new Promise((c,u)=>{let d=t({predicate:r,effect:(h,f)=>{f.unsubscribe(),c([h,f.getState(),f.getOriginalState()])}});s=()=>{d(),u()}})];a!=null&&l.push(new Promise(c=>setTimeout(c,a,null)));try{const c=await cZ(e,Promise.race(l));return gf(e),c}finally{s()}};return(r,a)=>oZ(n(r,a))},dZ=t=>{let{type:e,actionCreator:n,matcher:r,predicate:a,effect:s}=t;if(e)a=Nl(e).match;else if(n)e=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(Ro(21));return TL(s),{predicate:a,type:e,effect:s}},hZ=tb(t=>{const{type:e,predicate:n,effect:r}=dZ(t);return{id:NEe(),effect:r,type:e,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(Ro(22))}}},{withTypes:()=>hZ}),uV=(t,e)=>{const{type:n,effect:r,predicate:a}=dZ(e);return Array.from(t.values()).find(s=>(typeof n=="string"?s.type===n:s.predicate===a)&&s.effect===r)},DD=t=>{t.pending.forEach(e=>{e.abort(jD)})},BEe=(t,e)=>()=>{for(const n of e.keys())DD(n);t.clear()},dV=(t,e,n)=>{try{t(e,n)}catch(r){setTimeout(()=>{throw r},0)}},mZ=tb(Nl(`${Ck}/add`),{withTypes:()=>mZ}),HEe=Nl(`${Ck}/removeAll`),fZ=tb(Nl(`${Ck}/remove`),{withTypes:()=>fZ}),$Ee=(...t)=>{console.error(`${Ck}/error`,...t)},S0=(t={})=>{const e=new Map,n=new Map,r=p=>{const x=n.get(p)??0;n.set(p,x+1)},a=p=>{const x=n.get(p)??1;x===1?n.delete(p):n.set(p,x-1)},{extra:s,onError:o=$Ee}=t;TL(o);const l=p=>(p.unsubscribe=()=>e.delete(p.id),e.set(p.id,p),x=>{p.unsubscribe(),x?.cancelActive&&DD(p)}),c=p=>{const x=uV(e,p)??hZ(p);return l(x)};tb(c,{withTypes:()=>c});const u=p=>{const x=uV(e,p);return x&&(x.unsubscribe(),p.cancelActive&&DD(x)),!!x};tb(u,{withTypes:()=>u});const d=async(p,x,v,g)=>{const y=new AbortController,_=UEe(c,y.signal),N=[];try{p.pending.add(y),r(p),await Promise.resolve(p.effect(x,tb({},v,{getOriginalState:g,condition:(k,A)=>_(k,A).then(Boolean),take:_,delay:uZ(y.signal),pause:tN(y.signal),extra:s,signal:y.signal,fork:zEe(y.signal,N),unsubscribe:p.unsubscribe,subscribe:()=>{e.set(p.id,p)},cancelActiveListeners:()=>{p.pending.forEach((k,A,M)=>{k!==y&&(k.abort(jD),M.delete(k))})},cancel:()=>{y.abort(jD),p.pending.delete(y)},throwIfCancelled:()=>{gf(y.signal)}})))}catch(k){k instanceof Nk||dV(o,k,{raisedBy:"effect"})}finally{await Promise.all(N),y.abort(OEe),a(p),p.pending.delete(y)}},h=BEe(e,n);return{middleware:p=>x=>v=>{if(!$Q(v))return x(v);if(mZ.match(v))return c(v.payload);if(HEe.match(v)){h();return}if(fZ.match(v))return u(v.payload);let g=p.getState();const y=()=>{if(g===cV)throw new Error(Ro(23));return g};let _;try{if(_=x(v),e.size>0){const N=p.getState(),k=Array.from(e.values());for(const A of k){let M=!1;try{M=A.predicate(v,N,g)}catch(C){M=!1,dV(o,C,{raisedBy:"predicate"})}M&&d(A,v,p,y)}}}finally{g=cV}return _},startListening:c,stopListening:u,clearListeners:h}};function Ro(t){return`Minified Redux Toolkit error #${t}; visit https://redux-toolkit.js.org/Errors?code=${t} for the full message or use the non-minified dev environment for full errors. `}var VEe={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},pZ=lo({name:"chartLayout",initialState:VEe,reducers:{setLayout(t,e){t.layoutType=e.payload},setChartSize(t,e){t.width=e.payload.width,t.height=e.payload.height},setMargin(t,e){var n,r,a,s;t.margin.top=(n=e.payload.top)!==null&&n!==void 0?n:0,t.margin.right=(r=e.payload.right)!==null&&r!==void 0?r:0,t.margin.bottom=(a=e.payload.bottom)!==null&&a!==void 0?a:0,t.margin.left=(s=e.payload.left)!==null&&s!==void 0?s:0},setScale(t,e){t.scale=e.payload}}}),{setMargin:qEe,setLayout:GEe,setChartSize:WEe,setScale:KEe}=pZ.actions,XEe=pZ.reducer;function gZ(t,e,n){return Array.isArray(t)&&t&&e+n!==0?t.slice(e,n+1):t}function Nn(t){return Number.isFinite(t)}function Oc(t){return typeof t=="number"&&t>0&&Number.isFinite(t)}function hV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Bg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?hV(Object(n),!0).forEach(function(r){YEe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):hV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function YEe(t,e,n){return(e=QEe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function QEe(t){var e=ZEe(t,"string");return typeof e=="symbol"?e:e+""}function ZEe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yr(t,e,n){return ha(t)||ha(e)?n:_l(e)?Hf(t,e,n):typeof e=="function"?e(t):n}var JEe=(t,e,n)=>{if(e&&n){var{width:r,height:a}=n,{align:s,verticalAlign:o,layout:l}=e;if((l==="vertical"||l==="horizontal"&&o==="middle")&&s!=="center"&&qt(t[s]))return Bg(Bg({},t),{},{[s]:t[s]+(r||0)});if((l==="horizontal"||l==="vertical"&&s==="center")&&o!=="middle"&&qt(t[o]))return Bg(Bg({},t),{},{[o]:t[o]+(a||0)})}return t},sc=(t,e)=>t==="horizontal"&&e==="xAxis"||t==="vertical"&&e==="yAxis"||t==="centric"&&e==="angleAxis"||t==="radial"&&e==="radiusAxis",bZ=(t,e,n,r)=>{if(r)return t.map(l=>l.coordinate);var a,s,o=t.map(l=>(l.coordinate===e&&(a=!0),l.coordinate===n&&(s=!0),l.coordinate));return a||o.push(e),s||o.push(n),o},xZ=(t,e,n)=>{if(!t)return null;var{duplicateDomain:r,type:a,range:s,scale:o,realScaleType:l,isCategorical:c,categoricalDomain:u,tickCount:d,ticks:h,niceTicks:f,axisType:p}=t;if(!o)return null;var x=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,v=a==="category"&&o.bandwidth?o.bandwidth()/x:0;if(v=p==="angleAxis"&&s&&s.length>=2?Ri(s[0]-s[1])*2*v:v,h||f){var g=(h||f||[]).map((y,_)=>{var N=r?r.indexOf(y):y,k=o.map(N);return Nn(k)?{coordinate:k+v,value:y,offset:v,index:_}:null}).filter(Js);return g}return c&&u?u.map((y,_)=>{var N=o.map(y);return Nn(N)?{coordinate:N+v,value:y,index:_,offset:v}:null}).filter(Js):o.ticks&&d!=null?o.ticks(d).map((y,_)=>{var N=o.map(y);return Nn(N)?{coordinate:N+v,value:y,index:_,offset:v}:null}).filter(Js):o.domain().map((y,_)=>{var N=o.map(y);return Nn(N)?{coordinate:N+v,value:r?r[y]:y,index:_,offset:v}:null}).filter(Js)},eje=(t,e)=>{if(!e||e.length!==2||!qt(e[0])||!qt(e[1]))return t;var n=Math.min(e[0],e[1]),r=Math.max(e[0],e[1]),a=[t[0],t[1]];return(!qt(t[0])||t[0]<n)&&(a[0]=n),(!qt(t[1])||t[1]>r)&&(a[1]=r),a[0]>r&&(a[0]=r),a[1]<n&&(a[1]=n),a},tje=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a<r;++a)for(var s=0,o=0,l=0;l<n;++l){var c=t[l],u=c?.[a];if(u!=null){var d=u[1],h=u[0],f=Jl(d)?h:d;f>=0?(u[0]=s,s+=f,u[1]=s):(u[0]=o,o+=f,u[1]=o)}}}},nje=t=>{var e,n=t.length;if(!(n<=0)){var r=(e=t[0])===null||e===void 0?void 0:e.length;if(!(r==null||r<=0))for(var a=0;a<r;++a)for(var s=0,o=0;o<n;++o){var l=t[o],c=l?.[a];if(c!=null){var u=Jl(c[1])?c[0]:c[1];u>=0?(c[0]=s,s+=u,c[1]=s):(c[0]=0,c[1]=0)}}}},rje={sign:tje,expand:kMe,none:Bf,silhouette:AMe,wiggle:TMe,positive:nje},aje=(t,e,n)=>{var r,a=(r=rje[n])!==null&&r!==void 0?r:Bf,s=CMe().keys(e).value((l,c)=>Number(yr(l,c,0))).order(SD).offset(a),o=s(t);return o.forEach((l,c)=>{l.forEach((u,d)=>{var h=yr(t[d],e[c],0);Array.isArray(h)&&h.length===2&&qt(h[0])&&qt(h[1])&&(u[0]=h[0],u[1]=h[1])})}),o};function yZ(t){return t==null?void 0:String(t)}function nN(t){var{axis:e,ticks:n,bandSize:r,entry:a,index:s,dataKey:o}=t;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!ha(a[e.dataKey])){var l=_Q(n,"value",a[e.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[s]?n[s].coordinate+r/2:null}var c=yr(a,ha(o)?e.dataKey:o),u=e.scale.map(c);return qt(u)?u:null}var mV=t=>{var{axis:e,ticks:n,offset:r,bandSize:a,entry:s,index:o}=t;if(e.type==="category")return n[o]?n[o].coordinate+r:null;var l=yr(s,e.dataKey,e.scale.domain()[o]);if(ha(l))return null;var c=e.scale.map(l);return qt(c)?c-a/2+r:null},ije=t=>{var{numericAxis:e}=t,n=e.scale.domain();if(e.type==="number"){var r=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return r<=0&&a>=0?0:a<0?a:r}return n[0]},sje=t=>{var e=t.flat(2).filter(qt);return[Math.min(...e),Math.max(...e)]},oje=t=>[t[0]===1/0?0:t[0],t[1]===-1/0?0:t[1]],lje=(t,e,n)=>{if(t!=null)return oje(Object.keys(t).reduce((r,a)=>{var s=t[a];if(!s)return r;var{stackedData:o}=s,l=o.reduce((c,u)=>{var d=gZ(u,e,n),h=sje(d);return!Nn(h[0])||!Nn(h[1])?c:[Math.min(c[0],h[0]),Math.max(c[1],h[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},fV=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,pV=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Xh=(t,e,n)=>{if(t&&t.scale&&t.scale.bandwidth){var r=t.scale.bandwidth();if(!n||r>0)return r}if(t&&e&&e.length>=2){for(var a=gk(e,d=>d.coordinate),s=1/0,o=1,l=a.length;o<l;o++){var c=a[o],u=a[o-1];s=Math.min((c?.coordinate||0)-(u?.coordinate||0),s)}return s===1/0?0:s}return n?void 0:0};function gV(t){var{tooltipEntrySettings:e,dataKey:n,payload:r,value:a,name:s}=t;return Bg(Bg({},e),{},{dataKey:n,payload:r,value:a,name:s})}function tm(t,e){if(t)return String(t);if(typeof e=="string")return e}var cje=(t,e)=>{if(e==="horizontal")return t.chartX;if(e==="vertical")return t.chartY},uje=(t,e)=>e==="centric"?t.angle:t.radius,fd=t=>t.layout.width,pd=t=>t.layout.height,dje=t=>t.layout.scale,vZ=t=>t.layout.margin,kk=ct(t=>t.cartesianAxis.xAxis,t=>Object.values(t)),Ak=ct(t=>t.cartesianAxis.yAxis,t=>Object.values(t)),wZ="data-recharts-item-index",SZ="data-recharts-item-id",_0=60;function bV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function d_(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?bV(Object(n),!0).forEach(function(r){hje(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):bV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function hje(t,e,n){return(e=mje(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mje(t){var e=fje(t,"string");return typeof e=="symbol"?e:e+""}function fje(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var pje=t=>t.brush.height;function gje(t){var e=Ak(t);return e.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:_0;return n+a}return n},0)}function bje(t){var e=Ak(t);return e.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:_0;return n+a}return n},0)}function xje(t){var e=kk(t);return e.reduce((n,r)=>r.orientation==="top"&&!r.mirror&&!r.hide?n+r.height:n,0)}function yje(t){var e=kk(t);return e.reduce((n,r)=>r.orientation==="bottom"&&!r.mirror&&!r.hide?n+r.height:n,0)}var vi=ct([fd,pd,vZ,pje,gje,bje,xje,yje,zQ,GPe],(t,e,n,r,a,s,o,l,c,u)=>{var d={left:(n.left||0)+a,right:(n.right||0)+s},h={top:(n.top||0)+o,bottom:(n.bottom||0)+l},f=d_(d_({},h),d),p=f.bottom;f.bottom+=r,f=JEe(f,c,u);var x=t-f.left-f.right,v=e-f.top-f.bottom;return d_(d_({brushBottom:p},f),{},{width:Math.max(x,0),height:Math.max(v,0)})}),vje=ct(vi,t=>({x:t.left,y:t.top,width:t.width,height:t.height})),ML=ct(fd,pd,(t,e)=>({x:0,y:0,width:t,height:e})),wje=w.createContext(null),wi=()=>w.useContext(wje)!=null,Tk=t=>t.brush,Mk=ct([Tk,vi,vZ],(t,e,n)=>({height:t.height,x:qt(t.x)?t.x:e.left,y:qt(t.y)?t.y:e.top+e.height+e.brushBottom-(n?.bottom||0),width:qt(t.width)?t.width:e.width})),ij={},sj={},oj={},xV;function Sje(){return xV||(xV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n,r,{signal:a,edges:s}={}){let o,l=null;const c=s!=null&&s.includes("leading"),u=s==null||s.includes("trailing"),d=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},h=()=>{u&&d(),v()};let f=null;const p=()=>{f!=null&&clearTimeout(f),f=setTimeout(()=>{f=null,h()},r)},x=()=>{f!==null&&(clearTimeout(f),f=null)},v=()=>{x(),o=void 0,l=null},g=()=>{d()},y=function(..._){if(a?.aborted)return;o=this,l=_;const N=f==null;p(),c&&N&&d()};return y.schedule=p,y.cancel=v,y.flush=g,a?.addEventListener("abort",v,{once:!0}),y}t.debounce=e})(oj)),oj}var yV;function _je(){return yV||(yV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=Sje();function n(r,a=0,s={}){typeof s!="object"&&(s={});const{leading:o=!1,trailing:l=!0,maxWait:c}=s,u=Array(2);o&&(u[0]="leading"),l&&(u[1]="trailing");let d,h=null;const f=e.debounce(function(...v){d=r.apply(this,v),h=null},a,{edges:u}),p=function(...v){return c!=null&&(h===null&&(h=Date.now()),Date.now()-h>=c)?(d=r.apply(this,v),h=Date.now(),f.cancel(),f.schedule(),d):(f.apply(this,v),d)},x=()=>(f.flush(),d);return p.cancel=f.cancel,p.flush=x,p}t.debounce=n})(sj)),sj}var vV;function Nje(){return vV||(vV=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=_je();function n(r,a=0,s={}){const{leading:o=!0,trailing:l=!0}=s;return e.debounce(r,a,{leading:o,maxWait:a,trailing:l})}t.throttle=n})(ij)),ij}var lj,wV;function Cje(){return wV||(wV=1,lj=Nje().throttle),lj}var kje=Cje();const Aje=nc(kje);var rN=function(e,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),s=2;s<r;s++)a[s-2]=arguments[s];if(typeof console<"u"&&console.warn&&(n===void 0&&console.warn("LogUtils requires an error message argument"),!e))if(n===void 0)console.warn("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var o=0;console.warn(n.replace(/%s/g,()=>a[o++]))}},Tc={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},_Z=(t,e,n)=>{var{width:r=Tc.width,height:a=Tc.height,aspect:s,maxHeight:o}=n,l=$f(r)?t:Number(r),c=$f(a)?e:Number(a);return s&&s>0&&(l?c=l/s:c&&(l=c*s),o&&c!=null&&c>o&&(c=o)),{calculatedWidth:l,calculatedHeight:c}},Tje={width:0,height:0,overflow:"visible"},Mje={width:0,overflowX:"visible"},Pje={height:0,overflowY:"visible"},Eje={},jje=t=>{var{width:e,height:n}=t,r=$f(e),a=$f(n);return r&&a?Tje:r?Mje:a?Pje:Eje};function Dje(t){var{width:e,height:n,aspect:r}=t,a=e,s=n;return a===void 0&&s===void 0?(a=Tc.width,s=Tc.height):a===void 0?a=r&&r>0?void 0:Tc.width:s===void 0&&(s=r&&r>0?void 0:Tc.height),{width:a,height:s}}function RD(){return RD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},RD.apply(null,arguments)}function SV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _V(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?SV(Object(n),!0).forEach(function(r){Rje(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):SV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Rje(t,e,n){return(e=Fje(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Fje(t){var e=Lje(t,"string");return typeof e=="symbol"?e:e+""}function Lje(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var NZ=w.createContext(Tc.initialDimension);function Oje(t){return Oc(t.width)&&Oc(t.height)}function CZ(t){var{children:e,width:n,height:r}=t,a=w.useMemo(()=>({width:n,height:r}),[n,r]);return Oje(a)?w.createElement(NZ.Provider,{value:a},e):null}var PL=()=>w.useContext(NZ),Ije=w.forwardRef((t,e)=>{var{aspect:n,initialDimension:r=Tc.initialDimension,width:a,height:s,minWidth:o=Tc.minWidth,minHeight:l,maxHeight:c,children:u,debounce:d=Tc.debounce,id:h,className:f,onResize:p,style:x={}}=t,v=w.useRef(null),g=w.useRef();g.current=p,w.useImperativeHandle(e,()=>v.current);var[y,_]=w.useState({containerWidth:r.width,containerHeight:r.height}),N=w.useCallback((j,P)=>{_(E=>{var U=Math.round(j),L=Math.round(P);return E.containerWidth===U&&E.containerHeight===L?E:{containerWidth:U,containerHeight:L}})},[]);w.useEffect(()=>{if(v.current==null||typeof ResizeObserver>"u")return em;var j=L=>{var B,D=L[0];if(D!=null){var{width:$,height:G}=D.contentRect;N($,G),(B=g.current)===null||B===void 0||B.call(g,$,G)}};d>0&&(j=Aje(j,d,{trailing:!0,leading:!1}));var P=new ResizeObserver(j),{width:E,height:U}=v.current.getBoundingClientRect();return N(E,U),P.observe(v.current),()=>{P.disconnect()}},[N,d]);var{containerWidth:k,containerHeight:A}=y;rN(!n||n>0,"The aspect(%s) must be greater than zero.",n);var{calculatedWidth:M,calculatedHeight:C}=_Z(k,A,{width:a,height:s,aspect:n,maxHeight:c});return rN(M!=null&&M>0||C!=null&&C>0,`The width(%s) and height(%s) of chart should be greater than 0,
  8071. please check the style of container, or the props width(%s) and height(%s),
  8072. or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the
  8073. height and width.`,M,C,a,s,o,l,n),w.createElement("div",{id:h?"".concat(h):void 0,className:ir("recharts-responsive-container",f),style:_V(_V({},x),{},{width:a,height:s,minWidth:o,minHeight:l,maxHeight:c}),ref:v},w.createElement("div",{style:jje({width:a,height:s})},w.createElement(CZ,{width:M,height:C},u)))}),n1=w.forwardRef((t,e)=>{var n=PL();if(Oc(n.width)&&Oc(n.height))return t.children;var{width:r,height:a}=Dje({width:t.width,height:t.height,aspect:t.aspect}),{calculatedWidth:s,calculatedHeight:o}=_Z(void 0,void 0,{width:r,height:a,aspect:t.aspect,maxHeight:t.maxHeight});return qt(s)&&qt(o)?w.createElement(CZ,{width:s,height:o},t.children):w.createElement(Ije,RD({},t,{width:r,height:a,ref:e}))});function EL(t){if(t)return{x:t.x,y:t.y,upperWidth:"upperWidth"in t?t.upperWidth:t.width,lowerWidth:"lowerWidth"in t?t.lowerWidth:t.width,width:t.width,height:t.height}}var N0=()=>{var t,e=wi(),n=Kt(vje),r=Kt(Mk),a=(t=Kt(Tk))===null||t===void 0?void 0:t.padding;return!e||!r||!a?n:{width:r.width-a.left-a.right,height:r.height-a.top-a.bottom,x:a.left,y:a.top}},zje={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},kZ=()=>{var t;return(t=Kt(vi))!==null&&t!==void 0?t:zje},jL=()=>Kt(fd),DL=()=>Kt(pd),Uje=()=>Kt(t=>t.layout.margin),ar=t=>t.layout.layoutType,nm=()=>Kt(ar),RL=()=>{var t=nm();if(t==="horizontal"||t==="vertical")return t},AZ=t=>{var e=t.layout.layoutType;if(e==="centric"||e==="radial")return e},Bje=()=>{var t=nm();return t!==void 0},C0=t=>{var e=qr(),n=wi(),{width:r,height:a}=t,s=PL(),o=r,l=a;return s&&(o=s.width>0?s.width:r,l=s.height>0?s.height:a),w.useEffect(()=>{!n&&Oc(o)&&Oc(l)&&e(WEe({width:o,height:l}))},[e,n,o,l]),null},TZ=Symbol.for("immer-nothing"),NV=Symbol.for("immer-draftable"),Oo=Symbol.for("immer-state");function Hl(t,...e){throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Rv=Object.getPrototypeOf;function Nb(t){return!!t&&!!t[Oo]}function qf(t){return t?MZ(t)||Array.isArray(t)||!!t[NV]||!!t.constructor?.[NV]||k0(t)||Ek(t):!1}var Hje=Object.prototype.constructor.toString(),CV=new WeakMap;function MZ(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);if(e===null||e===Object.prototype)return!0;const n=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;if(n===Object)return!0;if(typeof n!="function")return!1;let r=CV.get(n);return r===void 0&&(r=Function.toString.call(n),CV.set(n,r)),r===Hje}function aN(t,e,n=!0){Pk(t)===0?(n?Reflect.ownKeys(t):Object.keys(t)).forEach(a=>{e(a,t[a],t)}):t.forEach((r,a)=>e(a,r,t))}function Pk(t){const e=t[Oo];return e?e.type_:Array.isArray(t)?1:k0(t)?2:Ek(t)?3:0}function FD(t,e){return Pk(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function PZ(t,e,n){const r=Pk(t);r===2?t.set(e,n):r===3?t.add(n):t[e]=n}function $je(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function k0(t){return t instanceof Map}function Ek(t){return t instanceof Set}function Vm(t){return t.copy_||t.base_}function LD(t,e){if(k0(t))return new Map(t);if(Ek(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);const n=MZ(t);if(e===!0||e==="class_only"&&!n){const r=Object.getOwnPropertyDescriptors(t);delete r[Oo];let a=Reflect.ownKeys(r);for(let s=0;s<a.length;s++){const o=a[s],l=r[o];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(r[o]={configurable:!0,writable:!0,enumerable:l.enumerable,value:t[o]})}return Object.create(Rv(t),r)}else{const r=Rv(t);if(r!==null&&n)return{...t};const a=Object.create(r);return Object.assign(a,t)}}function FL(t,e=!1){return jk(t)||Nb(t)||!qf(t)||(Pk(t)>1&&Object.defineProperties(t,{set:h_,add:h_,clear:h_,delete:h_}),Object.freeze(t),e&&Object.values(t).forEach(n=>FL(n,!0))),t}function Vje(){Hl(2)}var h_={value:Vje};function jk(t){return t===null||typeof t!="object"?!0:Object.isFrozen(t)}var qje={};function Gf(t){const e=qje[t];return e||Hl(0,t),e}var Fv;function EZ(){return Fv}function Gje(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kV(t,e){e&&(Gf("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function OD(t){ID(t),t.drafts_.forEach(Wje),t.drafts_=null}function ID(t){t===Fv&&(Fv=t.parent_)}function AV(t){return Fv=Gje(Fv,t)}function Wje(t){const e=t[Oo];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function TV(t,e){e.unfinalizedDrafts_=e.drafts_.length;const n=e.drafts_[0];return t!==void 0&&t!==n?(n[Oo].modified_&&(OD(e),Hl(4)),qf(t)&&(t=iN(e,t),e.parent_||sN(e,t)),e.patches_&&Gf("Patches").generateReplacementPatches_(n[Oo].base_,t,e.patches_,e.inversePatches_)):t=iN(e,n,[]),OD(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==TZ?t:void 0}function iN(t,e,n){if(jk(e))return e;const r=t.immer_.shouldUseStrictIteration(),a=e[Oo];if(!a)return aN(e,(s,o)=>MV(t,a,e,s,o,n),r),e;if(a.scope_!==t)return e;if(!a.modified_)return sN(t,a.base_,!0),a.base_;if(!a.finalized_){a.finalized_=!0,a.scope_.unfinalizedDrafts_--;const s=a.copy_;let o=s,l=!1;a.type_===3&&(o=new Set(s),s.clear(),l=!0),aN(o,(c,u)=>MV(t,a,s,c,u,n,l),r),sN(t,s,!1),n&&t.patches_&&Gf("Patches").generatePatches_(a,n,t.patches_,t.inversePatches_)}return a.copy_}function MV(t,e,n,r,a,s,o){if(a==null||typeof a!="object"&&!o)return;const l=jk(a);if(!(l&&!o)){if(Nb(a)){const c=s&&e&&e.type_!==3&&!FD(e.assigned_,r)?s.concat(r):void 0,u=iN(t,a,c);if(PZ(n,r,u),Nb(u))t.canAutoFreeze_=!1;else return}else o&&n.add(a);if(qf(a)&&!l){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1||e&&e.base_&&e.base_[r]===a&&l)return;iN(t,a),(!e||!e.scope_.parent_)&&typeof r!="symbol"&&(k0(n)?n.has(r):Object.prototype.propertyIsEnumerable.call(n,r))&&sN(t,a)}}}function sN(t,e,n=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&FL(e,n)}function Kje(t,e){const n=Array.isArray(t),r={type_:n?1:0,scope_:e?e.scope_:EZ(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1};let a=r,s=LL;n&&(a=[r],s=Lv);const{revoke:o,proxy:l}=Proxy.revocable(a,s);return r.draft_=l,r.revoke_=o,l}var LL={get(t,e){if(e===Oo)return t;const n=Vm(t);if(!FD(n,e))return Xje(t,n,e);const r=n[e];return t.finalized_||!qf(r)?r:r===cj(t.base_,e)?(uj(t),t.copy_[e]=UD(r,t)):r},has(t,e){return e in Vm(t)},ownKeys(t){return Reflect.ownKeys(Vm(t))},set(t,e,n){const r=jZ(Vm(t),e);if(r?.set)return r.set.call(t.draft_,n),!0;if(!t.modified_){const a=cj(Vm(t),e),s=a?.[Oo];if(s&&s.base_===n)return t.copy_[e]=n,t.assigned_[e]=!1,!0;if($je(n,a)&&(n!==void 0||FD(t.base_,e)))return!0;uj(t),zD(t)}return t.copy_[e]===n&&(n!==void 0||e in t.copy_)||Number.isNaN(n)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=n,t.assigned_[e]=!0),!0},deleteProperty(t,e){return cj(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,uj(t),zD(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){const n=Vm(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},defineProperty(){Hl(11)},getPrototypeOf(t){return Rv(t.base_)},setPrototypeOf(){Hl(12)}},Lv={};aN(LL,(t,e)=>{Lv[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Lv.deleteProperty=function(t,e){return Lv.set.call(this,t,e,void 0)};Lv.set=function(t,e,n){return LL.set.call(this,t[0],e,n,t[0])};function cj(t,e){const n=t[Oo];return(n?Vm(n):t)[e]}function Xje(t,e,n){const r=jZ(e,n);return r?"value"in r?r.value:r.get?.call(t.draft_):void 0}function jZ(t,e){if(!(e in t))return;let n=Rv(t);for(;n;){const r=Object.getOwnPropertyDescriptor(n,e);if(r)return r;n=Rv(n)}}function zD(t){t.modified_||(t.modified_=!0,t.parent_&&zD(t.parent_))}function uj(t){t.copy_||(t.copy_=LD(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var Yje=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,n,r)=>{if(typeof e=="function"&&typeof n!="function"){const s=n;n=e;const o=this;return function(c=s,...u){return o.produce(c,d=>n.call(this,d,...u))}}typeof n!="function"&&Hl(6),r!==void 0&&typeof r!="function"&&Hl(7);let a;if(qf(e)){const s=AV(this),o=UD(e,void 0);let l=!0;try{a=n(o),l=!1}finally{l?OD(s):ID(s)}return kV(s,r),TV(a,s)}else if(!e||typeof e!="object"){if(a=n(e),a===void 0&&(a=e),a===TZ&&(a=void 0),this.autoFreeze_&&FL(a,!0),r){const s=[],o=[];Gf("Patches").generateReplacementPatches_(e,a,s,o),r(s,o)}return a}else Hl(1,e)},this.produceWithPatches=(e,n)=>{if(typeof e=="function")return(o,...l)=>this.produceWithPatches(o,c=>e(c,...l));let r,a;return[this.produce(e,n,(o,l)=>{r=o,a=l}),r,a]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),typeof t?.useStrictIteration=="boolean"&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(t){qf(t)||Hl(8),Nb(t)&&(t=Qje(t));const e=AV(this),n=UD(t,void 0);return n[Oo].isManual_=!0,ID(e),n}finishDraft(t,e){const n=t&&t[Oo];(!n||!n.isManual_)&&Hl(9);const{scope_:r}=n;return kV(r,e),TV(void 0,r)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}setUseStrictIteration(t){this.useStrictIteration_=t}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(t,e){let n;for(n=e.length-1;n>=0;n--){const a=e[n];if(a.path.length===0&&a.op==="replace"){t=a.value;break}}n>-1&&(e=e.slice(n+1));const r=Gf("Patches").applyPatches_;return Nb(t)?r(t,e):this.produce(t,a=>r(a,e))}};function UD(t,e){const n=k0(t)?Gf("MapSet").proxyMap_(t,e):Ek(t)?Gf("MapSet").proxySet_(t,e):Kje(t,e);return(e?e.scope_:EZ()).drafts_.push(n),n}function Qje(t){return Nb(t)||Hl(10,t),DZ(t)}function DZ(t){if(!qf(t)||jk(t))return t;const e=t[Oo];let n,r=!0;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,n=LD(t,e.scope_.immer_.useStrictShallowCopy_),r=e.scope_.immer_.shouldUseStrictIteration()}else n=LD(t,!0);return aN(n,(a,s)=>{PZ(n,a,DZ(s))},r),e&&(e.finalized_=!1),n}var Zje=new Yje;Zje.produce;var Jje={settings:{layout:"horizontal",align:"center",verticalAlign:"middle",itemSorter:"value"},size:{width:0,height:0},payload:[]},RZ=lo({name:"legend",initialState:Jje,reducers:{setLegendSize(t,e){t.size.width=e.payload.width,t.size.height=e.payload.height},setLegendSettings(t,e){t.settings.align=e.payload.align,t.settings.layout=e.payload.layout,t.settings.verticalAlign=e.payload.verticalAlign,t.settings.itemSorter=e.payload.itemSorter},addLegendPayload:{reducer(t,e){t.payload.push(e.payload)},prepare:la()},replaceLegendPayload:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Kl(t).payload.indexOf(n);a>-1&&(t.payload[a]=r)},prepare:la()},removeLegendPayload:{reducer(t,e){var n=Kl(t).payload.indexOf(e.payload);n>-1&&t.payload.splice(n,1)},prepare:la()}}}),{setLegendSize:PV,setLegendSettings:e2e,addLegendPayload:FZ,replaceLegendPayload:LZ,removeLegendPayload:OZ}=RZ.actions,t2e=RZ.reducer,n2e=["contextPayload"];function BD(){return BD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},BD.apply(null,arguments)}function EV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Cb(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?EV(Object(n),!0).forEach(function(r){r2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):EV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function r2e(t,e,n){return(e=a2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function a2e(t){var e=i2e(t,"string");return typeof e=="symbol"?e:e+""}function i2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function s2e(t,e){if(t==null)return{};var n,r,a=o2e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function o2e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function l2e(t){return t.value}function c2e(t){var{contextPayload:e}=t,n=s2e(t,n2e),r=RQ(e,t.payloadUniqBy,l2e),a=Cb(Cb({},n),{},{payload:r});return w.isValidElement(t.content)?w.cloneElement(t.content,a):typeof t.content=="function"?w.createElement(t.content,a):w.createElement(rPe,a)}function u2e(t,e,n,r,a,s){var{layout:o,align:l,verticalAlign:c}=e,u,d;return(!t||(t.left===void 0||t.left===null)&&(t.right===void 0||t.right===null))&&(l==="center"&&o==="vertical"?u={left:((r||0)-s.width)/2}:u=l==="right"?{right:n&&n.right||0}:{left:n&&n.left||0}),(!t||(t.top===void 0||t.top===null)&&(t.bottom===void 0||t.bottom===null))&&(c==="middle"?d={top:((a||0)-s.height)/2}:d=c==="bottom"?{bottom:n&&n.bottom||0}:{top:n&&n.top||0}),Cb(Cb({},u),d)}function d2e(t){var e=qr();return w.useEffect(()=>{e(e2e(t))},[e,t]),null}function h2e(t){var e=qr();return w.useEffect(()=>(e(PV(t)),()=>{e(PV({width:0,height:0}))}),[e,t]),null}function m2e(t,e,n,r){return t==="vertical"&&e!=null?{height:e}:t==="horizontal"?{width:n||r}:null}var f2e={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",layout:"horizontal",verticalAlign:"bottom"};function OL(t){var e=ba(t,f2e),n=XPe(),r=XTe(),a=Uje(),{width:s,height:o,wrapperStyle:l,portal:c}=e,[u,d]=UQ([n]),h=jL(),f=DL();if(h==null||f==null)return null;var p=h-(a?.left||0)-(a?.right||0),x=m2e(e.layout,o,s,p),v=c?l:Cb(Cb({position:"absolute",width:x?.width||s||"auto",height:x?.height||o||"auto"},u2e(l,e,a,h,f,u)),l),g=c??r;if(g==null||n==null)return null;var y=w.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:d},w.createElement(d2e,{layout:e.layout,align:e.align,verticalAlign:e.verticalAlign,itemSorter:e.itemSorter}),!c&&w.createElement(h2e,{width:u.width,height:u.height}),w.createElement(c2e,BD({},e,x,{margin:a,chartWidth:h,chartHeight:f,contextPayload:n})));return Fu.createPortal(y,g)}OL.displayName="Legend";function HD(){return HD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},HD.apply(null,arguments)}function jV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function fy(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?jV(Object(n),!0).forEach(function(r){p2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):jV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function p2e(t,e,n){return(e=g2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function g2e(t){var e=b2e(t,"string");return typeof e=="symbol"?e:e+""}function b2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function x2e(t){return Array.isArray(t)&&_l(t[0])&&_l(t[1])?t.join(" ~ "):t}var wg={separator:" : ",contentStyle:{margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},itemStyle:{display:"block",paddingTop:4,paddingBottom:4,color:"#000"},labelStyle:{},accessibilityLayer:!1},y2e=t=>{var{separator:e=wg.separator,contentStyle:n,itemStyle:r,labelStyle:a=wg.labelStyle,payload:s,formatter:o,itemSorter:l,wrapperClassName:c,labelClassName:u,label:d,labelFormatter:h,accessibilityLayer:f=wg.accessibilityLayer}=t,p=()=>{if(s&&s.length){var A={padding:0,margin:0},M=(l?gk(s,l):s).map((C,j)=>{if(C.type==="none")return null;var P=C.formatter||o||x2e,{value:E,name:U}=C,L=E,B=U;if(P){var D=P(E,U,C,j,s);if(Array.isArray(D))[L,B]=D;else if(D!=null)L=D;else return null}var $=fy(fy({},wg.itemStyle),{},{color:C.color||wg.itemStyle.color},r);return w.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(j),style:$},_l(B)?w.createElement("span",{className:"recharts-tooltip-item-name"},B):null,_l(B)?w.createElement("span",{className:"recharts-tooltip-item-separator"},e):null,w.createElement("span",{className:"recharts-tooltip-item-value"},L),w.createElement("span",{className:"recharts-tooltip-item-unit"},C.unit||""))});return w.createElement("ul",{className:"recharts-tooltip-item-list",style:A},M)}return null},x=fy(fy({},wg.contentStyle),n),v=fy({margin:0},a),g=!ha(d),y=g?d:"",_=ir("recharts-default-tooltip",c),N=ir("recharts-tooltip-label",u);g&&h&&s!==void 0&&s!==null&&(y=h(d,s));var k=f?{role:"status","aria-live":"assertive"}:{};return w.createElement("div",HD({className:_,style:x},k),w.createElement("p",{className:N,style:v},w.isValidElement(y)?y:"".concat(y)),p())},py="recharts-tooltip-wrapper",v2e={visibility:"hidden"};function w2e(t){var{coordinate:e,translateX:n,translateY:r}=t;return ir(py,{["".concat(py,"-right")]:qt(n)&&e&&qt(e.x)&&n>=e.x,["".concat(py,"-left")]:qt(n)&&e&&qt(e.x)&&n<e.x,["".concat(py,"-bottom")]:qt(r)&&e&&qt(e.y)&&r>=e.y,["".concat(py,"-top")]:qt(r)&&e&&qt(e.y)&&r<e.y})}function DV(t){var{allowEscapeViewBox:e,coordinate:n,key:r,offset:a,position:s,reverseDirection:o,tooltipDimension:l,viewBox:c,viewBoxDimension:u}=t;if(s&&qt(s[r]))return s[r];var d=n[r]-l-(a>0?a:0),h=n[r]+a;if(e[r])return o[r]?d:h;var f=c[r];if(f==null)return 0;if(o[r]){var p=d,x=f;return p<x?Math.max(h,f):Math.max(d,f)}if(u==null)return 0;var v=h+l,g=f+u;return v>g?Math.max(d,f):Math.max(h,f)}function S2e(t){var{translateX:e,translateY:n,useTranslate3d:r}=t;return{transform:r?"translate3d(".concat(e,"px, ").concat(n,"px, 0)"):"translate(".concat(e,"px, ").concat(n,"px)")}}function _2e(t){var{allowEscapeViewBox:e,coordinate:n,offsetTop:r,offsetLeft:a,position:s,reverseDirection:o,tooltipBox:l,useTranslate3d:c,viewBox:u}=t,d,h,f;return l.height>0&&l.width>0&&n?(h=DV({allowEscapeViewBox:e,coordinate:n,key:"x",offset:a,position:s,reverseDirection:o,tooltipDimension:l.width,viewBox:u,viewBoxDimension:u.width}),f=DV({allowEscapeViewBox:e,coordinate:n,key:"y",offset:r,position:s,reverseDirection:o,tooltipDimension:l.height,viewBox:u,viewBoxDimension:u.height}),d=S2e({translateX:h,translateY:f,useTranslate3d:c})):d=v2e,{cssProperties:d,cssClasses:w2e({translateX:h,translateY:f,coordinate:n})}}function RV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function m_(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?RV(Object(n),!0).forEach(function(r){$D(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):RV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function $D(t,e,n){return(e=N2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function N2e(t){var e=C2e(t,"string");return typeof e=="symbol"?e:e+""}function C2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class k2e extends w.PureComponent{constructor(){super(...arguments),$D(this,"state",{dismissed:!1,dismissedAtCoordinate:{x:0,y:0}}),$D(this,"handleKeyDown",e=>{if(e.key==="Escape"){var n,r,a,s;this.setState({dismissed:!0,dismissedAtCoordinate:{x:(n=(r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==null&&n!==void 0?n:0,y:(a=(s=this.props.coordinate)===null||s===void 0?void 0:s.y)!==null&&a!==void 0?a:0}})}})}componentDidMount(){document.addEventListener("keydown",this.handleKeyDown)}componentWillUnmount(){document.removeEventListener("keydown",this.handleKeyDown)}componentDidUpdate(){var e,n;this.state.dismissed&&(((e=this.props.coordinate)===null||e===void 0?void 0:e.x)!==this.state.dismissedAtCoordinate.x||((n=this.props.coordinate)===null||n===void 0?void 0:n.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}render(){var{active:e,allowEscapeViewBox:n,animationDuration:r,animationEasing:a,children:s,coordinate:o,hasPayload:l,isAnimationActive:c,offset:u,position:d,reverseDirection:h,useTranslate3d:f,viewBox:p,wrapperStyle:x,lastBoundingBox:v,innerRef:g,hasPortalFromProps:y}=this.props,_=typeof u=="number"?u:u.x,N=typeof u=="number"?u:u.y,{cssClasses:k,cssProperties:A}=_2e({allowEscapeViewBox:n,coordinate:o,offsetLeft:_,offsetTop:N,position:d,reverseDirection:h,tooltipBox:{height:v.height,width:v.width},useTranslate3d:f,viewBox:p}),M=y?{}:m_(m_({transition:c&&e?"transform ".concat(r,"ms ").concat(a):void 0},A),{},{pointerEvents:"none",visibility:!this.state.dismissed&&e&&l?"visible":"hidden",position:"absolute",top:0,left:0}),C=m_(m_({},M),{},{visibility:!this.state.dismissed&&e&&l?"visible":"hidden"},x);return w.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:k,style:C,ref:g},s)}}var IZ=()=>{var t;return(t=Kt(e=>e.rootProps.accessibilityLayer))!==null&&t!==void 0?t:!0};function VD(){return VD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},VD.apply(null,arguments)}function FV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function LV(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?FV(Object(n),!0).forEach(function(r){A2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):FV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function A2e(t,e,n){return(e=T2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function T2e(t){var e=M2e(t,"string");return typeof e=="symbol"?e:e+""}function M2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var OV={curveBasisClosed:fMe,curveBasisOpen:pMe,curveBasis:mMe,curveBumpX:JTe,curveBumpY:eMe,curveLinearClosed:gMe,curveLinear:fk,curveMonotoneX:bMe,curveMonotoneY:xMe,curveNatural:yMe,curveStep:vMe,curveStepAfter:SMe,curveStepBefore:wMe},oN=t=>Nn(t.x)&&Nn(t.y),IV=t=>t.base!=null&&oN(t.base)&&oN(t),gy=t=>t.x,by=t=>t.y,P2e=(t,e)=>{if(typeof t=="function")return t;var n="curve".concat(y0(t));if((n==="curveMonotone"||n==="curveBump")&&e){var r=OV["".concat(n).concat(e==="vertical"?"Y":"X")];if(r)return r}return OV[n]||fk},zV={connectNulls:!1,type:"linear"},E2e=t=>{var{type:e=zV.type,points:n=[],baseLine:r,layout:a,connectNulls:s=zV.connectNulls}=t,o=P2e(e,a),l=s?n.filter(oN):n;if(Array.isArray(r)){var c,u=n.map((x,v)=>LV(LV({},x),{},{base:r[v]}));a==="vertical"?c=i_().y(by).x1(gy).x0(x=>x.base.x):c=i_().x(gy).y1(by).y0(x=>x.base.y);var d=c.defined(IV).curve(o),h=s?u.filter(IV):u;return d(h)}var f;a==="vertical"&&qt(r)?f=i_().y(by).x1(gy).x0(r):qt(r)?f=i_().x(gy).y1(by).y0(r):f=uQ().x(gy).y(by);var p=f.defined(oN).curve(o);return p(l)},nb=t=>{var{className:e,points:n,path:r,pathRef:a}=t,s=nm();if((!n||!n.length)&&!r)return null;var o={type:t.type,points:t.points,baseLine:t.baseLine,layout:t.layout||s,connectNulls:t.connectNulls},l=n&&n.length?E2e(o):r;return w.createElement("path",VD({},Fs(t),yL(t),{className:ir("recharts-curve",e),d:l===null?void 0:l,ref:a}))},j2e=["x","y","top","left","width","height","className"];function qD(){return qD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},qD.apply(null,arguments)}function UV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function D2e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?UV(Object(n),!0).forEach(function(r){R2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):UV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function R2e(t,e,n){return(e=F2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function F2e(t){var e=L2e(t,"string");return typeof e=="symbol"?e:e+""}function L2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function O2e(t,e){if(t==null)return{};var n,r,a=I2e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function I2e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var z2e=(t,e,n,r,a,s)=>"M".concat(t,",").concat(a,"v").concat(r,"M").concat(s,",").concat(e,"h").concat(n),U2e=t=>{var{x:e=0,y:n=0,top:r=0,left:a=0,width:s=0,height:o=0,className:l}=t,c=O2e(t,j2e),u=D2e({x:e,y:n,top:r,left:a,width:s,height:o},c);return!qt(e)||!qt(n)||!qt(s)||!qt(o)||!qt(r)||!qt(a)?null:w.createElement("path",qD({},ts(u),{className:ir("recharts-cross",l),d:z2e(e,n,s,o,r,a)}))};function B2e(t,e,n,r){var a=r/2;return{stroke:"none",fill:"#ccc",x:t==="horizontal"?e.x-a:n.left+.5,y:t==="horizontal"?n.top+.5:e.y-a,width:t==="horizontal"?r:n.width-1,height:t==="horizontal"?n.height-1:r}}function BV(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function HV(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?BV(Object(n),!0).forEach(function(r){H2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):BV(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function H2e(t,e,n){return(e=$2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $2e(t){var e=V2e(t,"string");return typeof e=="symbol"?e:e+""}function V2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var q2e=t=>t.replace(/([A-Z])/g,e=>"-".concat(e.toLowerCase())),zZ=(t,e,n)=>t.map(r=>"".concat(q2e(r)," ").concat(e,"ms ").concat(n)).join(","),G2e=(t,e)=>[Object.keys(t),Object.keys(e)].reduce((n,r)=>n.filter(a=>r.includes(a))),Ov=(t,e)=>Object.keys(e).reduce((n,r)=>HV(HV({},n),{},{[r]:t(r,e[r])}),{});function $V(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ui(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?$V(Object(n),!0).forEach(function(r){W2e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):$V(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function W2e(t,e,n){return(e=K2e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function K2e(t){var e=X2e(t,"string");return typeof e=="symbol"?e:e+""}function X2e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var lN=(t,e,n)=>t+(e-t)*n,GD=t=>{var{from:e,to:n}=t;return e!==n},UZ=(t,e,n)=>{var r=Ov((a,s)=>{if(GD(s)){var[o,l]=t(s.from,s.to,s.velocity);return ui(ui({},s),{},{from:o,velocity:l})}return s},e);return n<1?Ov((a,s)=>GD(s)&&r[a]!=null?ui(ui({},s),{},{velocity:lN(s.velocity,r[a].velocity,n),from:lN(s.from,r[a].from,n)}):s,e):UZ(t,r,n-1)};function Y2e(t,e,n,r,a,s){var o,l=r.reduce((f,p)=>ui(ui({},f),{},{[p]:{from:t[p],velocity:0,to:e[p]}}),{}),c=()=>Ov((f,p)=>p.from,l),u=()=>!Object.values(l).filter(GD).length,d=null,h=f=>{o||(o=f);var p=f-o,x=p/n.dt;l=UZ(n,l,x),a(ui(ui(ui({},t),e),c())),o=f,u()||(d=s.setTimeout(h))};return()=>(d=s.setTimeout(h),()=>{var f;(f=d)===null||f===void 0||f()})}function Q2e(t,e,n,r,a,s,o){var l=null,c=a.reduce((h,f)=>{var p=t[f],x=e[f];return p==null||x==null?h:ui(ui({},h),{},{[f]:[p,x]})},{}),u,d=h=>{u||(u=h);var f=(h-u)/r,p=Ov((v,g)=>lN(...g,n(f)),c);if(s(ui(ui(ui({},t),e),p)),f<1)l=o.setTimeout(d);else{var x=Ov((v,g)=>lN(...g,n(1)),c);s(ui(ui(ui({},t),e),x))}};return()=>(l=o.setTimeout(d),()=>{var h;(h=l)===null||h===void 0||h()})}const Z2e=(t,e,n,r,a,s)=>{var o=G2e(t,e);return n==null?()=>(a(ui(ui({},t),e)),()=>{}):n.isStepper===!0?Y2e(t,e,n,o,a,s):Q2e(t,e,n,r,o,a,s)};var cN=1e-4,BZ=(t,e)=>[0,3*t,3*e-6*t,3*t-3*e+1],HZ=(t,e)=>t.map((n,r)=>n*e**r).reduce((n,r)=>n+r),VV=(t,e)=>n=>{var r=BZ(t,e);return HZ(r,n)},J2e=(t,e)=>n=>{var r=BZ(t,e),a=[...r.map((s,o)=>s*o).slice(1),0];return HZ(a,n)},e3e=t=>{var e,n=t.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var r=(e=n[1])===null||e===void 0||(e=e.split(")")[0])===null||e===void 0?void 0:e.split(",");if(r==null||r.length!==4)return null;var a=r.map(s=>parseFloat(s));return[a[0],a[1],a[2],a[3]]},t3e=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];if(n.length===1)switch(n[0]){case"linear":return[0,0,1,1];case"ease":return[.25,.1,.25,1];case"ease-in":return[.42,0,1,1];case"ease-out":return[.42,0,.58,1];case"ease-in-out":return[0,0,.58,1];default:{var a=e3e(n[0]);if(a)return a}}return n.length===4?n:[0,0,1,1]},n3e=(t,e,n,r)=>{var a=VV(t,n),s=VV(e,r),o=J2e(t,n),l=u=>u>1?1:u<0?0:u,c=u=>{for(var d=u>1?1:u,h=d,f=0;f<8;++f){var p=a(h)-d,x=o(h);if(Math.abs(p-d)<cN||x<cN)return s(h);h=l(h-p/x)}return s(h)};return c.isStepper=!1,c},qV=function(){return n3e(...t3e(...arguments))},r3e=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{stiff:n=100,damping:r=8,dt:a=17}=e,s=(o,l,c)=>{var u=-(o-l)*n,d=c*r,h=c+(u-d)*a/1e3,f=c*a/1e3+o;return Math.abs(f-l)<cN&&Math.abs(h)<cN?[l,0]:[f,h]};return s.isStepper=!0,s.dt=a,s},a3e=t=>{if(typeof t=="string")switch(t){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return qV(t);case"spring":return r3e();default:if(t.split("(")[0]==="cubic-bezier")return qV(t)}return typeof t=="function"?t:null};function i3e(t){var e,n=()=>null,r=!1,a=null,s=o=>{if(!r){if(Array.isArray(o)){if(!o.length)return;var l=o,[c,...u]=l;if(typeof c=="number"){a=t.setTimeout(s.bind(null,u),c);return}s(c),a=t.setTimeout(s.bind(null,u));return}typeof o=="string"&&(e=o,n(e)),typeof o=="object"&&(e=o,n(e)),typeof o=="function"&&o()}};return{stop:()=>{r=!0},start:o=>{r=!1,a&&(a(),a=null),s(o)},subscribe:o=>(n=o,()=>{n=()=>null}),getTimeoutController:()=>t}}class s3e{setTimeout(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),a=null,s=o=>{o-r>=n?e(o):typeof requestAnimationFrame=="function"&&(a=requestAnimationFrame(s))};return a=requestAnimationFrame(s),()=>{a!=null&&cancelAnimationFrame(a)}}}function o3e(){return i3e(new s3e)}var l3e=w.createContext(o3e);function c3e(t,e){var n=w.useContext(l3e);return w.useMemo(()=>e??n(t),[t,e,n])}var u3e=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),A0={isSsr:u3e()},d3e={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},GV={t:0},dj={t:1};function Qb(t){var e=ba(t,d3e),{isActive:n,canBegin:r,duration:a,easing:s,begin:o,onAnimationEnd:l,onAnimationStart:c,children:u}=e,d=n==="auto"?!A0.isSsr:n,h=c3e(e.animationId,e.animationManager),[f,p]=w.useState(d?GV:dj),x=w.useRef(null);return w.useEffect(()=>{d||p(dj)},[d]),w.useEffect(()=>{if(!d||!r)return em;var v=Z2e(GV,dj,a3e(s),a,p,h.getTimeoutController()),g=()=>{x.current=v()};return h.start([c,o,g,a,l]),()=>{h.stop(),x.current&&x.current(),l()}},[d,r,a,s,o,c,l,h]),u(f.t)}function Zb(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=w.useRef(Pv(e)),r=w.useRef(t);return r.current!==t&&(n.current=Pv(e),r.current=t),n.current}var h3e=["radius"],m3e=["radius"],WV,KV,XV,YV,QV,ZV,JV,eq,tq,nq;function rq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function aq(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rq(Object(n),!0).forEach(function(r){f3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rq(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function f3e(t,e,n){return(e=p3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function p3e(t){var e=g3e(t,"string");return typeof e=="symbol"?e:e+""}function g3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function uN(){return uN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},uN.apply(null,arguments)}function iq(t,e){if(t==null)return{};var n,r,a=b3e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function b3e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function pc(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var sq=(t,e,n,r,a)=>{var s=_h(n),o=_h(r),l=Math.min(Math.abs(s)/2,Math.abs(o)/2),c=o>=0?1:-1,u=s>=0?1:-1,d=o>=0&&s>=0||o<0&&s<0?1:0,h;if(l>0&&Array.isArray(a)){for(var f=[0,0,0,0],p=0,x=4;p<x;p++){var v,g=(v=a[p])!==null&&v!==void 0?v:0;f[p]=g>l?l:g}h=Ta(WV||(WV=pc(["M",",",""])),t,e+c*f[0]),f[0]>0&&(h+=Ta(KV||(KV=pc(["A ",",",",0,0,",",",",",""])),f[0],f[0],d,t+u*f[0],e)),h+=Ta(XV||(XV=pc(["L ",",",""])),t+n-u*f[1],e),f[1]>0&&(h+=Ta(YV||(YV=pc(["A ",",",",0,0,",`,
  8074. `,",",""])),f[1],f[1],d,t+n,e+c*f[1])),h+=Ta(QV||(QV=pc(["L ",",",""])),t+n,e+r-c*f[2]),f[2]>0&&(h+=Ta(ZV||(ZV=pc(["A ",",",",0,0,",`,
  8075. `,",",""])),f[2],f[2],d,t+n-u*f[2],e+r)),h+=Ta(JV||(JV=pc(["L ",",",""])),t+u*f[3],e+r),f[3]>0&&(h+=Ta(eq||(eq=pc(["A ",",",",0,0,",`,
  8076. `,",",""])),f[3],f[3],d,t,e+r-c*f[3])),h+="Z"}else if(l>0&&a===+a&&a>0){var y=Math.min(l,a);h=Ta(tq||(tq=pc(["M ",",",`
  8077. A `,",",",0,0,",",",",",`
  8078. L `,",",`
  8079. A `,",",",0,0,",",",",",`
  8080. L `,",",`
  8081. A `,",",",0,0,",",",",",`
  8082. L `,",",`
  8083. A `,",",",0,0,",",",","," Z"])),t,e+c*y,y,y,d,t+u*y,e,t+n-u*y,e,y,y,d,t+n,e+c*y,t+n,e+r-c*y,y,y,d,t+n-u*y,e+r,t+u*y,e+r,y,y,d,t,e+r-c*y)}else h=Ta(nq||(nq=pc(["M ",","," h "," v "," h "," Z"])),t,e,n,r,-n);return h},oq={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},$Z=t=>{var e=ba(t,oq),n=w.useRef(null),[r,a]=w.useState(-1);w.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var z=n.current.getTotalLength();z&&a(z)}catch{}},[]);var{x:s,y:o,width:l,height:c,radius:u,className:d}=e,{animationEasing:h,animationDuration:f,animationBegin:p,isAnimationActive:x,isUpdateAnimationActive:v}=e,g=w.useRef(l),y=w.useRef(c),_=w.useRef(s),N=w.useRef(o),k=w.useMemo(()=>({x:s,y:o,width:l,height:c,radius:u}),[s,o,l,c,u]),A=Zb(k,"rectangle-");if(s!==+s||o!==+o||l!==+l||c!==+c||l===0||c===0)return null;var M=ir("recharts-rectangle",d);if(!v){var C=ts(e),{radius:j}=C,P=iq(C,h3e);return w.createElement("path",uN({},P,{x:_h(s),y:_h(o),width:_h(l),height:_h(c),radius:typeof u=="number"?u:void 0,className:M,d:sq(s,o,l,c,u)}))}var E=g.current,U=y.current,L=_.current,B=N.current,D="0px ".concat(r===-1?1:r,"px"),$="".concat(r,"px 0px"),G=zZ(["strokeDasharray"],f,typeof h=="string"?h:oq.animationEasing);return w.createElement(Qb,{animationId:A,key:A,canBegin:r>0,duration:f,easing:h,isActive:v,begin:p},z=>{var W=br(E,l,z),X=br(U,c,z),ae=br(L,s,z),H=br(B,o,z);n.current&&(g.current=W,y.current=X,_.current=ae,N.current=H);var K;x?z>0?K={transition:G,strokeDasharray:$}:K={strokeDasharray:D}:K={strokeDasharray:$};var te=ts(e),{radius:Z}=te,ve=iq(te,m3e);return w.createElement("path",uN({},ve,{radius:typeof u=="number"?u:void 0,className:M,d:sq(ae,H,W,X,u),ref:n,style:aq(aq({},K),e.style)}))})};function lq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function cq(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?lq(Object(n),!0).forEach(function(r){x3e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lq(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function x3e(t,e,n){return(e=y3e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function y3e(t){var e=v3e(t,"string");return typeof e=="symbol"?e:e+""}function v3e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var dN=Math.PI/180,w3e=t=>t*180/Math.PI,ei=(t,e,n,r)=>({x:t+Math.cos(-dN*r)*n,y:e+Math.sin(-dN*r)*n}),VZ=function(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},S3e=(t,e)=>{var{x:n,y:r}=t,{x:a,y:s}=e;return Math.sqrt((n-a)**2+(r-s)**2)},_3e=(t,e)=>{var{x:n,y:r}=t,{cx:a,cy:s}=e,o=S3e({x:n,y:r},{x:a,y:s});if(o<=0)return{radius:o,angle:0};var l=(n-a)/o,c=Math.acos(l);return r>s&&(c=2*Math.PI-c),{radius:o,angle:w3e(c),angleInRadian:c}},N3e=t=>{var{startAngle:e,endAngle:n}=t,r=Math.floor(e/360),a=Math.floor(n/360),s=Math.min(r,a);return{startAngle:e-s*360,endAngle:n-s*360}},C3e=(t,e)=>{var{startAngle:n,endAngle:r}=e,a=Math.floor(n/360),s=Math.floor(r/360),o=Math.min(a,s);return t+o*360},k3e=(t,e)=>{var{chartX:n,chartY:r}=t,{radius:a,angle:s}=_3e({x:n,y:r},e),{innerRadius:o,outerRadius:l}=e;if(a<o||a>l||a===0)return null;var{startAngle:c,endAngle:u}=N3e(e),d=s,h;if(c<=u){for(;d>u;)d-=360;for(;d<c;)d+=360;h=d>=c&&d<=u}else{for(;d>c;)d-=360;for(;d<u;)d+=360;h=d>=u&&d<=c}return h?cq(cq({},e),{},{radius:a,angle:C3e(d,e)}):null};function qZ(t){var{cx:e,cy:n,radius:r,startAngle:a,endAngle:s}=t,o=ei(e,n,r,a),l=ei(e,n,r,s);return{points:[o,l],cx:e,cy:n,radius:r,startAngle:a,endAngle:s}}var uq,dq,hq,mq,fq,pq,gq;function WD(){return WD=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},WD.apply(null,arguments)}function nf(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var A3e=(t,e)=>{var n=Ri(e-t),r=Math.min(Math.abs(e-t),359.999);return n*r},f_=t=>{var{cx:e,cy:n,radius:r,angle:a,sign:s,isExternal:o,cornerRadius:l,cornerIsExternal:c}=t,u=l*(o?1:-1)+r,d=Math.asin(l/u)/dN,h=c?a:a+s*d,f=ei(e,n,u,h),p=ei(e,n,r,h),x=c?a-s*d:a,v=ei(e,n,u*Math.cos(d*dN),x);return{center:f,circleTangency:p,lineTangency:v,theta:d}},GZ=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:a,startAngle:s,endAngle:o}=t,l=A3e(s,o),c=s+l,u=ei(e,n,a,s),d=ei(e,n,a,c),h=Ta(uq||(uq=nf(["M ",",",`
  8084. A `,",",`,0,
  8085. `,",",`,
  8086. `,",",`
  8087. `])),u.x,u.y,a,a,+(Math.abs(l)>180),+(s>c),d.x,d.y);if(r>0){var f=ei(e,n,r,s),p=ei(e,n,r,c);h+=Ta(dq||(dq=nf(["L ",",",`
  8088. A `,",",`,0,
  8089. `,",",`,
  8090. `,","," Z"])),p.x,p.y,r,r,+(Math.abs(l)>180),+(s<=c),f.x,f.y)}else h+=Ta(hq||(hq=nf(["L ",","," Z"])),e,n);return h},T3e=t=>{var{cx:e,cy:n,innerRadius:r,outerRadius:a,cornerRadius:s,forceCornerRadius:o,cornerIsExternal:l,startAngle:c,endAngle:u}=t,d=Ri(u-c),{circleTangency:h,lineTangency:f,theta:p}=f_({cx:e,cy:n,radius:a,angle:c,sign:d,cornerRadius:s,cornerIsExternal:l}),{circleTangency:x,lineTangency:v,theta:g}=f_({cx:e,cy:n,radius:a,angle:u,sign:-d,cornerRadius:s,cornerIsExternal:l}),y=l?Math.abs(c-u):Math.abs(c-u)-p-g;if(y<0)return o?Ta(mq||(mq=nf(["M ",",",`
  8091. a`,",",",0,0,1,",`,0
  8092. a`,",",",0,0,1,",`,0
  8093. `])),f.x,f.y,s,s,s*2,s,s,-s*2):GZ({cx:e,cy:n,innerRadius:r,outerRadius:a,startAngle:c,endAngle:u});var _=Ta(fq||(fq=nf(["M ",",",`
  8094. A`,",",",0,0,",",",",",`
  8095. A`,",",",0,",",",",",",",`
  8096. A`,",",",0,0,",",",",",`
  8097. `])),f.x,f.y,s,s,+(d<0),h.x,h.y,a,a,+(y>180),+(d<0),x.x,x.y,s,s,+(d<0),v.x,v.y);if(r>0){var{circleTangency:N,lineTangency:k,theta:A}=f_({cx:e,cy:n,radius:r,angle:c,sign:d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),{circleTangency:M,lineTangency:C,theta:j}=f_({cx:e,cy:n,radius:r,angle:u,sign:-d,isExternal:!0,cornerRadius:s,cornerIsExternal:l}),P=l?Math.abs(c-u):Math.abs(c-u)-A-j;if(P<0&&s===0)return"".concat(_,"L").concat(e,",").concat(n,"Z");_+=Ta(pq||(pq=nf(["L",",",`
  8098. A`,",",",0,0,",",",",",`
  8099. A`,",",",0,",",",",",",",`
  8100. A`,",",",0,0,",",",",","Z"])),C.x,C.y,s,s,+(d<0),M.x,M.y,r,r,+(P>180),+(d>0),N.x,N.y,s,s,+(d<0),k.x,k.y)}else _+=Ta(gq||(gq=nf(["L",",","Z"])),e,n);return _},M3e={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},WZ=t=>{var e=ba(t,M3e),{cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:o,forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d,className:h}=e;if(s<a||u===d)return null;var f=ir("recharts-sector",h),p=s-a,x=bs(o,p,0,!0),v;return x>0&&Math.abs(u-d)<360?v=T3e({cx:n,cy:r,innerRadius:a,outerRadius:s,cornerRadius:Math.min(x,p/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):v=GZ({cx:n,cy:r,innerRadius:a,outerRadius:s,startAngle:u,endAngle:d}),w.createElement("path",WD({},ts(e),{className:f,d:v}))};function P3e(t,e,n){if(t==="horizontal")return[{x:e.x,y:n.top},{x:e.x,y:n.top+n.height}];if(t==="vertical")return[{x:n.left,y:e.y},{x:n.left+n.width,y:e.y}];if(CQ(e)){if(t==="centric"){var{cx:r,cy:a,innerRadius:s,outerRadius:o,angle:l}=e,c=ei(r,a,s,l),u=ei(r,a,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return qZ(e)}}var hj={},mj={},fj={},bq;function E3e(){return bq||(bq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=OQ();function n(r){return e.isSymbol(r)?NaN:Number(r)}t.toNumber=n})(fj)),fj}var xq;function j3e(){return xq||(xq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=E3e();function n(r){return r?(r=e.toNumber(r),r===1/0||r===-1/0?(r<0?-1:1)*Number.MAX_VALUE:r===r?r:0):r===0?r:0}t.toFinite=n})(mj)),mj}var yq;function D3e(){return yq||(yq=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=IQ(),n=j3e();function r(a,s,o){o&&typeof o!="number"&&e.isIterateeCall(a,s,o)&&(s=o=void 0),a=n.toFinite(a),s===void 0?(s=a,a=0):s=n.toFinite(s),o=o===void 0?a<s?1:-1:n.toFinite(o);const l=Math.max(Math.ceil((s-a)/(o||1)),0),c=new Array(l);for(let u=0;u<l;u++)c[u]=a,a+=o;return c}t.range=r})(hj)),hj}var pj,vq;function R3e(){return vq||(vq=1,pj=D3e().range),pj}var F3e=R3e();const KZ=nc(F3e);function Ih(t,e){return t==null||e==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function L3e(t,e){return t==null||e==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function IL(t){let e,n,r;t.length!==2?(e=Ih,n=(l,c)=>Ih(t(l),c),r=(l,c)=>t(l)-c):(e=t===Ih||t===L3e?t:O3e,n=t,r=t);function a(l,c,u=0,d=l.length){if(u<d){if(e(c,c)!==0)return d;do{const h=u+d>>>1;n(l[h],c)<0?u=h+1:d=h}while(u<d)}return u}function s(l,c,u=0,d=l.length){if(u<d){if(e(c,c)!==0)return d;do{const h=u+d>>>1;n(l[h],c)<=0?u=h+1:d=h}while(u<d)}return u}function o(l,c,u=0,d=l.length){const h=a(l,c,u,d-1);return h>u&&r(l[h-1],c)>-r(l[h],c)?h-1:h}return{left:a,center:o,right:s}}function O3e(){return 0}function XZ(t){return t===null?NaN:+t}function*I3e(t,e){for(let n of t)n!=null&&(n=+n)>=n&&(yield n)}const z3e=IL(Ih),T0=z3e.right;IL(XZ).center;class wq extends Map{constructor(e,n=H3e){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),e!=null)for(const[r,a]of e)this.set(r,a)}get(e){return super.get(Sq(this,e))}has(e){return super.has(Sq(this,e))}set(e,n){return super.set(U3e(this,e),n)}delete(e){return super.delete(B3e(this,e))}}function Sq({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function U3e({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function B3e({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function H3e(t){return t!==null&&typeof t=="object"?t.valueOf():t}function $3e(t=Ih){if(t===Ih)return YZ;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,n)=>{const r=t(e,n);return r||r===0?r:(t(n,n)===0)-(t(e,e)===0)}}function YZ(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(t<e?-1:t>e?1:0)}const V3e=Math.sqrt(50),q3e=Math.sqrt(10),G3e=Math.sqrt(2);function hN(t,e,n){const r=(e-t)/Math.max(0,n),a=Math.floor(Math.log10(r)),s=r/Math.pow(10,a),o=s>=V3e?10:s>=q3e?5:s>=G3e?2:1;let l,c,u;return a<0?(u=Math.pow(10,-a)/o,l=Math.round(t*u),c=Math.round(e*u),l/u<t&&++l,c/u>e&&--c,u=-u):(u=Math.pow(10,a)*o,l=Math.round(t/u),c=Math.round(e/u),l*u<t&&++l,c*u>e&&--c),c<l&&.5<=n&&n<2?hN(t,e,n*2):[l,c,u]}function KD(t,e,n){if(e=+e,t=+t,n=+n,!(n>0))return[];if(t===e)return[t];const r=e<t,[a,s,o]=r?hN(e,t,n):hN(t,e,n);if(!(s>=a))return[];const l=s-a+1,c=new Array(l);if(r)if(o<0)for(let u=0;u<l;++u)c[u]=(s-u)/-o;else for(let u=0;u<l;++u)c[u]=(s-u)*o;else if(o<0)for(let u=0;u<l;++u)c[u]=(a+u)/-o;else for(let u=0;u<l;++u)c[u]=(a+u)*o;return c}function XD(t,e,n){return e=+e,t=+t,n=+n,hN(t,e,n)[2]}function YD(t,e,n){e=+e,t=+t,n=+n;const r=e<t,a=r?XD(e,t,n):XD(t,e,n);return(r?-1:1)*(a<0?1/-a:a)}function _q(t,e){let n;for(const r of t)r!=null&&(n<r||n===void 0&&r>=r)&&(n=r);return n}function Nq(t,e){let n;for(const r of t)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function QZ(t,e,n=0,r=1/0,a){if(e=Math.floor(e),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(t.length-1,r)),!(n<=e&&e<=r))return t;for(a=a===void 0?YZ:$3e(a);r>n;){if(r-n>600){const c=r-n+1,u=e-n+1,d=Math.log(c),h=.5*Math.exp(2*d/3),f=.5*Math.sqrt(d*h*(c-h)/c)*(u-c/2<0?-1:1),p=Math.max(n,Math.floor(e-u*h/c+f)),x=Math.min(r,Math.floor(e+(c-u)*h/c+f));QZ(t,e,p,x,a)}const s=t[e];let o=n,l=r;for(xy(t,n,e),a(t[r],s)>0&&xy(t,n,r);o<l;){for(xy(t,o,l),++o,--l;a(t[o],s)<0;)++o;for(;a(t[l],s)>0;)--l}a(t[n],s)===0?xy(t,n,l):(++l,xy(t,l,r)),l<=e&&(n=l+1),e<=l&&(r=l-1)}return t}function xy(t,e,n){const r=t[e];t[e]=t[n],t[n]=r}function W3e(t,e,n){if(t=Float64Array.from(I3e(t)),!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return Nq(t);if(e>=1)return _q(t);var r,a=(r-1)*e,s=Math.floor(a),o=_q(QZ(t,s).subarray(0,s+1)),l=Nq(t.subarray(s+1));return o+(l-o)*(a-s)}}function K3e(t,e,n=XZ){if(!(!(r=t.length)||isNaN(e=+e))){if(e<=0||r<2)return+n(t[0],0,t);if(e>=1)return+n(t[r-1],r-1,t);var r,a=(r-1)*e,s=Math.floor(a),o=+n(t[s],s,t),l=+n(t[s+1],s+1,t);return o+(l-o)*(a-s)}}function X3e(t,e,n){t=+t,e=+e,n=(a=arguments.length)<2?(e=t,t=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((e-t)/n))|0,s=new Array(a);++r<a;)s[r]=t+r*n;return s}function Al(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}function gd(t,e){switch(arguments.length){case 0:break;case 1:{typeof t=="function"?this.interpolator(t):this.range(t);break}default:{this.domain(t),typeof e=="function"?this.interpolator(e):this.range(e);break}}return this}const QD=Symbol("implicit");function zL(){var t=new wq,e=[],n=[],r=QD;function a(s){let o=t.get(s);if(o===void 0){if(r!==QD)return r;t.set(s,o=e.push(s)-1)}return n[o%n.length]}return a.domain=function(s){if(!arguments.length)return e.slice();e=[],t=new wq;for(const o of s)t.has(o)||t.set(o,e.push(o)-1);return a},a.range=function(s){return arguments.length?(n=Array.from(s),a):n.slice()},a.unknown=function(s){return arguments.length?(r=s,a):r},a.copy=function(){return zL(e,n).unknown(r)},Al.apply(a,arguments),a}function UL(){var t=zL().unknown(void 0),e=t.domain,n=t.range,r=0,a=1,s,o,l=!1,c=0,u=0,d=.5;delete t.unknown;function h(){var f=e().length,p=a<r,x=p?a:r,v=p?r:a;s=(v-x)/Math.max(1,f-c+u*2),l&&(s=Math.floor(s)),x+=(v-x-s*(f-c))*d,o=s*(1-c),l&&(x=Math.round(x),o=Math.round(o));var g=X3e(f).map(function(y){return x+s*y});return n(p?g.reverse():g)}return t.domain=function(f){return arguments.length?(e(f),h()):e()},t.range=function(f){return arguments.length?([r,a]=f,r=+r,a=+a,h()):[r,a]},t.rangeRound=function(f){return[r,a]=f,r=+r,a=+a,l=!0,h()},t.bandwidth=function(){return o},t.step=function(){return s},t.round=function(f){return arguments.length?(l=!!f,h()):l},t.padding=function(f){return arguments.length?(c=Math.min(1,u=+f),h()):c},t.paddingInner=function(f){return arguments.length?(c=Math.min(1,f),h()):c},t.paddingOuter=function(f){return arguments.length?(u=+f,h()):u},t.align=function(f){return arguments.length?(d=Math.max(0,Math.min(1,f)),h()):d},t.copy=function(){return UL(e(),[r,a]).round(l).paddingInner(c).paddingOuter(u).align(d)},Al.apply(h(),arguments)}function ZZ(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return ZZ(e())},t}function Y3e(){return ZZ(UL.apply(null,arguments).paddingInner(1))}function BL(t,e,n){t.prototype=e.prototype=n,n.constructor=t}function JZ(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}function M0(){}var Iv=.7,mN=1/Iv,rb="\\s*([+-]?\\d+)\\s*",zv="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Rc="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Q3e=/^#([0-9a-f]{3,8})$/,Z3e=new RegExp(`^rgb\\(${rb},${rb},${rb}\\)$`),J3e=new RegExp(`^rgb\\(${Rc},${Rc},${Rc}\\)$`),eDe=new RegExp(`^rgba\\(${rb},${rb},${rb},${zv}\\)$`),tDe=new RegExp(`^rgba\\(${Rc},${Rc},${Rc},${zv}\\)$`),nDe=new RegExp(`^hsl\\(${zv},${Rc},${Rc}\\)$`),rDe=new RegExp(`^hsla\\(${zv},${Rc},${Rc},${zv}\\)$`),Cq={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};BL(M0,Uv,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:kq,formatHex:kq,formatHex8:aDe,formatHsl:iDe,formatRgb:Aq,toString:Aq});function kq(){return this.rgb().formatHex()}function aDe(){return this.rgb().formatHex8()}function iDe(){return eJ(this).formatHsl()}function Aq(){return this.rgb().formatRgb()}function Uv(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=Q3e.exec(t))?(n=e[1].length,e=parseInt(e[1],16),n===6?Tq(e):n===3?new eo(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):n===8?p_(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):n===4?p_(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=Z3e.exec(t))?new eo(e[1],e[2],e[3],1):(e=J3e.exec(t))?new eo(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=eDe.exec(t))?p_(e[1],e[2],e[3],e[4]):(e=tDe.exec(t))?p_(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=nDe.exec(t))?Eq(e[1],e[2]/100,e[3]/100,1):(e=rDe.exec(t))?Eq(e[1],e[2]/100,e[3]/100,e[4]):Cq.hasOwnProperty(t)?Tq(Cq[t]):t==="transparent"?new eo(NaN,NaN,NaN,0):null}function Tq(t){return new eo(t>>16&255,t>>8&255,t&255,1)}function p_(t,e,n,r){return r<=0&&(t=e=n=NaN),new eo(t,e,n,r)}function sDe(t){return t instanceof M0||(t=Uv(t)),t?(t=t.rgb(),new eo(t.r,t.g,t.b,t.opacity)):new eo}function ZD(t,e,n,r){return arguments.length===1?sDe(t):new eo(t,e,n,r??1)}function eo(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}BL(eo,ZD,JZ(M0,{brighter(t){return t=t==null?mN:Math.pow(mN,t),new eo(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Iv:Math.pow(Iv,t),new eo(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new eo(bf(this.r),bf(this.g),bf(this.b),fN(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Mq,formatHex:Mq,formatHex8:oDe,formatRgb:Pq,toString:Pq}));function Mq(){return`#${rf(this.r)}${rf(this.g)}${rf(this.b)}`}function oDe(){return`#${rf(this.r)}${rf(this.g)}${rf(this.b)}${rf((isNaN(this.opacity)?1:this.opacity)*255)}`}function Pq(){const t=fN(this.opacity);return`${t===1?"rgb(":"rgba("}${bf(this.r)}, ${bf(this.g)}, ${bf(this.b)}${t===1?")":`, ${t})`}`}function fN(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function bf(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function rf(t){return t=bf(t),(t<16?"0":"")+t.toString(16)}function Eq(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new $l(t,e,n,r)}function eJ(t){if(t instanceof $l)return new $l(t.h,t.s,t.l,t.opacity);if(t instanceof M0||(t=Uv(t)),!t)return new $l;if(t instanceof $l)return t;t=t.rgb();var e=t.r/255,n=t.g/255,r=t.b/255,a=Math.min(e,n,r),s=Math.max(e,n,r),o=NaN,l=s-a,c=(s+a)/2;return l?(e===s?o=(n-r)/l+(n<r)*6:n===s?o=(r-e)/l+2:o=(e-n)/l+4,l/=c<.5?s+a:2-s-a,o*=60):l=c>0&&c<1?0:o,new $l(o,l,c,t.opacity)}function lDe(t,e,n,r){return arguments.length===1?eJ(t):new $l(t,e,n,r??1)}function $l(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}BL($l,lDe,JZ(M0,{brighter(t){return t=t==null?mN:Math.pow(mN,t),new $l(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Iv:Math.pow(Iv,t),new $l(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,a=2*n-r;return new eo(gj(t>=240?t-240:t+120,a,r),gj(t,a,r),gj(t<120?t+240:t-120,a,r),this.opacity)},clamp(){return new $l(jq(this.h),g_(this.s),g_(this.l),fN(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=fN(this.opacity);return`${t===1?"hsl(":"hsla("}${jq(this.h)}, ${g_(this.s)*100}%, ${g_(this.l)*100}%${t===1?")":`, ${t})`}`}}));function jq(t){return t=(t||0)%360,t<0?t+360:t}function g_(t){return Math.max(0,Math.min(1,t||0))}function gj(t,e,n){return(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)*255}const HL=t=>()=>t;function cDe(t,e){return function(n){return t+n*e}}function uDe(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}function dDe(t){return(t=+t)==1?tJ:function(e,n){return n-e?uDe(e,n,t):HL(isNaN(e)?n:e)}}function tJ(t,e){var n=e-t;return n?cDe(t,n):HL(isNaN(t)?e:t)}const Dq=(function t(e){var n=dDe(e);function r(a,s){var o=n((a=ZD(a)).r,(s=ZD(s)).r),l=n(a.g,s.g),c=n(a.b,s.b),u=tJ(a.opacity,s.opacity);return function(d){return a.r=o(d),a.g=l(d),a.b=c(d),a.opacity=u(d),a+""}}return r.gamma=t,r})(1);function hDe(t,e){e||(e=[]);var n=t?Math.min(e.length,t.length):0,r=e.slice(),a;return function(s){for(a=0;a<n;++a)r[a]=t[a]*(1-s)+e[a]*s;return r}}function mDe(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fDe(t,e){var n=e?e.length:0,r=t?Math.min(n,t.length):0,a=new Array(r),s=new Array(n),o;for(o=0;o<r;++o)a[o]=Jb(t[o],e[o]);for(;o<n;++o)s[o]=e[o];return function(l){for(o=0;o<r;++o)s[o]=a[o](l);return s}}function pDe(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}function pN(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}function gDe(t,e){var n={},r={},a;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(a in e)a in t?n[a]=Jb(t[a],e[a]):r[a]=e[a];return function(s){for(a in n)r[a]=n[a](s);return r}}var JD=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,bj=new RegExp(JD.source,"g");function bDe(t){return function(){return t}}function xDe(t){return function(e){return t(e)+""}}function yDe(t,e){var n=JD.lastIndex=bj.lastIndex=0,r,a,s,o=-1,l=[],c=[];for(t=t+"",e=e+"";(r=JD.exec(t))&&(a=bj.exec(e));)(s=a.index)>n&&(s=e.slice(n,s),l[o]?l[o]+=s:l[++o]=s),(r=r[0])===(a=a[0])?l[o]?l[o]+=a:l[++o]=a:(l[++o]=null,c.push({i:o,x:pN(r,a)})),n=bj.lastIndex;return n<e.length&&(s=e.slice(n),l[o]?l[o]+=s:l[++o]=s),l.length<2?c[0]?xDe(c[0].x):bDe(e):(e=c.length,function(u){for(var d=0,h;d<e;++d)l[(h=c[d]).i]=h.x(u);return l.join("")})}function Jb(t,e){var n=typeof e,r;return e==null||n==="boolean"?HL(e):(n==="number"?pN:n==="string"?(r=Uv(e))?(e=r,Dq):yDe:e instanceof Uv?Dq:e instanceof Date?pDe:mDe(e)?hDe:Array.isArray(e)?fDe:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?gDe:pN)(t,e)}function $L(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}function vDe(t,e){e===void 0&&(e=t,t=Jb);for(var n=0,r=e.length-1,a=e[0],s=new Array(r<0?0:r);n<r;)s[n]=t(a,a=e[++n]);return function(o){var l=Math.max(0,Math.min(r-1,Math.floor(o*=r)));return s[l](o-l)}}function wDe(t){return function(){return t}}function gN(t){return+t}var Rq=[0,1];function Ps(t){return t}function eR(t,e){return(e-=t=+t)?function(n){return(n-t)/e}:wDe(isNaN(e)?NaN:.5)}function SDe(t,e){var n;return t>e&&(n=t,t=e,e=n),function(r){return Math.max(t,Math.min(e,r))}}function _De(t,e,n){var r=t[0],a=t[1],s=e[0],o=e[1];return a<r?(r=eR(a,r),s=n(o,s)):(r=eR(r,a),s=n(s,o)),function(l){return s(r(l))}}function NDe(t,e,n){var r=Math.min(t.length,e.length)-1,a=new Array(r),s=new Array(r),o=-1;for(t[r]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<r;)a[o]=eR(t[o],t[o+1]),s[o]=n(e[o],e[o+1]);return function(l){var c=T0(t,l,1,r)-1;return s[c](a[c](l))}}function P0(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function Dk(){var t=Rq,e=Rq,n=Jb,r,a,s,o=Ps,l,c,u;function d(){var f=Math.min(t.length,e.length);return o!==Ps&&(o=SDe(t[0],t[f-1])),l=f>2?NDe:_De,c=u=null,h}function h(f){return f==null||isNaN(f=+f)?s:(c||(c=l(t.map(r),e,n)))(r(o(f)))}return h.invert=function(f){return o(a((u||(u=l(e,t.map(r),pN)))(f)))},h.domain=function(f){return arguments.length?(t=Array.from(f,gN),d()):t.slice()},h.range=function(f){return arguments.length?(e=Array.from(f),d()):e.slice()},h.rangeRound=function(f){return e=Array.from(f),n=$L,d()},h.clamp=function(f){return arguments.length?(o=f?!0:Ps,d()):o!==Ps},h.interpolate=function(f){return arguments.length?(n=f,d()):n},h.unknown=function(f){return arguments.length?(s=f,h):s},function(f,p){return r=f,a=p,d()}}function VL(){return Dk()(Ps,Ps)}function CDe(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function bN(t,e){if(!isFinite(t)||t===0)return null;var n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function kb(t){return t=bN(Math.abs(t)),t?t[1]:NaN}function kDe(t,e){return function(n,r){for(var a=n.length,s=[],o=0,l=t[0],c=0;a>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),s.push(n.substring(a-=l,a+l)),!((c+=l+1)>r));)l=t[o=(o+1)%t.length];return s.reverse().join(e)}}function ADe(t){return function(e){return e.replace(/[0-9]/g,function(n){return t[+n]})}}var TDe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Bv(t){if(!(e=TDe.exec(t)))throw new Error("invalid format: "+t);var e;return new qL({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Bv.prototype=qL.prototype;function qL(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}qL.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function MDe(t){e:for(var e=t.length,n=1,r=-1,a;n<e;++n)switch(t[n]){case".":r=a=n;break;case"0":r===0&&(r=n),a=n;break;default:if(!+t[n])break e;r>0&&(r=0);break}return r>0?t.slice(0,r)+t.slice(a+1):t}var xN;function PDe(t,e){var n=bN(t,e);if(!n)return xN=void 0,t.toPrecision(e);var r=n[0],a=n[1],s=a-(xN=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,o=r.length;return s===o?r:s>o?r+new Array(s-o+1).join("0"):s>0?r.slice(0,s)+"."+r.slice(s):"0."+new Array(1-s).join("0")+bN(t,Math.max(0,e+s-1))[0]}function Fq(t,e){var n=bN(t,e);if(!n)return t+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const Lq={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:CDe,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>Fq(t*100,e),r:Fq,s:PDe,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function Oq(t){return t}var Iq=Array.prototype.map,zq=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function EDe(t){var e=t.grouping===void 0||t.thousands===void 0?Oq:kDe(Iq.call(t.grouping,Number),t.thousands+""),n=t.currency===void 0?"":t.currency[0]+"",r=t.currency===void 0?"":t.currency[1]+"",a=t.decimal===void 0?".":t.decimal+"",s=t.numerals===void 0?Oq:ADe(Iq.call(t.numerals,String)),o=t.percent===void 0?"%":t.percent+"",l=t.minus===void 0?"−":t.minus+"",c=t.nan===void 0?"NaN":t.nan+"";function u(h,f){h=Bv(h);var p=h.fill,x=h.align,v=h.sign,g=h.symbol,y=h.zero,_=h.width,N=h.comma,k=h.precision,A=h.trim,M=h.type;M==="n"?(N=!0,M="g"):Lq[M]||(k===void 0&&(k=12),A=!0,M="g"),(y||p==="0"&&x==="=")&&(y=!0,p="0",x="=");var C=(f&&f.prefix!==void 0?f.prefix:"")+(g==="$"?n:g==="#"&&/[boxX]/.test(M)?"0"+M.toLowerCase():""),j=(g==="$"?r:/[%p]/.test(M)?o:"")+(f&&f.suffix!==void 0?f.suffix:""),P=Lq[M],E=/[defgprs%]/.test(M);k=k===void 0?6:/[gprs]/.test(M)?Math.max(1,Math.min(21,k)):Math.max(0,Math.min(20,k));function U(L){var B=C,D=j,$,G,z;if(M==="c")D=P(L)+D,L="";else{L=+L;var W=L<0||1/L<0;if(L=isNaN(L)?c:P(Math.abs(L),k),A&&(L=MDe(L)),W&&+L==0&&v!=="+"&&(W=!1),B=(W?v==="("?v:l:v==="-"||v==="("?"":v)+B,D=(M==="s"&&!isNaN(L)&&xN!==void 0?zq[8+xN/3]:"")+D+(W&&v==="("?")":""),E){for($=-1,G=L.length;++$<G;)if(z=L.charCodeAt($),48>z||z>57){D=(z===46?a+L.slice($+1):L.slice($))+D,L=L.slice(0,$);break}}}N&&!y&&(L=e(L,1/0));var X=B.length+L.length+D.length,ae=X<_?new Array(_-X+1).join(p):"";switch(N&&y&&(L=e(ae+L,ae.length?_-D.length:1/0),ae=""),x){case"<":L=B+L+D+ae;break;case"=":L=B+ae+L+D;break;case"^":L=ae.slice(0,X=ae.length>>1)+B+L+D+ae.slice(X);break;default:L=ae+B+L+D;break}return s(L)}return U.toString=function(){return h+""},U}function d(h,f){var p=Math.max(-8,Math.min(8,Math.floor(kb(f)/3)))*3,x=Math.pow(10,-p),v=u((h=Bv(h),h.type="f",h),{suffix:zq[8+p/3]});return function(g){return v(x*g)}}return{format:u,formatPrefix:d}}var b_,GL,nJ;jDe({thousands:",",grouping:[3],currency:["$",""]});function jDe(t){return b_=EDe(t),GL=b_.format,nJ=b_.formatPrefix,b_}function DDe(t){return Math.max(0,-kb(Math.abs(t)))}function RDe(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(kb(e)/3)))*3-kb(Math.abs(t)))}function FDe(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,kb(e)-kb(t))+1}function rJ(t,e,n,r){var a=YD(t,e,n),s;switch(r=Bv(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(t),Math.abs(e));return r.precision==null&&!isNaN(s=RDe(a,o))&&(r.precision=s),nJ(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=FDe(a,Math.max(Math.abs(t),Math.abs(e))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=DDe(a))&&(r.precision=s-(r.type==="%")*2);break}}return GL(r)}function rm(t){var e=t.domain;return t.ticks=function(n){var r=e();return KD(r[0],r[r.length-1],n??10)},t.tickFormat=function(n,r){var a=e();return rJ(a[0],a[a.length-1],n??10,r)},t.nice=function(n){n==null&&(n=10);var r=e(),a=0,s=r.length-1,o=r[a],l=r[s],c,u,d=10;for(l<o&&(u=o,o=l,l=u,u=a,a=s,s=u);d-- >0;){if(u=XD(o,l,n),u===c)return r[a]=o,r[s]=l,e(r);if(u>0)o=Math.floor(o/u)*u,l=Math.ceil(l/u)*u;else if(u<0)o=Math.ceil(o*u)/u,l=Math.floor(l*u)/u;else break;c=u}return t},t}function aJ(){var t=VL();return t.copy=function(){return P0(t,aJ())},Al.apply(t,arguments),rm(t)}function iJ(t){var e;function n(r){return r==null||isNaN(r=+r)?e:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(t=Array.from(r,gN),n):t.slice()},n.unknown=function(r){return arguments.length?(e=r,n):e},n.copy=function(){return iJ(t).unknown(e)},t=arguments.length?Array.from(t,gN):[0,1],rm(n)}function sJ(t,e){t=t.slice();var n=0,r=t.length-1,a=t[n],s=t[r],o;return s<a&&(o=n,n=r,r=o,o=a,a=s,s=o),t[n]=e.floor(a),t[r]=e.ceil(s),t}function Uq(t){return Math.log(t)}function Bq(t){return Math.exp(t)}function LDe(t){return-Math.log(-t)}function ODe(t){return-Math.exp(-t)}function IDe(t){return isFinite(t)?+("1e"+t):t<0?0:t}function zDe(t){return t===10?IDe:t===Math.E?Math.exp:e=>Math.pow(t,e)}function UDe(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function Hq(t){return(e,n)=>-t(-e,n)}function WL(t){const e=t(Uq,Bq),n=e.domain;let r=10,a,s;function o(){return a=UDe(r),s=zDe(r),n()[0]<0?(a=Hq(a),s=Hq(s),t(LDe,ODe)):t(Uq,Bq),e}return e.base=function(l){return arguments.length?(r=+l,o()):r},e.domain=function(l){return arguments.length?(n(l),o()):n()},e.ticks=l=>{const c=n();let u=c[0],d=c[c.length-1];const h=d<u;h&&([u,d]=[d,u]);let f=a(u),p=a(d),x,v;const g=l==null?10:+l;let y=[];if(!(r%1)&&p-f<g){if(f=Math.floor(f),p=Math.ceil(p),u>0){for(;f<=p;++f)for(x=1;x<r;++x)if(v=f<0?x/s(-f):x*s(f),!(v<u)){if(v>d)break;y.push(v)}}else for(;f<=p;++f)for(x=r-1;x>=1;--x)if(v=f>0?x/s(-f):x*s(f),!(v<u)){if(v>d)break;y.push(v)}y.length*2<g&&(y=KD(u,d,g))}else y=KD(f,p,Math.min(p-f,g)).map(s);return h?y.reverse():y},e.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Bv(c)).precision==null&&(c.trim=!0),c=GL(c)),l===1/0)return c;const u=Math.max(1,r*l/e.ticks().length);return d=>{let h=d/s(Math.round(a(d)));return h*r<r-.5&&(h*=r),h<=u?c(d):""}},e.nice=()=>n(sJ(n(),{floor:l=>s(Math.floor(a(l))),ceil:l=>s(Math.ceil(a(l)))})),e}function oJ(){const t=WL(Dk()).domain([1,10]);return t.copy=()=>P0(t,oJ()).base(t.base()),Al.apply(t,arguments),t}function $q(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function Vq(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function KL(t){var e=1,n=t($q(e),Vq(e));return n.constant=function(r){return arguments.length?t($q(e=+r),Vq(e)):e},rm(n)}function lJ(){var t=KL(Dk());return t.copy=function(){return P0(t,lJ()).constant(t.constant())},Al.apply(t,arguments)}function qq(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function BDe(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function HDe(t){return t<0?-t*t:t*t}function XL(t){var e=t(Ps,Ps),n=1;function r(){return n===1?t(Ps,Ps):n===.5?t(BDe,HDe):t(qq(n),qq(1/n))}return e.exponent=function(a){return arguments.length?(n=+a,r()):n},rm(e)}function YL(){var t=XL(Dk());return t.copy=function(){return P0(t,YL()).exponent(t.exponent())},Al.apply(t,arguments),t}function $De(){return YL.apply(null,arguments).exponent(.5)}function Gq(t){return Math.sign(t)*t*t}function VDe(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function cJ(){var t=VL(),e=[0,1],n=!1,r;function a(s){var o=VDe(t(s));return isNaN(o)?r:n?Math.round(o):o}return a.invert=function(s){return t.invert(Gq(s))},a.domain=function(s){return arguments.length?(t.domain(s),a):t.domain()},a.range=function(s){return arguments.length?(t.range((e=Array.from(s,gN)).map(Gq)),a):e.slice()},a.rangeRound=function(s){return a.range(s).round(!0)},a.round=function(s){return arguments.length?(n=!!s,a):n},a.clamp=function(s){return arguments.length?(t.clamp(s),a):t.clamp()},a.unknown=function(s){return arguments.length?(r=s,a):r},a.copy=function(){return cJ(t.domain(),e).round(n).clamp(t.clamp()).unknown(r)},Al.apply(a,arguments),rm(a)}function uJ(){var t=[],e=[],n=[],r;function a(){var o=0,l=Math.max(1,e.length);for(n=new Array(l-1);++o<l;)n[o-1]=K3e(t,o/l);return s}function s(o){return o==null||isNaN(o=+o)?r:e[T0(n,o)]}return s.invertExtent=function(o){var l=e.indexOf(o);return l<0?[NaN,NaN]:[l>0?n[l-1]:t[0],l<n.length?n[l]:t[t.length-1]]},s.domain=function(o){if(!arguments.length)return t.slice();t=[];for(let l of o)l!=null&&!isNaN(l=+l)&&t.push(l);return t.sort(Ih),a()},s.range=function(o){return arguments.length?(e=Array.from(o),a()):e.slice()},s.unknown=function(o){return arguments.length?(r=o,s):r},s.quantiles=function(){return n.slice()},s.copy=function(){return uJ().domain(t).range(e).unknown(r)},Al.apply(s,arguments)}function dJ(){var t=0,e=1,n=1,r=[.5],a=[0,1],s;function o(c){return c!=null&&c<=c?a[T0(r,c,0,n)]:s}function l(){var c=-1;for(r=new Array(n);++c<n;)r[c]=((c+1)*e-(c-n)*t)/(n+1);return o}return o.domain=function(c){return arguments.length?([t,e]=c,t=+t,e=+e,l()):[t,e]},o.range=function(c){return arguments.length?(n=(a=Array.from(c)).length-1,l()):a.slice()},o.invertExtent=function(c){var u=a.indexOf(c);return u<0?[NaN,NaN]:u<1?[t,r[0]]:u>=n?[r[n-1],e]:[r[u-1],r[u]]},o.unknown=function(c){return arguments.length&&(s=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return dJ().domain([t,e]).range(a).unknown(s)},Al.apply(rm(o),arguments)}function hJ(){var t=[.5],e=[0,1],n,r=1;function a(s){return s!=null&&s<=s?e[T0(t,s,0,r)]:n}return a.domain=function(s){return arguments.length?(t=Array.from(s),r=Math.min(t.length,e.length-1),a):t.slice()},a.range=function(s){return arguments.length?(e=Array.from(s),r=Math.min(t.length,e.length-1),a):e.slice()},a.invertExtent=function(s){var o=e.indexOf(s);return[t[o-1],t[o]]},a.unknown=function(s){return arguments.length?(n=s,a):n},a.copy=function(){return hJ().domain(t).range(e).unknown(n)},Al.apply(a,arguments)}const xj=new Date,yj=new Date;function Si(t,e,n,r){function a(s){return t(s=arguments.length===0?new Date:new Date(+s)),s}return a.floor=s=>(t(s=new Date(+s)),s),a.ceil=s=>(t(s=new Date(s-1)),e(s,1),t(s),s),a.round=s=>{const o=a(s),l=a.ceil(s);return s-o<l-s?o:l},a.offset=(s,o)=>(e(s=new Date(+s),o==null?1:Math.floor(o)),s),a.range=(s,o,l)=>{const c=[];if(s=a.ceil(s),l=l==null?1:Math.floor(l),!(s<o)||!(l>0))return c;let u;do c.push(u=new Date(+s)),e(s,l),t(s);while(u<s&&s<o);return c},a.filter=s=>Si(o=>{if(o>=o)for(;t(o),!s(o);)o.setTime(o-1)},(o,l)=>{if(o>=o)if(l<0)for(;++l<=0;)for(;e(o,-1),!s(o););else for(;--l>=0;)for(;e(o,1),!s(o););}),n&&(a.count=(s,o)=>(xj.setTime(+s),yj.setTime(+o),t(xj),t(yj),Math.floor(n(xj,yj))),a.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?a.filter(r?o=>r(o)%s===0:o=>a.count(0,o)%s===0):a)),a}const yN=Si(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);yN.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?Si(e=>{e.setTime(Math.floor(e/t)*t)},(e,n)=>{e.setTime(+e+n*t)},(e,n)=>(n-e)/t):yN);yN.range;const Uu=1e3,ml=Uu*60,Bu=ml*60,od=Bu*24,QL=od*7,Wq=od*30,vj=od*365,af=Si(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Uu)},(t,e)=>(e-t)/Uu,t=>t.getUTCSeconds());af.range;const ZL=Si(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Uu)},(t,e)=>{t.setTime(+t+e*ml)},(t,e)=>(e-t)/ml,t=>t.getMinutes());ZL.range;const JL=Si(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*ml)},(t,e)=>(e-t)/ml,t=>t.getUTCMinutes());JL.range;const eO=Si(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Uu-t.getMinutes()*ml)},(t,e)=>{t.setTime(+t+e*Bu)},(t,e)=>(e-t)/Bu,t=>t.getHours());eO.range;const tO=Si(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Bu)},(t,e)=>(e-t)/Bu,t=>t.getUTCHours());tO.range;const E0=Si(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*ml)/od,t=>t.getDate()-1);E0.range;const Rk=Si(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/od,t=>t.getUTCDate()-1);Rk.range;const mJ=Si(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/od,t=>Math.floor(t/od));mJ.range;function ap(t){return Si(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,n)=>{e.setDate(e.getDate()+n*7)},(e,n)=>(n-e-(n.getTimezoneOffset()-e.getTimezoneOffset())*ml)/QL)}const Fk=ap(0),vN=ap(1),qDe=ap(2),GDe=ap(3),Ab=ap(4),WDe=ap(5),KDe=ap(6);Fk.range;vN.range;qDe.range;GDe.range;Ab.range;WDe.range;KDe.range;function ip(t){return Si(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCDate(e.getUTCDate()+n*7)},(e,n)=>(n-e)/QL)}const Lk=ip(0),wN=ip(1),XDe=ip(2),YDe=ip(3),Tb=ip(4),QDe=ip(5),ZDe=ip(6);Lk.range;wN.range;XDe.range;YDe.range;Tb.range;QDe.range;ZDe.range;const nO=Si(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());nO.range;const rO=Si(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());rO.range;const ld=Si(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());ld.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Si(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,n)=>{e.setFullYear(e.getFullYear()+n*t)});ld.range;const cd=Si(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());cd.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:Si(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,n)=>{e.setUTCFullYear(e.getUTCFullYear()+n*t)});cd.range;function fJ(t,e,n,r,a,s){const o=[[af,1,Uu],[af,5,5*Uu],[af,15,15*Uu],[af,30,30*Uu],[s,1,ml],[s,5,5*ml],[s,15,15*ml],[s,30,30*ml],[a,1,Bu],[a,3,3*Bu],[a,6,6*Bu],[a,12,12*Bu],[r,1,od],[r,2,2*od],[n,1,QL],[e,1,Wq],[e,3,3*Wq],[t,1,vj]];function l(u,d,h){const f=d<u;f&&([u,d]=[d,u]);const p=h&&typeof h.range=="function"?h:c(u,d,h),x=p?p.range(u,+d+1):[];return f?x.reverse():x}function c(u,d,h){const f=Math.abs(d-u)/h,p=IL(([,,g])=>g).right(o,f);if(p===o.length)return t.every(YD(u/vj,d/vj,h));if(p===0)return yN.every(Math.max(YD(u,d,h),1));const[x,v]=o[f/o[p-1][2]<o[p][2]/f?p-1:p];return x.every(v)}return[l,c]}const[JDe,eRe]=fJ(cd,rO,Lk,mJ,tO,JL),[tRe,nRe]=fJ(ld,nO,Fk,E0,eO,ZL);function wj(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function Sj(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function yy(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function rRe(t){var e=t.dateTime,n=t.date,r=t.time,a=t.periods,s=t.days,o=t.shortDays,l=t.months,c=t.shortMonths,u=vy(a),d=wy(a),h=vy(s),f=wy(s),p=vy(o),x=wy(o),v=vy(l),g=wy(l),y=vy(c),_=wy(c),N={a:z,A:W,b:X,B:ae,c:null,d:Jq,e:Jq,f:kRe,g:LRe,G:IRe,H:_Re,I:NRe,j:CRe,L:pJ,m:ARe,M:TRe,p:H,q:K,Q:nG,s:rG,S:MRe,u:PRe,U:ERe,V:jRe,w:DRe,W:RRe,x:null,X:null,y:FRe,Y:ORe,Z:zRe,"%":tG},k={a:te,A:Z,b:ve,B:ce,c:null,d:eG,e:eG,f:$Re,g:JRe,G:tFe,H:URe,I:BRe,j:HRe,L:bJ,m:VRe,M:qRe,p:ee,q:je,Q:nG,s:rG,S:GRe,u:WRe,U:KRe,V:XRe,w:YRe,W:QRe,x:null,X:null,y:ZRe,Y:eFe,Z:nFe,"%":tG},A={a:E,A:U,b:L,B,c:D,d:Qq,e:Qq,f:yRe,g:Yq,G:Xq,H:Zq,I:Zq,j:pRe,L:xRe,m:fRe,M:gRe,p:P,q:mRe,Q:wRe,s:SRe,S:bRe,u:lRe,U:cRe,V:uRe,w:oRe,W:dRe,x:$,X:G,y:Yq,Y:Xq,Z:hRe,"%":vRe};N.x=M(n,N),N.X=M(r,N),N.c=M(e,N),k.x=M(n,k),k.X=M(r,k),k.c=M(e,k);function M(he,oe){return function(_e){var ie=[],ze=-1,V=0,Y=he.length,me,Q,se;for(_e instanceof Date||(_e=new Date(+_e));++ze<Y;)he.charCodeAt(ze)===37&&(ie.push(he.slice(V,ze)),(Q=Kq[me=he.charAt(++ze)])!=null?me=he.charAt(++ze):Q=me==="e"?" ":"0",(se=oe[me])&&(me=se(_e,Q)),ie.push(me),V=ze+1);return ie.push(he.slice(V,ze)),ie.join("")}}function C(he,oe){return function(_e){var ie=yy(1900,void 0,1),ze=j(ie,he,_e+="",0),V,Y;if(ze!=_e.length)return null;if("Q"in ie)return new Date(ie.Q);if("s"in ie)return new Date(ie.s*1e3+("L"in ie?ie.L:0));if(oe&&!("Z"in ie)&&(ie.Z=0),"p"in ie&&(ie.H=ie.H%12+ie.p*12),ie.m===void 0&&(ie.m="q"in ie?ie.q:0),"V"in ie){if(ie.V<1||ie.V>53)return null;"w"in ie||(ie.w=1),"Z"in ie?(V=Sj(yy(ie.y,0,1)),Y=V.getUTCDay(),V=Y>4||Y===0?wN.ceil(V):wN(V),V=Rk.offset(V,(ie.V-1)*7),ie.y=V.getUTCFullYear(),ie.m=V.getUTCMonth(),ie.d=V.getUTCDate()+(ie.w+6)%7):(V=wj(yy(ie.y,0,1)),Y=V.getDay(),V=Y>4||Y===0?vN.ceil(V):vN(V),V=E0.offset(V,(ie.V-1)*7),ie.y=V.getFullYear(),ie.m=V.getMonth(),ie.d=V.getDate()+(ie.w+6)%7)}else("W"in ie||"U"in ie)&&("w"in ie||(ie.w="u"in ie?ie.u%7:"W"in ie?1:0),Y="Z"in ie?Sj(yy(ie.y,0,1)).getUTCDay():wj(yy(ie.y,0,1)).getDay(),ie.m=0,ie.d="W"in ie?(ie.w+6)%7+ie.W*7-(Y+5)%7:ie.w+ie.U*7-(Y+6)%7);return"Z"in ie?(ie.H+=ie.Z/100|0,ie.M+=ie.Z%100,Sj(ie)):wj(ie)}}function j(he,oe,_e,ie){for(var ze=0,V=oe.length,Y=_e.length,me,Q;ze<V;){if(ie>=Y)return-1;if(me=oe.charCodeAt(ze++),me===37){if(me=oe.charAt(ze++),Q=A[me in Kq?oe.charAt(ze++):me],!Q||(ie=Q(he,_e,ie))<0)return-1}else if(me!=_e.charCodeAt(ie++))return-1}return ie}function P(he,oe,_e){var ie=u.exec(oe.slice(_e));return ie?(he.p=d.get(ie[0].toLowerCase()),_e+ie[0].length):-1}function E(he,oe,_e){var ie=p.exec(oe.slice(_e));return ie?(he.w=x.get(ie[0].toLowerCase()),_e+ie[0].length):-1}function U(he,oe,_e){var ie=h.exec(oe.slice(_e));return ie?(he.w=f.get(ie[0].toLowerCase()),_e+ie[0].length):-1}function L(he,oe,_e){var ie=y.exec(oe.slice(_e));return ie?(he.m=_.get(ie[0].toLowerCase()),_e+ie[0].length):-1}function B(he,oe,_e){var ie=v.exec(oe.slice(_e));return ie?(he.m=g.get(ie[0].toLowerCase()),_e+ie[0].length):-1}function D(he,oe,_e){return j(he,e,oe,_e)}function $(he,oe,_e){return j(he,n,oe,_e)}function G(he,oe,_e){return j(he,r,oe,_e)}function z(he){return o[he.getDay()]}function W(he){return s[he.getDay()]}function X(he){return c[he.getMonth()]}function ae(he){return l[he.getMonth()]}function H(he){return a[+(he.getHours()>=12)]}function K(he){return 1+~~(he.getMonth()/3)}function te(he){return o[he.getUTCDay()]}function Z(he){return s[he.getUTCDay()]}function ve(he){return c[he.getUTCMonth()]}function ce(he){return l[he.getUTCMonth()]}function ee(he){return a[+(he.getUTCHours()>=12)]}function je(he){return 1+~~(he.getUTCMonth()/3)}return{format:function(he){var oe=M(he+="",N);return oe.toString=function(){return he},oe},parse:function(he){var oe=C(he+="",!1);return oe.toString=function(){return he},oe},utcFormat:function(he){var oe=M(he+="",k);return oe.toString=function(){return he},oe},utcParse:function(he){var oe=C(he+="",!0);return oe.toString=function(){return he},oe}}}var Kq={"-":"",_:" ",0:"0"},Oi=/^\s*\d+/,aRe=/^%/,iRe=/[\\^$*+?|[\]().{}]/g;function ur(t,e,n){var r=t<0?"-":"",a=(r?-t:t)+"",s=a.length;return r+(s<n?new Array(n-s+1).join(e)+a:a)}function sRe(t){return t.replace(iRe,"\\$&")}function vy(t){return new RegExp("^(?:"+t.map(sRe).join("|")+")","i")}function wy(t){return new Map(t.map((e,n)=>[e.toLowerCase(),n]))}function oRe(t,e,n){var r=Oi.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function lRe(t,e,n){var r=Oi.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function cRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function uRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function dRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function Xq(t,e,n){var r=Oi.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Yq(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function hRe(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function mRe(t,e,n){var r=Oi.exec(e.slice(n,n+1));return r?(t.q=r[0]*3-3,n+r[0].length):-1}function fRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function Qq(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function pRe(t,e,n){var r=Oi.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function Zq(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function gRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function bRe(t,e,n){var r=Oi.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function xRe(t,e,n){var r=Oi.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function yRe(t,e,n){var r=Oi.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function vRe(t,e,n){var r=aRe.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function wRe(t,e,n){var r=Oi.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function SRe(t,e,n){var r=Oi.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Jq(t,e){return ur(t.getDate(),e,2)}function _Re(t,e){return ur(t.getHours(),e,2)}function NRe(t,e){return ur(t.getHours()%12||12,e,2)}function CRe(t,e){return ur(1+E0.count(ld(t),t),e,3)}function pJ(t,e){return ur(t.getMilliseconds(),e,3)}function kRe(t,e){return pJ(t,e)+"000"}function ARe(t,e){return ur(t.getMonth()+1,e,2)}function TRe(t,e){return ur(t.getMinutes(),e,2)}function MRe(t,e){return ur(t.getSeconds(),e,2)}function PRe(t){var e=t.getDay();return e===0?7:e}function ERe(t,e){return ur(Fk.count(ld(t)-1,t),e,2)}function gJ(t){var e=t.getDay();return e>=4||e===0?Ab(t):Ab.ceil(t)}function jRe(t,e){return t=gJ(t),ur(Ab.count(ld(t),t)+(ld(t).getDay()===4),e,2)}function DRe(t){return t.getDay()}function RRe(t,e){return ur(vN.count(ld(t)-1,t),e,2)}function FRe(t,e){return ur(t.getFullYear()%100,e,2)}function LRe(t,e){return t=gJ(t),ur(t.getFullYear()%100,e,2)}function ORe(t,e){return ur(t.getFullYear()%1e4,e,4)}function IRe(t,e){var n=t.getDay();return t=n>=4||n===0?Ab(t):Ab.ceil(t),ur(t.getFullYear()%1e4,e,4)}function zRe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+ur(e/60|0,"0",2)+ur(e%60,"0",2)}function eG(t,e){return ur(t.getUTCDate(),e,2)}function URe(t,e){return ur(t.getUTCHours(),e,2)}function BRe(t,e){return ur(t.getUTCHours()%12||12,e,2)}function HRe(t,e){return ur(1+Rk.count(cd(t),t),e,3)}function bJ(t,e){return ur(t.getUTCMilliseconds(),e,3)}function $Re(t,e){return bJ(t,e)+"000"}function VRe(t,e){return ur(t.getUTCMonth()+1,e,2)}function qRe(t,e){return ur(t.getUTCMinutes(),e,2)}function GRe(t,e){return ur(t.getUTCSeconds(),e,2)}function WRe(t){var e=t.getUTCDay();return e===0?7:e}function KRe(t,e){return ur(Lk.count(cd(t)-1,t),e,2)}function xJ(t){var e=t.getUTCDay();return e>=4||e===0?Tb(t):Tb.ceil(t)}function XRe(t,e){return t=xJ(t),ur(Tb.count(cd(t),t)+(cd(t).getUTCDay()===4),e,2)}function YRe(t){return t.getUTCDay()}function QRe(t,e){return ur(wN.count(cd(t)-1,t),e,2)}function ZRe(t,e){return ur(t.getUTCFullYear()%100,e,2)}function JRe(t,e){return t=xJ(t),ur(t.getUTCFullYear()%100,e,2)}function eFe(t,e){return ur(t.getUTCFullYear()%1e4,e,4)}function tFe(t,e){var n=t.getUTCDay();return t=n>=4||n===0?Tb(t):Tb.ceil(t),ur(t.getUTCFullYear()%1e4,e,4)}function nFe(){return"+0000"}function tG(){return"%"}function nG(t){return+t}function rG(t){return Math.floor(+t/1e3)}var Sg,yJ,vJ;rFe({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function rFe(t){return Sg=rRe(t),yJ=Sg.format,Sg.parse,vJ=Sg.utcFormat,Sg.utcParse,Sg}function aFe(t){return new Date(t)}function iFe(t){return t instanceof Date?+t:+new Date(+t)}function aO(t,e,n,r,a,s,o,l,c,u){var d=VL(),h=d.invert,f=d.domain,p=u(".%L"),x=u(":%S"),v=u("%I:%M"),g=u("%I %p"),y=u("%a %d"),_=u("%b %d"),N=u("%B"),k=u("%Y");function A(M){return(c(M)<M?p:l(M)<M?x:o(M)<M?v:s(M)<M?g:r(M)<M?a(M)<M?y:_:n(M)<M?N:k)(M)}return d.invert=function(M){return new Date(h(M))},d.domain=function(M){return arguments.length?f(Array.from(M,iFe)):f().map(aFe)},d.ticks=function(M){var C=f();return t(C[0],C[C.length-1],M??10)},d.tickFormat=function(M,C){return C==null?A:u(C)},d.nice=function(M){var C=f();return(!M||typeof M.range!="function")&&(M=e(C[0],C[C.length-1],M??10)),M?f(sJ(C,M)):d},d.copy=function(){return P0(d,aO(t,e,n,r,a,s,o,l,c,u))},d}function sFe(){return Al.apply(aO(tRe,nRe,ld,nO,Fk,E0,eO,ZL,af,yJ).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function oFe(){return Al.apply(aO(JDe,eRe,cd,rO,Lk,Rk,tO,JL,af,vJ).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function Ok(){var t=0,e=1,n,r,a,s,o=Ps,l=!1,c;function u(h){return h==null||isNaN(h=+h)?c:o(a===0?.5:(h=(s(h)-n)*a,l?Math.max(0,Math.min(1,h)):h))}u.domain=function(h){return arguments.length?([t,e]=h,n=s(t=+t),r=s(e=+e),a=n===r?0:1/(r-n),u):[t,e]},u.clamp=function(h){return arguments.length?(l=!!h,u):l},u.interpolator=function(h){return arguments.length?(o=h,u):o};function d(h){return function(f){var p,x;return arguments.length?([p,x]=f,o=h(p,x),u):[o(0),o(1)]}}return u.range=d(Jb),u.rangeRound=d($L),u.unknown=function(h){return arguments.length?(c=h,u):c},function(h){return s=h,n=h(t),r=h(e),a=n===r?0:1/(r-n),u}}function am(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function wJ(){var t=rm(Ok()(Ps));return t.copy=function(){return am(t,wJ())},gd.apply(t,arguments)}function SJ(){var t=WL(Ok()).domain([1,10]);return t.copy=function(){return am(t,SJ()).base(t.base())},gd.apply(t,arguments)}function _J(){var t=KL(Ok());return t.copy=function(){return am(t,_J()).constant(t.constant())},gd.apply(t,arguments)}function iO(){var t=XL(Ok());return t.copy=function(){return am(t,iO()).exponent(t.exponent())},gd.apply(t,arguments)}function lFe(){return iO.apply(null,arguments).exponent(.5)}function NJ(){var t=[],e=Ps;function n(r){if(r!=null&&!isNaN(r=+r))return e((T0(t,r,1)-1)/(t.length-1))}return n.domain=function(r){if(!arguments.length)return t.slice();t=[];for(let a of r)a!=null&&!isNaN(a=+a)&&t.push(a);return t.sort(Ih),n},n.interpolator=function(r){return arguments.length?(e=r,n):e},n.range=function(){return t.map((r,a)=>e(a/(t.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,s)=>W3e(t,s/r))},n.copy=function(){return NJ(e).domain(t)},gd.apply(n,arguments)}function Ik(){var t=0,e=.5,n=1,r=1,a,s,o,l,c,u=Ps,d,h=!1,f;function p(v){return isNaN(v=+v)?f:(v=.5+((v=+d(v))-s)*(r*v<r*s?l:c),u(h?Math.max(0,Math.min(1,v)):v))}p.domain=function(v){return arguments.length?([t,e,n]=v,a=d(t=+t),s=d(e=+e),o=d(n=+n),l=a===s?0:.5/(s-a),c=s===o?0:.5/(o-s),r=s<a?-1:1,p):[t,e,n]},p.clamp=function(v){return arguments.length?(h=!!v,p):h},p.interpolator=function(v){return arguments.length?(u=v,p):u};function x(v){return function(g){var y,_,N;return arguments.length?([y,_,N]=g,u=vDe(v,[y,_,N]),p):[u(0),u(.5),u(1)]}}return p.range=x(Jb),p.rangeRound=x($L),p.unknown=function(v){return arguments.length?(f=v,p):f},function(v){return d=v,a=v(t),s=v(e),o=v(n),l=a===s?0:.5/(s-a),c=s===o?0:.5/(o-s),r=s<a?-1:1,p}}function CJ(){var t=rm(Ik()(Ps));return t.copy=function(){return am(t,CJ())},gd.apply(t,arguments)}function kJ(){var t=WL(Ik()).domain([.1,1,10]);return t.copy=function(){return am(t,kJ()).base(t.base())},gd.apply(t,arguments)}function AJ(){var t=KL(Ik());return t.copy=function(){return am(t,AJ()).constant(t.constant())},gd.apply(t,arguments)}function sO(){var t=XL(Ik());return t.copy=function(){return am(t,sO()).exponent(t.exponent())},gd.apply(t,arguments)}function cFe(){return sO.apply(null,arguments).exponent(.5)}const Ey=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:UL,scaleDiverging:CJ,scaleDivergingLog:kJ,scaleDivergingPow:sO,scaleDivergingSqrt:cFe,scaleDivergingSymlog:AJ,scaleIdentity:iJ,scaleImplicit:QD,scaleLinear:aJ,scaleLog:oJ,scaleOrdinal:zL,scalePoint:Y3e,scalePow:YL,scaleQuantile:uJ,scaleQuantize:dJ,scaleRadial:cJ,scaleSequential:wJ,scaleSequentialLog:SJ,scaleSequentialPow:iO,scaleSequentialQuantile:NJ,scaleSequentialSqrt:lFe,scaleSequentialSymlog:_J,scaleSqrt:$De,scaleSymlog:lJ,scaleThreshold:hJ,scaleTime:sFe,scaleUtc:oFe,tickFormat:rJ},Symbol.toStringTag,{value:"Module"}));var bd=t=>t.chartData,zk=ct([bd],t=>{var e=t.chartData!=null?t.chartData.length-1:0;return{chartData:t.chartData,computedData:t.computedData,dataEndIndex:e,dataStartIndex:0}}),oO=(t,e,n,r)=>r?zk(t):bd(t),TJ=(t,e,n)=>n?zk(t):bd(t);function ud(t){if(Array.isArray(t)&&t.length===2){var[e,n]=t;if(Nn(e)&&Nn(n))return!0}return!1}function aG(t,e,n){return n?t:[Math.min(t[0],e[0]),Math.max(t[1],e[1])]}function MJ(t,e){if(e&&typeof t!="function"&&Array.isArray(t)&&t.length===2){var[n,r]=t,a,s;if(Nn(n))a=n;else if(typeof n=="function")return;if(Nn(r))s=r;else if(typeof r=="function")return;var o=[a,s];if(ud(o))return o}}function uFe(t,e,n){if(!(!n&&e==null)){if(typeof t=="function"&&e!=null)try{var r=t(e,n);if(ud(r))return aG(r,e,n)}catch{}if(Array.isArray(t)&&t.length===2){var[a,s]=t,o,l;if(a==="auto")e!=null&&(o=Math.min(...e));else if(qt(a))o=a;else if(typeof a=="function")try{e!=null&&(o=a(e?.[0]))}catch{}else if(typeof a=="string"&&fV.test(a)){var c=fV.exec(a);if(c==null||c[1]==null||e==null)o=void 0;else{var u=+c[1];o=e[0]-u}}else o=e?.[0];if(s==="auto")e!=null&&(l=Math.max(...e));else if(qt(s))l=s;else if(typeof s=="function")try{e!=null&&(l=s(e?.[1]))}catch{}else if(typeof s=="string"&&pV.test(s)){var d=pV.exec(s);if(d==null||d[1]==null||e==null)l=void 0;else{var h=+d[1];l=e[1]+h}}else l=e?.[1];var f=[o,l];if(ud(f))return e==null?f:aG(f,e,n)}}}var ex=1e9,dFe={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},cO,ca=!0,Cl="[DecimalError] ",xf=Cl+"Invalid argument: ",lO=Cl+"Exponent out of range: ",tx=Math.floor,qm=Math.pow,hFe=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,To,Ei=1e7,na=7,PJ=9007199254740991,SN=tx(PJ/na),Yt={};Yt.absoluteValue=Yt.abs=function(){var t=new this.constructor(this);return t.s&&(t.s=1),t};Yt.comparedTo=Yt.cmp=function(t){var e,n,r,a,s=this;if(t=new s.constructor(t),s.s!==t.s)return s.s||-t.s;if(s.e!==t.e)return s.e>t.e^s.s<0?1:-1;for(r=s.d.length,a=t.d.length,e=0,n=r<a?r:a;e<n;++e)if(s.d[e]!==t.d[e])return s.d[e]>t.d[e]^s.s<0?1:-1;return r===a?0:r>a^s.s<0?1:-1};Yt.decimalPlaces=Yt.dp=function(){var t=this,e=t.d.length-1,n=(e-t.e)*na;if(e=t.d[e],e)for(;e%10==0;e/=10)n--;return n<0?0:n};Yt.dividedBy=Yt.div=function(t){return Wu(this,new this.constructor(t))};Yt.dividedToIntegerBy=Yt.idiv=function(t){var e=this,n=e.constructor;return Vr(Wu(e,new n(t),0,1),n.precision)};Yt.equals=Yt.eq=function(t){return!this.cmp(t)};Yt.exponent=function(){return ai(this)};Yt.greaterThan=Yt.gt=function(t){return this.cmp(t)>0};Yt.greaterThanOrEqualTo=Yt.gte=function(t){return this.cmp(t)>=0};Yt.isInteger=Yt.isint=function(){return this.e>this.d.length-2};Yt.isNegative=Yt.isneg=function(){return this.s<0};Yt.isPositive=Yt.ispos=function(){return this.s>0};Yt.isZero=function(){return this.s===0};Yt.lessThan=Yt.lt=function(t){return this.cmp(t)<0};Yt.lessThanOrEqualTo=Yt.lte=function(t){return this.cmp(t)<1};Yt.logarithm=Yt.log=function(t){var e,n=this,r=n.constructor,a=r.precision,s=a+5;if(t===void 0)t=new r(10);else if(t=new r(t),t.s<1||t.eq(To))throw Error(Cl+"NaN");if(n.s<1)throw Error(Cl+(n.s?"NaN":"-Infinity"));return n.eq(To)?new r(0):(ca=!1,e=Wu(Hv(n,s),Hv(t,s),s),ca=!0,Vr(e,a))};Yt.minus=Yt.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?DJ(e,t):EJ(e,(t.s=-t.s,t))};Yt.modulo=Yt.mod=function(t){var e,n=this,r=n.constructor,a=r.precision;if(t=new r(t),!t.s)throw Error(Cl+"NaN");return n.s?(ca=!1,e=Wu(n,t,0,1).times(t),ca=!0,n.minus(e)):Vr(new r(n),a)};Yt.naturalExponential=Yt.exp=function(){return jJ(this)};Yt.naturalLogarithm=Yt.ln=function(){return Hv(this)};Yt.negated=Yt.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};Yt.plus=Yt.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?EJ(e,t):DJ(e,(t.s=-t.s,t))};Yt.precision=Yt.sd=function(t){var e,n,r,a=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(xf+t);if(e=ai(a)+1,r=a.d.length-1,n=r*na+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return t&&e>n?e:n};Yt.squareRoot=Yt.sqrt=function(){var t,e,n,r,a,s,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(Cl+"NaN")}for(t=ai(l),ca=!1,a=Math.sqrt(+l),a==0||a==1/0?(e=Mc(l.d),(e.length+t)%2==0&&(e+="0"),a=Math.sqrt(e),t=tx((t+1)/2)-(t<0||t%2),a==1/0?e="5e"+t:(e=a.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),r=new c(e)):r=new c(a.toString()),n=c.precision,a=o=n+3;;)if(s=r,r=s.plus(Wu(l,s,o+2)).times(.5),Mc(s.d).slice(0,o)===(e=Mc(r.d)).slice(0,o)){if(e=e.slice(o-3,o+1),a==o&&e=="4999"){if(Vr(s,n+1,0),s.times(s).eq(l)){r=s;break}}else if(e!="9999")break;o+=4}return ca=!0,Vr(r,n)};Yt.times=Yt.mul=function(t){var e,n,r,a,s,o,l,c,u,d=this,h=d.constructor,f=d.d,p=(t=new h(t)).d;if(!d.s||!t.s)return new h(0);for(t.s*=d.s,n=d.e+t.e,c=f.length,u=p.length,c<u&&(s=f,f=p,p=s,o=c,c=u,u=o),s=[],o=c+u,r=o;r--;)s.push(0);for(r=u;--r>=0;){for(e=0,a=c+r;a>r;)l=s[a]+p[r]*f[a-r-1]+e,s[a--]=l%Ei|0,e=l/Ei|0;s[a]=(s[a]+e)%Ei|0}for(;!s[--o];)s.pop();return e?++n:s.shift(),t.d=s,t.e=n,ca?Vr(t,h.precision):t};Yt.toDecimalPlaces=Yt.todp=function(t,e){var n=this,r=n.constructor;return n=new r(n),t===void 0?n:(Ic(t,0,ex),e===void 0?e=r.rounding:Ic(e,0,8),Vr(n,t+ai(n)+1,e))};Yt.toExponential=function(t,e){var n,r=this,a=r.constructor;return t===void 0?n=Wf(r,!0):(Ic(t,0,ex),e===void 0?e=a.rounding:Ic(e,0,8),r=Vr(new a(r),t+1,e),n=Wf(r,!0,t+1)),n};Yt.toFixed=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?Wf(a):(Ic(t,0,ex),e===void 0?e=s.rounding:Ic(e,0,8),r=Vr(new s(a),t+ai(a)+1,e),n=Wf(r.abs(),!1,t+ai(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Yt.toInteger=Yt.toint=function(){var t=this,e=t.constructor;return Vr(new e(t),ai(t)+1,e.rounding)};Yt.toNumber=function(){return+this};Yt.toPower=Yt.pow=function(t){var e,n,r,a,s,o,l=this,c=l.constructor,u=12,d=+(t=new c(t));if(!t.s)return new c(To);if(l=new c(l),!l.s){if(t.s<1)throw Error(Cl+"Infinity");return l}if(l.eq(To))return l;if(r=c.precision,t.eq(To))return Vr(l,r);if(e=t.e,n=t.d.length-1,o=e>=n,s=l.s,o){if((n=d<0?-d:d)<=PJ){for(a=new c(To),e=Math.ceil(r/na+4),ca=!1;n%2&&(a=a.times(l),sG(a.d,e)),n=tx(n/2),n!==0;)l=l.times(l),sG(l.d,e);return ca=!0,t.s<0?new c(To).div(a):Vr(a,r)}}else if(s<0)throw Error(Cl+"NaN");return s=s<0&&t.d[Math.max(e,n)]&1?-1:1,l.s=1,ca=!1,a=t.times(Hv(l,r+u)),ca=!0,a=jJ(a),a.s=s,a};Yt.toPrecision=function(t,e){var n,r,a=this,s=a.constructor;return t===void 0?(n=ai(a),r=Wf(a,n<=s.toExpNeg||n>=s.toExpPos)):(Ic(t,1,ex),e===void 0?e=s.rounding:Ic(e,0,8),a=Vr(new s(a),t,e),n=ai(a),r=Wf(a,t<=n||n<=s.toExpNeg,t)),r};Yt.toSignificantDigits=Yt.tosd=function(t,e){var n=this,r=n.constructor;return t===void 0?(t=r.precision,e=r.rounding):(Ic(t,1,ex),e===void 0?e=r.rounding:Ic(e,0,8)),Vr(new r(n),t,e)};Yt.toString=Yt.valueOf=Yt.val=Yt.toJSON=Yt[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=ai(t),n=t.constructor;return Wf(t,e<=n.toExpNeg||e>=n.toExpPos)};function EJ(t,e){var n,r,a,s,o,l,c,u,d=t.constructor,h=d.precision;if(!t.s||!e.s)return e.s||(e=new d(t)),ca?Vr(e,h):e;if(c=t.d,u=e.d,o=t.e,a=e.e,c=c.slice(),s=o-a,s){for(s<0?(r=c,s=-s,l=u.length):(r=u,a=o,l=c.length),o=Math.ceil(h/na),l=o>l?o+1:l+1,s>l&&(s=l,r.length=1),r.reverse();s--;)r.push(0);r.reverse()}for(l=c.length,s=u.length,l-s<0&&(s=l,r=u,u=c,c=r),n=0;s;)n=(c[--s]=c[s]+u[s]+n)/Ei|0,c[s]%=Ei;for(n&&(c.unshift(n),++a),l=c.length;c[--l]==0;)c.pop();return e.d=c,e.e=a,ca?Vr(e,h):e}function Ic(t,e,n){if(t!==~~t||t<e||t>n)throw Error(xf+t)}function Mc(t){var e,n,r,a=t.length-1,s="",o=t[0];if(a>0){for(s+=o,e=1;e<a;e++)r=t[e]+"",n=na-r.length,n&&(s+=oh(n)),s+=r;o=t[e],r=o+"",n=na-r.length,n&&(s+=oh(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}var Wu=(function(){function t(r,a){var s,o=0,l=r.length;for(r=r.slice();l--;)s=r[l]*a+o,r[l]=s%Ei|0,o=s/Ei|0;return o&&r.unshift(o),r}function e(r,a,s,o){var l,c;if(s!=o)c=s>o?1:-1;else for(l=c=0;l<s;l++)if(r[l]!=a[l]){c=r[l]>a[l]?1:-1;break}return c}function n(r,a,s){for(var o=0;s--;)r[s]-=o,o=r[s]<a[s]?1:0,r[s]=o*Ei+r[s]-a[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,a,s,o){var l,c,u,d,h,f,p,x,v,g,y,_,N,k,A,M,C,j,P=r.constructor,E=r.s==a.s?1:-1,U=r.d,L=a.d;if(!r.s)return new P(r);if(!a.s)throw Error(Cl+"Division by zero");for(c=r.e-a.e,C=L.length,A=U.length,p=new P(E),x=p.d=[],u=0;L[u]==(U[u]||0);)++u;if(L[u]>(U[u]||0)&&--c,s==null?_=s=P.precision:o?_=s+(ai(r)-ai(a))+1:_=s,_<0)return new P(0);if(_=_/na+2|0,u=0,C==1)for(d=0,L=L[0],_++;(u<A||d)&&_--;u++)N=d*Ei+(U[u]||0),x[u]=N/L|0,d=N%L|0;else{for(d=Ei/(L[0]+1)|0,d>1&&(L=t(L,d),U=t(U,d),C=L.length,A=U.length),k=C,v=U.slice(0,C),g=v.length;g<C;)v[g++]=0;j=L.slice(),j.unshift(0),M=L[0],L[1]>=Ei/2&&++M;do d=0,l=e(L,v,C,g),l<0?(y=v[0],C!=g&&(y=y*Ei+(v[1]||0)),d=y/M|0,d>1?(d>=Ei&&(d=Ei-1),h=t(L,d),f=h.length,g=v.length,l=e(h,v,f,g),l==1&&(d--,n(h,C<f?j:L,f))):(d==0&&(l=d=1),h=L.slice()),f=h.length,f<g&&h.unshift(0),n(v,h,g),l==-1&&(g=v.length,l=e(L,v,C,g),l<1&&(d++,n(v,C<g?j:L,g))),g=v.length):l===0&&(d++,v=[0]),x[u++]=d,l&&v[0]?v[g++]=U[k]||0:(v=[U[k]],g=1);while((k++<A||v[0]!==void 0)&&_--)}return x[0]||x.shift(),p.e=c,Vr(p,o?s+ai(p)+1:s)}})();function jJ(t,e){var n,r,a,s,o,l,c=0,u=0,d=t.constructor,h=d.precision;if(ai(t)>16)throw Error(lO+ai(t));if(!t.s)return new d(To);for(ca=!1,l=h,o=new d(.03125);t.abs().gte(.1);)t=t.times(o),u+=5;for(r=Math.log(qm(2,u))/Math.LN10*2+5|0,l+=r,n=a=s=new d(To),d.precision=l;;){if(a=Vr(a.times(t),l),n=n.times(++c),o=s.plus(Wu(a,n,l)),Mc(o.d).slice(0,l)===Mc(s.d).slice(0,l)){for(;u--;)s=Vr(s.times(s),l);return d.precision=h,e==null?(ca=!0,Vr(s,h)):s}s=o}}function ai(t){for(var e=t.e*na,n=t.d[0];n>=10;n/=10)e++;return e}function _j(t,e,n){if(e>t.LN10.sd())throw ca=!0,n&&(t.precision=n),Error(Cl+"LN10 precision limit exceeded");return Vr(new t(t.LN10),e)}function oh(t){for(var e="";t--;)e+="0";return e}function Hv(t,e){var n,r,a,s,o,l,c,u,d,h=1,f=10,p=t,x=p.d,v=p.constructor,g=v.precision;if(p.s<1)throw Error(Cl+(p.s?"NaN":"-Infinity"));if(p.eq(To))return new v(0);if(e==null?(ca=!1,u=g):u=e,p.eq(10))return e==null&&(ca=!0),_j(v,u);if(u+=f,v.precision=u,n=Mc(x),r=n.charAt(0),s=ai(p),Math.abs(s)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(t),n=Mc(p.d),r=n.charAt(0),h++;s=ai(p),r>1?(p=new v("0."+n),s++):p=new v(r+"."+n.slice(1))}else return c=_j(v,u+2,g).times(s+""),p=Hv(new v(r+"."+n.slice(1)),u-f).plus(c),v.precision=g,e==null?(ca=!0,Vr(p,g)):p;for(l=o=p=Wu(p.minus(To),p.plus(To),u),d=Vr(p.times(p),u),a=3;;){if(o=Vr(o.times(d),u),c=l.plus(Wu(o,new v(a),u)),Mc(c.d).slice(0,u)===Mc(l.d).slice(0,u))return l=l.times(2),s!==0&&(l=l.plus(_j(v,u+2,g).times(s+""))),l=Wu(l,new v(h),u),v.precision=g,e==null?(ca=!0,Vr(l,g)):l;l=c,a+=2}}function iG(t,e){var n,r,a;for((n=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(n<0&&(n=r),n+=+e.slice(r+1),e=e.substring(0,r)):n<0&&(n=e.length),r=0;e.charCodeAt(r)===48;)++r;for(a=e.length;e.charCodeAt(a-1)===48;)--a;if(e=e.slice(r,a),e){if(a-=r,n=n-r-1,t.e=tx(n/na),t.d=[],r=(n+1)%na,n<0&&(r+=na),r<a){for(r&&t.d.push(+e.slice(0,r)),a-=na;r<a;)t.d.push(+e.slice(r,r+=na));e=e.slice(r),r=na-e.length}else r-=a;for(;r--;)e+="0";if(t.d.push(+e),ca&&(t.e>SN||t.e<-SN))throw Error(lO+n)}else t.s=0,t.e=0,t.d=[0];return t}function Vr(t,e,n){var r,a,s,o,l,c,u,d,h=t.d;for(o=1,s=h[0];s>=10;s/=10)o++;if(r=e-o,r<0)r+=na,a=e,u=h[d=0];else{if(d=Math.ceil((r+1)/na),s=h.length,d>=s)return t;for(u=s=h[d],o=1;s>=10;s/=10)o++;r%=na,a=r-na+o}if(n!==void 0&&(s=qm(10,o-a-1),l=u/s%10|0,c=e<0||h[d+1]!==void 0||u%s,c=n<4?(l||c)&&(n==0||n==(t.s<0?3:2)):l>5||l==5&&(n==4||c||n==6&&(r>0?a>0?u/qm(10,o-a):0:h[d-1])%10&1||n==(t.s<0?8:7))),e<1||!h[0])return c?(s=ai(t),h.length=1,e=e-s-1,h[0]=qm(10,(na-e%na)%na),t.e=tx(-e/na)||0):(h.length=1,h[0]=t.e=t.s=0),t;if(r==0?(h.length=d,s=1,d--):(h.length=d+1,s=qm(10,na-r),h[d]=a>0?(u/qm(10,o-a)%qm(10,a)|0)*s:0),c)for(;;)if(d==0){(h[0]+=s)==Ei&&(h[0]=1,++t.e);break}else{if(h[d]+=s,h[d]!=Ei)break;h[d--]=0,s=1}for(r=h.length;h[--r]===0;)h.pop();if(ca&&(t.e>SN||t.e<-SN))throw Error(lO+ai(t));return t}function DJ(t,e){var n,r,a,s,o,l,c,u,d,h,f=t.constructor,p=f.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new f(t),ca?Vr(e,p):e;if(c=t.d,h=e.d,r=e.e,u=t.e,c=c.slice(),o=u-r,o){for(d=o<0,d?(n=c,o=-o,l=h.length):(n=h,r=u,l=c.length),a=Math.max(Math.ceil(p/na),l)+2,o>a&&(o=a,n.length=1),n.reverse(),a=o;a--;)n.push(0);n.reverse()}else{for(a=c.length,l=h.length,d=a<l,d&&(l=a),a=0;a<l;a++)if(c[a]!=h[a]){d=c[a]<h[a];break}o=0}for(d&&(n=c,c=h,h=n,e.s=-e.s),l=c.length,a=h.length-l;a>0;--a)c[l++]=0;for(a=h.length;a>o;){if(c[--a]<h[a]){for(s=a;s&&c[--s]===0;)c[s]=Ei-1;--c[s],c[a]+=Ei}c[a]-=h[a]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--r;return c[0]?(e.d=c,e.e=r,ca?Vr(e,p):e):new f(0)}function Wf(t,e,n){var r,a=ai(t),s=Mc(t.d),o=s.length;return e?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+oh(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(a<0?"e":"e+")+a):a<0?(s="0."+oh(-a-1)+s,n&&(r=n-o)>0&&(s+=oh(r))):a>=o?(s+=oh(a+1-o),n&&(r=n-a-1)>0&&(s=s+"."+oh(r))):((r=a+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(a+1===o&&(s+="."),s+=oh(r))),t.s<0?"-"+s:s}function sG(t,e){if(t.length>e)return t.length=e,!0}function RJ(t){var e,n,r;function a(s){var o=this;if(!(o instanceof a))return new a(s);if(o.constructor=a,s instanceof a){o.s=s.s,o.e=s.e,o.d=(s=s.d)?s.slice():s;return}if(typeof s=="number"){if(s*0!==0)throw Error(xf+s);if(s>0)o.s=1;else if(s<0)s=-s,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(s===~~s&&s<1e7){o.e=0,o.d=[s];return}return iG(o,s.toString())}else if(typeof s!="string")throw Error(xf+s);if(s.charCodeAt(0)===45?(s=s.slice(1),o.s=-1):o.s=1,hFe.test(s))iG(o,s);else throw Error(xf+s)}if(a.prototype=Yt,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=RJ,a.config=a.set=mFe,t===void 0&&(t={}),t)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e<r.length;)t.hasOwnProperty(n=r[e++])||(t[n]=this[n]);return a.config(t),a}function mFe(t){if(!t||typeof t!="object")throw Error(Cl+"Object expected");var e,n,r,a=["precision",1,ex,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(e=0;e<a.length;e+=3)if((r=t[n=a[e]])!==void 0)if(tx(r)===r&&r>=a[e+1]&&r<=a[e+2])this[n]=r;else throw Error(xf+n+": "+r);if((r=t[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(xf+n+": "+r);return this}var cO=RJ(dFe);To=new cO(1);const kr=cO;function FJ(t){var e;return t===0?e=1:e=Math.floor(new kr(t).abs().log(10).toNumber())+1,e}function LJ(t,e,n){for(var r=new kr(t),a=0,s=[];r.lt(e)&&a<1e5;)s.push(r.toNumber()),r=r.add(n),a++;return s}var OJ=t=>{var[e,n]=t,[r,a]=[e,n];return e>n&&([r,a]=[n,e]),[r,a]},IJ=(t,e,n)=>{if(t.lte(0))return new kr(0);var r=FJ(t.toNumber()),a=new kr(10).pow(r),s=t.div(a),o=r!==1?.05:.1,l=new kr(Math.ceil(s.div(o).toNumber())).add(n).mul(o),c=l.mul(a);return e?new kr(c.toNumber()):new kr(Math.ceil(c.toNumber()))},fFe=(t,e,n)=>{var r=new kr(1),a=new kr(t);if(!a.isint()&&n){var s=Math.abs(t);s<1?(r=new kr(10).pow(FJ(t)-1),a=new kr(Math.floor(a.div(r).toNumber())).mul(r)):s>1&&(a=new kr(Math.floor(t)))}else t===0?a=new kr(Math.floor((e-1)/2)):n||(a=new kr(Math.floor(t)));for(var o=Math.floor((e-1)/2),l=[],c=0;c<e;c++)l.push(a.add(new kr(c-o).mul(r)).toNumber());return l},zJ=function(e,n,r,a){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((n-e)/(r-1)))return{step:new kr(0),tickMin:new kr(0),tickMax:new kr(0)};var o=IJ(new kr(n).sub(e).div(r-1),a,s),l;e<=0&&n>=0?l=new kr(0):(l=new kr(e).add(n).div(2),l=l.sub(new kr(l).mod(o)));var c=Math.ceil(l.sub(e).div(o).toNumber()),u=Math.ceil(new kr(n).sub(l).div(o).toNumber()),d=c+u+1;return d>r?zJ(e,n,r,a,s+1):(d<r&&(u=n>0?u+(r-d):u,c=n>0?c:c+(r-d)),{step:o,tickMin:l.sub(new kr(c).mul(o)),tickMax:l.add(new kr(u).mul(o))})},pFe=function(e){var[n,r]=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(a,2),[l,c]=OJ([n,r]);if(l===-1/0||c===1/0){var u=c===1/0?[l,...Array(a-1).fill(1/0)]:[...Array(a-1).fill(-1/0),c];return n>r?u.reverse():u}if(l===c)return fFe(l,a,s);var{step:d,tickMin:h,tickMax:f}=zJ(l,c,o,s,0),p=LJ(h,f.add(new kr(.1).mul(d)),d);return n>r?p.reverse():p},gFe=function(e,n){var[r,a]=e,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,[o,l]=OJ([r,a]);if(o===-1/0||l===1/0)return[r,a];if(o===l)return[o];var c=Math.max(n,2),u=IJ(new kr(l).sub(o).div(c-1),s,0),d=[...LJ(new kr(o),new kr(l),u),l];return s===!1&&(d=d.map(h=>Math.round(h))),r>a?d.reverse():d},UJ=t=>t.rootProps.maxBarSize,bFe=t=>t.rootProps.barGap,BJ=t=>t.rootProps.barCategoryGap,xFe=t=>t.rootProps.barSize,j0=t=>t.rootProps.stackOffset,HJ=t=>t.rootProps.reverseStackOrder,uO=t=>t.options.chartName,dO=t=>t.rootProps.syncId,$J=t=>t.rootProps.syncMethod,hO=t=>t.options.eventEmitter,yFe=t=>t.rootProps.baseValue,Da={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Om={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},gc={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},Uk=(t,e)=>{if(!(!t||!e))return t!=null&&t.reversed?[e[1],e[0]]:e};function Bk(t,e,n){if(n!=="auto")return n;if(t!=null)return sc(t,e)?"category":"number"}function oG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _N(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?oG(Object(n),!0).forEach(function(r){vFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function vFe(t,e,n){return(e=wFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function wFe(t){var e=SFe(t,"string");return typeof e=="symbol"?e:e+""}function SFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var lG={allowDataOverflow:Om.allowDataOverflow,allowDecimals:Om.allowDecimals,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:Om.angleAxisId,includeHidden:!1,name:void 0,reversed:Om.reversed,scale:Om.scale,tick:Om.tick,tickCount:void 0,ticks:void 0,type:Om.type,unit:void 0},cG={allowDataOverflow:gc.allowDataOverflow,allowDecimals:gc.allowDecimals,allowDuplicatedCategory:gc.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:gc.radiusAxisId,includeHidden:gc.includeHidden,name:void 0,reversed:gc.reversed,scale:gc.scale,tick:gc.tick,tickCount:gc.tickCount,ticks:void 0,type:gc.type,unit:void 0},_Fe=(t,e)=>{if(e!=null)return t.polarAxis.angleAxis[e]},mO=ct([_Fe,AZ],(t,e)=>{var n;if(t!=null)return t;var r=(n=Bk(e,"angleAxis",lG.type))!==null&&n!==void 0?n:"category";return _N(_N({},lG),{},{type:r})}),NFe=(t,e)=>t.polarAxis.radiusAxis[e],fO=ct([NFe,AZ],(t,e)=>{var n;if(t!=null)return t;var r=(n=Bk(e,"radiusAxis",cG.type))!==null&&n!==void 0?n:"category";return _N(_N({},cG),{},{type:r})}),Hk=t=>t.polarOptions,pO=ct([fd,pd,vi],VZ),VJ=ct([Hk,pO],(t,e)=>{if(t!=null)return bs(t.innerRadius,e,0)}),qJ=ct([Hk,pO],(t,e)=>{if(t!=null)return bs(t.outerRadius,e,e*.8)}),CFe=t=>{if(t==null)return[0,0];var{startAngle:e,endAngle:n}=t;return[e,n]},GJ=ct([Hk],CFe);ct([mO,GJ],Uk);var WJ=ct([pO,VJ,qJ],(t,e,n)=>{if(!(t==null||e==null||n==null))return[e,n]});ct([fO,WJ],Uk);var KJ=ct([ar,Hk,VJ,qJ,fd,pd],(t,e,n,r,a,s)=>{if(!(t!=="centric"&&t!=="radial"||e==null||n==null||r==null)){var{cx:o,cy:l,startAngle:c,endAngle:u}=e;return{cx:bs(o,a,a/2),cy:bs(l,s,s/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),xa=(t,e)=>e,D0=(t,e,n)=>n;function $k(t){return t?.id}function XJ(t,e,n){var{chartData:r=[]}=e,{allowDuplicatedCategory:a,dataKey:s}=n,o=new Map;return t.forEach(l=>{var c,u=(c=l.data)!==null&&c!==void 0?c:r;if(!(u==null||u.length===0)){var d=$k(l);u.forEach((h,f)=>{var p=s==null||a?f:String(yr(h,s,null)),x=yr(h,l.dataKey,0),v;o.has(p)?v=o.get(p):v={},Object.assign(v,{[d]:x}),o.set(p,v)})}}),Array.from(o.values())}function Vk(t){return"stackId"in t&&t.stackId!=null&&t.dataKey!=null}var qk=(t,e)=>t===e?!0:t==null||e==null?!1:t[0]===e[0]&&t[1]===e[1];function Gk(t,e){return Array.isArray(t)&&Array.isArray(e)&&t.length===0&&e.length===0?!0:t===e}function kFe(t,e){if(t.length===e.length){for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}return!1}var Ii=t=>{var e=ar(t);return e==="horizontal"?"xAxis":e==="vertical"?"yAxis":e==="centric"?"angleAxis":"radiusAxis"},nx=t=>t.tooltip.settings.axisId;function AFe(t){if(t in Ey)return Ey[t]();var e="scale".concat(y0(t));if(e in Ey)return Ey[e]()}function uG(t){var e=t.ticks,n=t.bandwidth,r=t.range(),a=[Math.min(...r),Math.max(...r)];return{domain:()=>t.domain(),range:(function(s){function o(){return s.apply(this,arguments)}return o.toString=function(){return s.toString()},o})(()=>a),rangeMin:()=>a[0],rangeMax:()=>a[1],isInRange(s){var o=a[0],l=a[1];return o<=l?s>=o&&s<=l:s>=l&&s<=o},bandwidth:n?()=>n.call(t):void 0,ticks:e?s=>e.call(t,s):void 0,map:(s,o)=>{var l=t(s);if(l!=null){if(t.bandwidth&&o!==null&&o!==void 0&&o.position){var c=t.bandwidth();switch(o.position){case"middle":l+=c/2;break;case"end":l+=c;break}}return l}}}}function dG(t,e,n){if(typeof t=="function")return uG(t.copy().domain(e).range(n));if(t!=null){var r=AFe(t);if(r!=null)return r.domain(e).range(n),uG(r)}}var YJ=(t,e)=>{if(e!=null)switch(t){case"linear":{if(!ud(e)){for(var n,r,a=0;a<e.length;a++){var s=e[a];Nn(s)&&((n===void 0||s<n)&&(n=s),(r===void 0||s>r)&&(r=s))}return n!==void 0&&r!==void 0?[n,r]:void 0}return e}default:return e}};function hG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function NN(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?hG(Object(n),!0).forEach(function(r){TFe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):hG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function TFe(t,e,n){return(e=MFe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function MFe(t){var e=PFe(t,"string");return typeof e=="symbol"?e:e+""}function PFe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var tR=[0,"auto"],Mi={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:void 0,height:30,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"bottom",padding:{left:0,right:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"category",unit:void 0},QJ=(t,e)=>t.cartesianAxis.xAxis[e],qc=(t,e)=>{var n=QJ(t,e);return n??Mi},Pi={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:tR,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,width:_0},ZJ=(t,e)=>t.cartesianAxis.yAxis[e],Gc=(t,e)=>{var n=ZJ(t,e);return n??Pi},EFe={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},gO=(t,e)=>{var n=t.cartesianAxis.zAxis[e];return n??EFe},La=(t,e,n)=>{switch(e){case"xAxis":return qc(t,n);case"yAxis":return Gc(t,n);case"zAxis":return gO(t,n);case"angleAxis":return mO(t,n);case"radiusAxis":return fO(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},jFe=(t,e,n)=>{switch(e){case"xAxis":return qc(t,n);case"yAxis":return Gc(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},rx=(t,e,n)=>{switch(e){case"xAxis":return qc(t,n);case"yAxis":return Gc(t,n);case"angleAxis":return mO(t,n);case"radiusAxis":return fO(t,n);default:throw new Error("Unexpected axis type: ".concat(e))}},JJ=t=>t.graphicalItems.cartesianItems.some(e=>e.type==="bar")||t.graphicalItems.polarItems.some(e=>e.type==="radialBar");function bO(t,e){return n=>{switch(t){case"xAxis":return"xAxisId"in n&&n.xAxisId===e;case"yAxis":return"yAxisId"in n&&n.yAxisId===e;case"zAxis":return"zAxisId"in n&&n.zAxisId===e;case"angleAxis":return"angleAxisId"in n&&n.angleAxisId===e;case"radiusAxis":return"radiusAxisId"in n&&n.radiusAxisId===e;default:return!1}}}var R0=t=>t.graphicalItems.cartesianItems,DFe=ct([xa,D0],bO),xO=(t,e,n)=>t.filter(n).filter(r=>e?.includeHidden===!0?!0:!r.hide),F0=ct([R0,La,DFe],xO,{memoizeOptions:{resultEqualityCheck:Gk}}),eee=ct([F0],t=>t.filter(e=>e.type==="area"||e.type==="bar").filter(Vk)),tee=t=>t.filter(e=>!("stackId"in e)||e.stackId===void 0),RFe=ct([F0],tee),yO=t=>t.map(e=>e.data).filter(Boolean).flat(1),FFe=ct([F0],yO,{memoizeOptions:{resultEqualityCheck:Gk}}),vO=(t,e)=>{var{chartData:n=[],dataStartIndex:r,dataEndIndex:a}=e;return t.length>0?t:n.slice(r,a+1)},wO=ct([FFe,oO],vO),SO=(t,e,n)=>e?.dataKey!=null?t.map(r=>({value:yr(r,e.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>t.map(a=>({value:yr(a,r)}))):t.map(r=>({value:r})),Wk=ct([wO,La,F0],SO);function nee(t,e){switch(t){case"xAxis":return e.direction==="x";case"yAxis":return e.direction==="y";default:return!1}}function r1(t){if(_l(t)||t instanceof Date){var e=Number(t);if(Nn(e))return e}}function mG(t){if(Array.isArray(t)){var e=[r1(t[0]),r1(t[1])];return ud(e)?e:void 0}var n=r1(t);if(n!=null)return[n,n]}function dd(t){return t.map(r1).filter(Js)}function LFe(t,e,n){return!n||typeof e!="number"||Jl(e)?[]:n.length?dd(n.flatMap(r=>{var a=yr(t,r.dataKey),s,o;if(Array.isArray(a)?[s,o]=a:s=o=a,!(!Nn(s)||!Nn(o)))return[e-s,e+o]})):[]}var _i=t=>{var e=Ii(t),n=nx(t);return rx(t,e,n)},L0=ct([_i],t=>t?.dataKey),OFe=ct([eee,oO,_i],XJ),ree=(t,e,n,r)=>{var a={},s=e.reduce((o,l)=>{if(l.stackId==null)return o;var c=o[l.stackId];return c==null&&(c=[]),c.push(l),o[l.stackId]=c,o},a);return Object.fromEntries(Object.entries(s).map(o=>{var[l,c]=o,u=r?[...c].reverse():c,d=u.map($k);return[l,{stackedData:aje(t,d,n),graphicalItems:u}]}))},CN=ct([OFe,eee,j0,HJ],ree),aee=(t,e,n,r)=>{var{dataStartIndex:a,dataEndIndex:s}=e;if(r==null&&n!=="zAxis"){var o=lje(t,a,s);if(!(o!=null&&o[0]===0&&o[1]===0))return o}},IFe=ct([La],t=>t.allowDataOverflow),_O=t=>{var e;if(t==null||!("domain"in t))return tR;if(t.domain!=null)return t.domain;if("ticks"in t&&t.ticks!=null){if(t.type==="number"){var n=dd(t.ticks);return[Math.min(...n),Math.max(...n)]}if(t.type==="category")return t.ticks.map(String)}return(e=t?.domain)!==null&&e!==void 0?e:tR},NO=ct([La],_O),CO=ct([NO,IFe],MJ),zFe=ct([CN,bd,xa,CO],aee,{memoizeOptions:{resultEqualityCheck:qk}}),Kk=t=>t.errorBars,UFe=(t,e,n)=>t.flatMap(r=>e[r.id]).filter(Boolean).filter(r=>nee(n,r)),kN=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];var a=n.filter(Boolean);if(a.length!==0){var s=a.flat(),o=Math.min(...s),l=Math.max(...s);return[o,l]}},kO=(t,e,n,r,a)=>{var s,o;if(n.length>0&&t.forEach(l=>{n.forEach(c=>{var u,d,h=(u=r[c.id])===null||u===void 0?void 0:u.filter(y=>nee(a,y)),f=yr(l,(d=e.dataKey)!==null&&d!==void 0?d:c.dataKey),p=LFe(l,f,h);if(p.length>=2){var x=Math.min(...p),v=Math.max(...p);(s==null||x<s)&&(s=x),(o==null||v>o)&&(o=v)}var g=mG(f);g!=null&&(s=s==null?g[0]:Math.min(s,g[0]),o=o==null?g[1]:Math.max(o,g[1]))})}),e?.dataKey!=null&&t.forEach(l=>{var c=mG(yr(l,e.dataKey));c!=null&&(s=s==null?c[0]:Math.min(s,c[0]),o=o==null?c[1]:Math.max(o,c[1]))}),Nn(s)&&Nn(o))return[s,o]},BFe=ct([wO,La,RFe,Kk,xa],kO,{memoizeOptions:{resultEqualityCheck:qk}});function HFe(t){var{value:e}=t;if(_l(e)||e instanceof Date)return e}var $Fe=(t,e,n)=>{var r=t.map(HFe).filter(a=>a!=null);return n&&(e.dataKey==null||e.allowDuplicatedCategory&&SQ(r))?KZ(0,t.length):e.allowDuplicatedCategory?r:Array.from(new Set(r))},iee=t=>t.referenceElements.dots,ax=(t,e,n)=>t.filter(r=>r.ifOverflow==="extendDomain").filter(r=>e==="xAxis"?r.xAxisId===n:r.yAxisId===n),VFe=ct([iee,xa,D0],ax),see=t=>t.referenceElements.areas,qFe=ct([see,xa,D0],ax),oee=t=>t.referenceElements.lines,GFe=ct([oee,xa,D0],ax),lee=(t,e)=>{if(t!=null){var n=dd(t.map(r=>e==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},WFe=ct(VFe,xa,lee),cee=(t,e)=>{if(t!=null){var n=dd(t.flatMap(r=>[e==="xAxis"?r.x1:r.y1,e==="xAxis"?r.x2:r.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},KFe=ct([qFe,xa],cee);function XFe(t){var e;if(t.x!=null)return dd([t.x]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.x);return n==null||n.length===0?[]:dd(n)}function YFe(t){var e;if(t.y!=null)return dd([t.y]);var n=(e=t.segment)===null||e===void 0?void 0:e.map(r=>r.y);return n==null||n.length===0?[]:dd(n)}var uee=(t,e)=>{if(t!=null){var n=t.flatMap(r=>e==="xAxis"?XFe(r):YFe(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},QFe=ct([GFe,xa],uee),ZFe=ct(WFe,QFe,KFe,(t,e,n)=>kN(t,n,e)),AO=(t,e,n,r,a,s,o,l)=>{if(n!=null)return n;var c=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",u=c?kN(r,s,a):kN(s,a);return uFe(e,u,t.allowDataOverflow)},JFe=ct([La,NO,CO,zFe,BFe,ZFe,ar,xa],AO,{memoizeOptions:{resultEqualityCheck:qk}}),eLe=[0,1],TO=(t,e,n,r,a,s,o)=>{if(!((t==null||n==null||n.length===0)&&o===void 0)){var{dataKey:l,type:c}=t,u=sc(e,s);if(u&&l==null){var d;return KZ(0,(d=n?.length)!==null&&d!==void 0?d:0)}return c==="category"?$Fe(r,t,u):a==="expand"?eLe:o}},MO=ct([La,ar,wO,Wk,j0,xa,JFe],TO);function tLe(t){return t in Ey}var dee=(t,e,n)=>{if(t!=null){var{scale:r,type:a}=t;if(r==="auto")return a==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!e)?"point":a==="category"?"band":"linear";if(typeof r=="string"){var s="scale".concat(y0(r));return tLe(s)?s:"point"}}},im=ct([La,JJ,uO],dee);function PO(t,e,n,r){if(!(n==null||r==null))return typeof t.scale=="function"?dG(t.scale,n,r):dG(e,n,r)}var EO=(t,e,n)=>{var r=_O(e);if(!(n!=="auto"&&n!=="linear")){if(e!=null&&e.tickCount&&Array.isArray(r)&&(r[0]==="auto"||r[1]==="auto")&&ud(t))return pFe(t,e.tickCount,e.allowDecimals);if(e!=null&&e.tickCount&&e.type==="number"&&ud(t))return gFe(t,e.tickCount,e.allowDecimals)}},jO=ct([MO,rx,im],EO),DO=(t,e,n,r)=>{if(r!=="angleAxis"&&t?.type==="number"&&ud(e)&&Array.isArray(n)&&n.length>0){var a,s,o=e[0],l=(a=n[0])!==null&&a!==void 0?a:0,c=e[1],u=(s=n[n.length-1])!==null&&s!==void 0?s:0;return[Math.min(o,l),Math.max(c,u)]}return e},nLe=ct([La,MO,jO,xa],DO),rLe=ct(Wk,La,(t,e)=>{if(!(!e||e.type!=="number")){var n=1/0,r=Array.from(dd(t.map(h=>h.value))).sort((h,f)=>h-f),a=r[0],s=r[r.length-1];if(a==null||s==null)return 1/0;var o=s-a;if(o===0)return 1/0;for(var l=0;l<r.length-1;l++){var c=r[l],u=r[l+1];if(!(c==null||u==null)){var d=u-c;n=Math.min(n,d)}}return n/o}}),hee=ct(rLe,ar,BJ,vi,(t,e,n,r,a)=>a,(t,e,n,r,a)=>{if(!Nn(t))return 0;var s=e==="vertical"?r.height:r.width;if(a==="gap")return t*s/2;if(a==="no-gap"){var o=bs(n,t*s),l=t*s/2;return l-o-(l-o)/s*o}return 0}),aLe=(t,e,n)=>{var r=qc(t,e);return r==null||typeof r.padding!="string"?0:hee(t,"xAxis",e,n,r.padding)},iLe=(t,e,n)=>{var r=Gc(t,e);return r==null||typeof r.padding!="string"?0:hee(t,"yAxis",e,n,r.padding)},sLe=ct(qc,aLe,(t,e)=>{var n,r;if(t==null)return{left:0,right:0};var{padding:a}=t;return typeof a=="string"?{left:e,right:e}:{left:((n=a.left)!==null&&n!==void 0?n:0)+e,right:((r=a.right)!==null&&r!==void 0?r:0)+e}}),oLe=ct(Gc,iLe,(t,e)=>{var n,r;if(t==null)return{top:0,bottom:0};var{padding:a}=t;return typeof a=="string"?{top:e,bottom:e}:{top:((n=a.top)!==null&&n!==void 0?n:0)+e,bottom:((r=a.bottom)!==null&&r!==void 0?r:0)+e}}),lLe=ct([vi,sLe,Mk,Tk,(t,e,n)=>n],(t,e,n,r,a)=>{var{padding:s}=r;return a?[s.left,n.width-s.right]:[t.left+e.left,t.left+t.width-e.right]}),cLe=ct([vi,ar,oLe,Mk,Tk,(t,e,n)=>n],(t,e,n,r,a,s)=>{var{padding:o}=a;return s?[r.height-o.bottom,o.top]:e==="horizontal"?[t.top+t.height-n.bottom,t.top+n.top]:[t.top+n.top,t.top+t.height-n.bottom]}),O0=(t,e,n,r)=>{var a;switch(e){case"xAxis":return lLe(t,n,r);case"yAxis":return cLe(t,n,r);case"zAxis":return(a=gO(t,n))===null||a===void 0?void 0:a.range;case"angleAxis":return GJ(t);case"radiusAxis":return WJ(t,n);default:return}},mee=ct([La,O0],Uk),uLe=ct([im,nLe],YJ),Mb=ct([La,im,uLe,mee],PO);ct([F0,Kk,xa],UFe);function fee(t,e){return t.id<e.id?-1:t.id>e.id?1:0}var Xk=(t,e)=>e,Yk=(t,e,n)=>n,dLe=ct(kk,Xk,Yk,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(fee)),hLe=ct(Ak,Xk,Yk,(t,e,n)=>t.filter(r=>r.orientation===e).filter(r=>r.mirror===n).sort(fee)),pee=(t,e)=>({width:t.width,height:e.height}),mLe=(t,e)=>{var n=typeof e.width=="number"?e.width:_0;return{width:n,height:t.height}},gee=ct(vi,qc,pee),fLe=(t,e,n)=>{switch(e){case"top":return t.top;case"bottom":return n-t.bottom;default:return 0}},pLe=(t,e,n)=>{switch(e){case"left":return t.left;case"right":return n-t.right;default:return 0}},gLe=ct(pd,vi,dLe,Xk,Yk,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=pee(e,l);o==null&&(o=fLe(e,r,t));var u=r==="top"&&!a||r==="bottom"&&a;s[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),s}),bLe=ct(fd,vi,hLe,Xk,Yk,(t,e,n,r,a)=>{var s={},o;return n.forEach(l=>{var c=mLe(e,l);o==null&&(o=pLe(e,r,t));var u=r==="left"&&!a||r==="right"&&a;s[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),s}),xLe=(t,e)=>{var n=qc(t,e);if(n!=null)return gLe(t,n.orientation,n.mirror)},yLe=ct([vi,qc,xLe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:t.left,y:0}:{x:t.left,y:a}}}),vLe=(t,e)=>{var n=Gc(t,e);if(n!=null)return bLe(t,n.orientation,n.mirror)},wLe=ct([vi,Gc,vLe,(t,e)=>e],(t,e,n,r)=>{if(e!=null){var a=n?.[r];return a==null?{x:0,y:t.top}:{x:a,y:t.top}}}),bee=ct(vi,Gc,(t,e)=>{var n=typeof e.width=="number"?e.width:_0;return{width:n,height:t.height}}),fG=(t,e,n)=>{switch(e){case"xAxis":return gee(t,n).width;case"yAxis":return bee(t,n).height;default:return}},xee=(t,e,n,r)=>{if(n!=null){var{allowDuplicatedCategory:a,type:s,dataKey:o}=n,l=sc(t,r),c=e.map(u=>u.value);if(o&&l&&s==="category"&&a&&SQ(c))return c}},RO=ct([ar,Wk,La,xa],xee),yee=(t,e,n,r)=>{if(!(n==null||n.dataKey==null)){var{type:a,scale:s}=n,o=sc(t,r);if(o&&(a==="number"||s!=="auto"))return e.map(l=>l.value)}},FO=ct([ar,Wk,rx,xa],yee),pG=ct([ar,jFe,im,Mb,RO,FO,O0,jO,xa],(t,e,n,r,a,s,o,l,c)=>{if(e!=null){var u=sc(t,c);return{angle:e.angle,interval:e.interval,minTickGap:e.minTickGap,orientation:e.orientation,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit,axisType:c,categoricalDomain:s,duplicateDomain:a,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),SLe=(t,e,n,r,a,s,o,l,c)=>{if(!(e==null||r==null)){var u=sc(t,c),{type:d,ticks:h,tickCount:f}=e,p=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,x=d==="category"&&r.bandwidth?r.bandwidth()/p:0;x=c==="angleAxis"&&s!=null&&s.length>=2?Ri(s[0]-s[1])*2*x:x;var v=h||a;return v?v.map((g,y)=>{var _=o?o.indexOf(g):g,N=r.map(_);return Nn(N)?{index:y,coordinate:N+x,value:g,offset:x}:null}).filter(Js):u&&l?l.map((g,y)=>{var _=r.map(g);return Nn(_)?{coordinate:_+x,value:g,index:y,offset:x}:null}).filter(Js):r.ticks?r.ticks(f).map((g,y)=>{var _=r.map(g);return Nn(_)?{coordinate:_+x,value:g,index:y,offset:x}:null}).filter(Js):r.domain().map((g,y)=>{var _=r.map(g);return Nn(_)?{coordinate:_+x,value:o?o[g]:g,index:y,offset:x}:null}).filter(Js)}},vee=ct([ar,rx,im,Mb,jO,O0,RO,FO,xa],SLe),_Le=(t,e,n,r,a,s,o)=>{if(!(e==null||n==null||r==null||r[0]===r[1])){var l=sc(t,o),{tickCount:c}=e,u=0;return u=o==="angleAxis"&&r?.length>=2?Ri(r[0]-r[1])*2*u:u,l&&s?s.map((d,h)=>{var f=n.map(d);return Nn(f)?{coordinate:f+u,value:d,index:h,offset:u}:null}).filter(Js):n.ticks?n.ticks(c).map((d,h)=>{var f=n.map(d);return Nn(f)?{coordinate:f+u,value:d,index:h,offset:u}:null}).filter(Js):n.domain().map((d,h)=>{var f=n.map(d);return Nn(f)?{coordinate:f+u,value:a?a[d]:d,index:h,offset:u}:null}).filter(Js)}},zc=ct([ar,rx,Mb,O0,RO,FO,xa],_Le),Uc=ct(La,Mb,(t,e)=>{if(!(t==null||e==null))return NN(NN({},t),{},{scale:e})}),NLe=ct([La,im,MO,mee],PO);ct((t,e,n)=>gO(t,n),NLe,(t,e)=>{if(!(t==null||e==null))return NN(NN({},t),{},{scale:e})});var CLe=ct([ar,kk,Ak],(t,e,n)=>{switch(t){case"horizontal":return e.some(r=>r.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(r=>r.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),wee=t=>t.options.defaultTooltipEventType,See=t=>t.options.validateTooltipEventTypes;function _ee(t,e,n){if(t==null)return e;var r=t?"axis":"item";return n==null?e:n.includes(r)?r:e}function LO(t,e){var n=wee(t),r=See(t);return _ee(e,n,r)}function kLe(t){return Kt(e=>LO(e,t))}var Nee=(t,e)=>{var n,r=Number(e);if(!(Jl(r)||e==null))return r>=0?t==null||(n=t[r])===null||n===void 0?void 0:n.value:void 0},ALe=t=>t.tooltip.settings,ph={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},TLe={itemInteraction:{click:ph,hover:ph},axisInteraction:{click:ph,hover:ph},keyboardInteraction:ph,syncInteraction:{active:!1,index:null,dataKey:void 0,label:void 0,coordinate:void 0,sourceViewBox:void 0,graphicalItemId:void 0},tooltipItemPayloads:[],settings:{shared:void 0,trigger:"hover",axisId:0,active:!1,defaultIndex:void 0}},Cee=lo({name:"tooltip",initialState:TLe,reducers:{addTooltipEntrySettings:{reducer(t,e){t.tooltipItemPayloads.push(e.payload)},prepare:la()},replaceTooltipEntrySettings:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Kl(t).tooltipItemPayloads.indexOf(n);a>-1&&(t.tooltipItemPayloads[a]=r)},prepare:la()},removeTooltipEntrySettings:{reducer(t,e){var n=Kl(t).tooltipItemPayloads.indexOf(e.payload);n>-1&&t.tooltipItemPayloads.splice(n,1)},prepare:la()},setTooltipSettingsState(t,e){t.settings=e.payload},setActiveMouseOverItemIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.itemInteraction.hover.active=!0,t.itemInteraction.hover.index=e.payload.activeIndex,t.itemInteraction.hover.dataKey=e.payload.activeDataKey,t.itemInteraction.hover.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.hover.coordinate=e.payload.activeCoordinate},mouseLeaveChart(t){t.itemInteraction.hover.active=!1,t.axisInteraction.hover.active=!1},mouseLeaveItem(t){t.itemInteraction.hover.active=!1},setActiveClickItemIndex(t,e){t.syncInteraction.active=!1,t.itemInteraction.click.active=!0,t.keyboardInteraction.active=!1,t.itemInteraction.click.index=e.payload.activeIndex,t.itemInteraction.click.dataKey=e.payload.activeDataKey,t.itemInteraction.click.graphicalItemId=e.payload.activeGraphicalItemId,t.itemInteraction.click.coordinate=e.payload.activeCoordinate},setMouseOverAxisIndex(t,e){t.syncInteraction.active=!1,t.axisInteraction.hover.active=!0,t.keyboardInteraction.active=!1,t.axisInteraction.hover.index=e.payload.activeIndex,t.axisInteraction.hover.dataKey=e.payload.activeDataKey,t.axisInteraction.hover.coordinate=e.payload.activeCoordinate},setMouseClickAxisIndex(t,e){t.syncInteraction.active=!1,t.keyboardInteraction.active=!1,t.axisInteraction.click.active=!0,t.axisInteraction.click.index=e.payload.activeIndex,t.axisInteraction.click.dataKey=e.payload.activeDataKey,t.axisInteraction.click.coordinate=e.payload.activeCoordinate},setSyncInteraction(t,e){t.syncInteraction=e.payload},setKeyboardInteraction(t,e){t.keyboardInteraction.active=e.payload.active,t.keyboardInteraction.index=e.payload.activeIndex,t.keyboardInteraction.coordinate=e.payload.activeCoordinate}}}),{addTooltipEntrySettings:MLe,replaceTooltipEntrySettings:PLe,removeTooltipEntrySettings:ELe,setTooltipSettingsState:jLe,setActiveMouseOverItemIndex:kee,mouseLeaveItem:DLe,mouseLeaveChart:Aee,setActiveClickItemIndex:RLe,setMouseOverAxisIndex:Tee,setMouseClickAxisIndex:FLe,setSyncInteraction:nR,setKeyboardInteraction:rR}=Cee.actions,LLe=Cee.reducer;function gG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function x_(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gG(Object(n),!0).forEach(function(r){OLe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function OLe(t,e,n){return(e=ILe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ILe(t){var e=zLe(t,"string");return typeof e=="symbol"?e:e+""}function zLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ULe(t,e,n){return e==="axis"?n==="click"?t.axisInteraction.click:t.axisInteraction.hover:n==="click"?t.itemInteraction.click:t.itemInteraction.hover}function BLe(t){return t.index!=null}var Mee=(t,e,n,r)=>{if(e==null)return ph;var a=ULe(t,e,n);if(a==null)return ph;if(a.active)return a;if(t.keyboardInteraction.active)return t.keyboardInteraction;if(t.syncInteraction.active&&t.syncInteraction.index!=null)return t.syncInteraction;var s=t.settings.active===!0;if(BLe(a)){if(s)return x_(x_({},a),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return x_(x_({},ph),{},{coordinate:a.coordinate})};function HLe(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date){var e=t.valueOf();return Number.isFinite(e)?e:void 0}var n=Number(t);return Number.isFinite(n)?n:void 0}function $Le(t,e){var n=HLe(t),r=e[0],a=e[1];if(n===void 0)return!1;var s=Math.min(r,a),o=Math.max(r,a);return n>=s&&n<=o}function VLe(t,e,n){if(n==null||e==null)return!0;var r=yr(t,e);return r==null||!ud(n)?!0:$Le(r,n)}var OO=(t,e,n,r)=>{var a=t?.index;if(a==null)return null;var s=Number(a);if(!Nn(s))return a;var o=0,l=1/0;e.length>0&&(l=e.length-1);var c=Math.max(o,Math.min(s,l)),u=e[c];return u==null||VLe(u,n,r)?String(c):null},Pee=(t,e,n,r,a,s,o)=>{if(s!=null){var l=o[0],c=l?.getPosition(s);if(c!=null)return c;var u=a?.[Number(s)];if(u)return n==="horizontal"?{x:u.coordinate,y:(r.top+e)/2}:{x:(r.left+t)/2,y:u.coordinate}}},Eee=(t,e,n,r)=>{if(e==="axis")return t.tooltipItemPayloads;if(t.tooltipItemPayloads.length===0)return[];var a;if(n==="hover"?a=t.itemInteraction.hover.graphicalItemId:a=t.itemInteraction.click.graphicalItemId,a==null&&r!=null){var s=t.tooltipItemPayloads[0];return s!=null?[s]:[]}return t.tooltipItemPayloads.filter(o=>{var l;return((l=o.settings)===null||l===void 0?void 0:l.graphicalItemId)===a})},jee=t=>t.options.tooltipPayloadSearcher,ix=t=>t.tooltip;function bG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function xG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?bG(Object(n),!0).forEach(function(r){qLe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):bG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function qLe(t,e,n){return(e=GLe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function GLe(t){var e=WLe(t,"string");return typeof e=="symbol"?e:e+""}function WLe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function KLe(t,e){return t??e}var Dee=(t,e,n,r,a,s,o)=>{if(!(e==null||s==null)){var{chartData:l,computedData:c,dataStartIndex:u,dataEndIndex:d}=n,h=[];return t.reduce((f,p)=>{var x,{dataDefinedOnItem:v,settings:g}=p,y=KLe(v,l),_=Array.isArray(y)?gZ(y,u,d):y,N=(x=g?.dataKey)!==null&&x!==void 0?x:r,k=g?.nameKey,A;if(r&&Array.isArray(_)&&!Array.isArray(_[0])&&o==="axis"?A=_Q(_,r,a):A=s(_,e,c,k),Array.isArray(A))A.forEach(C=>{var j=xG(xG({},g),{},{name:C.name,unit:C.unit,color:void 0,fill:void 0});f.push(gV({tooltipEntrySettings:j,dataKey:C.dataKey,payload:C.payload,value:yr(C.payload,C.dataKey),name:C.name}))});else{var M;f.push(gV({tooltipEntrySettings:g,dataKey:N,payload:A,value:yr(A,N),name:(M=yr(A,k))!==null&&M!==void 0?M:g?.name}))}return f},h)}},IO=ct([_i,JJ,uO],dee),XLe=ct([t=>t.graphicalItems.cartesianItems,t=>t.graphicalItems.polarItems],(t,e)=>[...t,...e]),YLe=ct([Ii,nx],bO),sx=ct([XLe,_i,YLe],xO,{memoizeOptions:{resultEqualityCheck:Gk}}),QLe=ct([sx],t=>t.filter(Vk)),ZLe=ct([sx],yO,{memoizeOptions:{resultEqualityCheck:Gk}}),ox=ct([ZLe,bd],vO),JLe=ct([QLe,bd,_i],XJ),zO=ct([ox,_i,sx],SO),Ree=ct([_i],_O),eOe=ct([_i],t=>t.allowDataOverflow),Fee=ct([Ree,eOe],MJ),tOe=ct([sx],t=>t.filter(Vk)),nOe=ct([JLe,tOe,j0,HJ],ree),rOe=ct([nOe,bd,Ii,Fee],aee),aOe=ct([sx],tee),iOe=ct([ox,_i,aOe,Kk,Ii],kO,{memoizeOptions:{resultEqualityCheck:qk}}),sOe=ct([iee,Ii,nx],ax),oOe=ct([sOe,Ii],lee),lOe=ct([see,Ii,nx],ax),cOe=ct([lOe,Ii],cee),uOe=ct([oee,Ii,nx],ax),dOe=ct([uOe,Ii],uee),hOe=ct([oOe,dOe,cOe],kN),mOe=ct([_i,Ree,Fee,rOe,iOe,hOe,ar,Ii],AO),I0=ct([_i,ar,ox,zO,j0,Ii,mOe],TO),fOe=ct([I0,_i,IO],EO),pOe=ct([_i,I0,fOe,Ii],DO),Lee=t=>{var e=Ii(t),n=nx(t),r=!1;return O0(t,e,n,r)},Oee=ct([_i,Lee],Uk),Iee=ct([_i,IO,pOe,Oee],PO),gOe=ct([ar,zO,_i,Ii],xee),bOe=ct([ar,zO,_i,Ii],yee),xOe=(t,e,n,r,a,s,o,l)=>{if(e){var{type:c}=e,u=sc(t,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,h=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return h=l==="angleAxis"&&a!=null&&a?.length>=2?Ri(a[0]-a[1])*2*h:h,u&&o?o.map((f,p)=>{var x=r.map(f);return Nn(x)?{coordinate:x+h,value:f,index:p,offset:h}:null}).filter(Js):r.domain().map((f,p)=>{var x=r.map(f);return Nn(x)?{coordinate:x+h,value:s?s[f]:f,index:p,offset:h}:null}).filter(Js)}}},xd=ct([ar,_i,IO,Iee,Lee,gOe,bOe,Ii],xOe),UO=ct([wee,See,ALe],(t,e,n)=>_ee(n.shared,t,e)),zee=t=>t.tooltip.settings.trigger,BO=t=>t.tooltip.settings.defaultIndex,z0=ct([ix,UO,zee,BO],Mee),Yh=ct([z0,ox,L0,I0],OO),Uee=ct([xd,Yh],Nee),HO=ct([z0],t=>{if(t)return t.dataKey}),yOe=ct([z0],t=>{if(t)return t.graphicalItemId}),Bee=ct([ix,UO,zee,BO],Eee),vOe=ct([fd,pd,ar,vi,xd,BO,Bee],Pee),wOe=ct([z0,vOe],(t,e)=>t!=null&&t.coordinate?t.coordinate:e),SOe=ct([z0],t=>{var e;return(e=t?.active)!==null&&e!==void 0?e:!1}),_Oe=ct([Bee,Yh,bd,L0,Uee,jee,UO],Dee),NOe=ct([_Oe],t=>{if(t!=null){var e=t.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(e))}});function yG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function vG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?yG(Object(n),!0).forEach(function(r){COe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):yG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function COe(t,e,n){return(e=kOe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function kOe(t){var e=AOe(t,"string");return typeof e=="symbol"?e:e+""}function AOe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var TOe=()=>Kt(_i),MOe=()=>{var t=TOe(),e=Kt(xd),n=Kt(Iee);return Xh(!t||!n?void 0:vG(vG({},t),{},{scale:n}),e)};function wG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _g(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?wG(Object(n),!0).forEach(function(r){POe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):wG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function POe(t,e,n){return(e=EOe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function EOe(t){var e=jOe(t,"string");return typeof e=="symbol"?e:e+""}function jOe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var DOe=(t,e,n,r)=>{var a=e.find(s=>s&&s.index===n);if(a){if(t==="horizontal")return{x:a.coordinate,y:r.chartY};if(t==="vertical")return{x:r.chartX,y:a.coordinate}}return{x:0,y:0}},ROe=(t,e,n,r)=>{var a=e.find(u=>u&&u.index===n);if(a){if(t==="centric"){var s=a.coordinate,{radius:o}=r;return _g(_g(_g({},r),ei(r.cx,r.cy,o,s)),{},{angle:s,radius:o})}var l=a.coordinate,{angle:c}=r;return _g(_g(_g({},r),ei(r.cx,r.cy,l,c)),{},{angle:c,radius:l})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function FOe(t,e){var{chartX:n,chartY:r}=t;return n>=e.left&&n<=e.left+e.width&&r>=e.top&&r<=e.top+e.height}var Hee=(t,e,n,r,a)=>{var s,o=(s=e?.length)!==null&&s!==void 0?s:0;if(o<=1||t==null)return 0;if(r==="angleAxis"&&a!=null&&Math.abs(Math.abs(a[1]-a[0])-360)<=1e-6)for(var l=0;l<o;l++){var c,u,d,h,f,p=l>0?(c=n[l-1])===null||c===void 0?void 0:c.coordinate:(u=n[o-1])===null||u===void 0?void 0:u.coordinate,x=(d=n[l])===null||d===void 0?void 0:d.coordinate,v=l>=o-1?(h=n[0])===null||h===void 0?void 0:h.coordinate:(f=n[l+1])===null||f===void 0?void 0:f.coordinate,g=void 0;if(!(p==null||x==null||v==null))if(Ri(x-p)!==Ri(v-x)){var y=[];if(Ri(v-x)===Ri(a[1]-a[0])){g=v;var _=x+a[1]-a[0];y[0]=Math.min(_,(_+p)/2),y[1]=Math.max(_,(_+p)/2)}else{g=p;var N=v+a[1]-a[0];y[0]=Math.min(x,(N+x)/2),y[1]=Math.max(x,(N+x)/2)}var k=[Math.min(x,(g+x)/2),Math.max(x,(g+x)/2)];if(t>k[0]&&t<=k[1]||t>=y[0]&&t<=y[1]){var A;return(A=n[l])===null||A===void 0?void 0:A.index}}else{var M=Math.min(p,v),C=Math.max(p,v);if(t>(M+x)/2&&t<=(C+x)/2){var j;return(j=n[l])===null||j===void 0?void 0:j.index}}}else if(e)for(var P=0;P<o;P++){var E=e[P];if(E!=null){var U=e[P+1],L=e[P-1];if(P===0&&U!=null&&t<=(E.coordinate+U.coordinate)/2||P===o-1&&L!=null&&t>(E.coordinate+L.coordinate)/2||P>0&&P<o-1&&L!=null&&U!=null&&t>(E.coordinate+L.coordinate)/2&&t<=(E.coordinate+U.coordinate)/2)return E.index}}return-1},$ee=()=>Kt(uO),$O=(t,e)=>e,Vee=(t,e,n)=>n,VO=(t,e,n,r)=>r,LOe=ct(xd,t=>gk(t,e=>e.coordinate)),qO=ct([ix,$O,Vee,VO],Mee),GO=ct([qO,ox,L0,I0],OO),OOe=(t,e,n)=>{if(e!=null){var r=ix(t);return e==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},qee=ct([ix,$O,Vee,VO],Eee),AN=ct([fd,pd,ar,vi,xd,VO,qee],Pee),IOe=ct([qO,AN],(t,e)=>{var n;return(n=t.coordinate)!==null&&n!==void 0?n:e}),Gee=ct([xd,GO],Nee),zOe=ct([qee,GO,bd,L0,Gee,jee,$O],Dee),UOe=ct([qO,GO],(t,e)=>({isActive:t.active&&e!=null,activeIndex:e})),BOe=(t,e,n,r,a,s,o)=>{if(!(!t||!n||!r||!a)&&FOe(t,o)){var l=cje(t,e),c=Hee(l,s,a,n,r),u=DOe(e,a,c,t);return{activeIndex:String(c),activeCoordinate:u}}},HOe=(t,e,n,r,a,s,o)=>{if(!(!t||!r||!a||!s||!n)){var l=k3e(t,n);if(l){var c=uje(l,e),u=Hee(c,o,s,r,a),d=ROe(e,s,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},$Oe=(t,e,n,r,a,s,o,l)=>{if(!(!t||!e||!r||!a||!s))return e==="horizontal"||e==="vertical"?BOe(t,e,r,a,s,o,l):HOe(t,e,n,r,a,s,o)},VOe=ct(t=>t.zIndex.zIndexMap,(t,e)=>e,(t,e,n)=>n,(t,e,n)=>{if(e!=null){var r=t[e];if(r!=null)return n?r.panoramaElement:r.element}}),qOe=ct(t=>t.zIndex.zIndexMap,t=>{var e=Object.keys(t).map(r=>parseInt(r,10)).concat(Object.values(Da)),n=Array.from(new Set(e));return n.sort((r,a)=>r-a)},{memoizeOptions:{resultEqualityCheck:kFe}});function SG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function _G(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?SG(Object(n),!0).forEach(function(r){GOe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):SG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function GOe(t,e,n){return(e=WOe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function WOe(t){var e=KOe(t,"string");return typeof e=="symbol"?e:e+""}function KOe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var XOe={},YOe={zIndexMap:Object.values(Da).reduce((t,e)=>_G(_G({},t),{},{[e]:{element:void 0,panoramaElement:void 0,consumers:0}}),XOe)},QOe=new Set(Object.values(Da));function ZOe(t){return QOe.has(t)}var Wee=lo({name:"zIndex",initialState:YOe,reducers:{registerZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]?t.zIndexMap[n].consumers+=1:t.zIndexMap[n]={consumers:1,element:void 0,panoramaElement:void 0}},prepare:la()},unregisterZIndexPortal:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(t.zIndexMap[n].consumers-=1,t.zIndexMap[n].consumers<=0&&!ZOe(n)&&delete t.zIndexMap[n])},prepare:la()},registerZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n,element:r,isPanorama:a}=e.payload;t.zIndexMap[n]?a?t.zIndexMap[n].panoramaElement=r:t.zIndexMap[n].element=r:t.zIndexMap[n]={consumers:0,element:a?void 0:r,panoramaElement:a?r:void 0}},prepare:la()},unregisterZIndexPortalElement:{reducer:(t,e)=>{var{zIndex:n}=e.payload;t.zIndexMap[n]&&(e.payload.isPanorama?t.zIndexMap[n].panoramaElement=void 0:t.zIndexMap[n].element=void 0)},prepare:la()}}}),{registerZIndexPortal:JOe,unregisterZIndexPortal:e4e,registerZIndexPortalElement:t4e,unregisterZIndexPortalElement:n4e}=Wee.actions,r4e=Wee.reducer;function vs(t){var{zIndex:e,children:n}=t,r=Bje(),a=r&&e!==void 0&&e!==0,s=wi(),o=qr();w.useLayoutEffect(()=>a?(o(JOe({zIndex:e})),()=>{o(e4e({zIndex:e}))}):em,[o,e,a]);var l=Kt(c=>VOe(c,e,s));return a?l?Fu.createPortal(n,l):null:n}function aR(){return aR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},aR.apply(null,arguments)}function NG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function y_(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?NG(Object(n),!0).forEach(function(r){a4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):NG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function a4e(t,e,n){return(e=i4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i4e(t){var e=s4e(t,"string");return typeof e=="symbol"?e:e+""}function s4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function o4e(t){var{cursor:e,cursorComp:n,cursorProps:r}=t;return w.isValidElement(e)?w.cloneElement(e,r):w.createElement(n,r)}function l4e(t){var e,{coordinate:n,payload:r,index:a,offset:s,tooltipAxisBandSize:o,layout:l,cursor:c,tooltipEventType:u,chartName:d}=t,h=n,f=r,p=a;if(!c||!h||d!=="ScatterChart"&&u!=="axis")return null;var x,v,g;if(d==="ScatterChart")x=h,v=U2e,g=Da.cursorLine;else if(d==="BarChart")x=B2e(l,h,s,o),v=$Z,g=Da.cursorRectangle;else if(l==="radial"&&CQ(h)){var{cx:y,cy:_,radius:N,startAngle:k,endAngle:A}=qZ(h);x={cx:y,cy:_,startAngle:k,endAngle:A,innerRadius:N,outerRadius:N},v=WZ,g=Da.cursorLine}else x={points:P3e(l,h,s)},v=nb,g=Da.cursorLine;var M=typeof c=="object"&&"className"in c?c.className:void 0,C=y_(y_(y_(y_({stroke:"#ccc",pointerEvents:"none"},s),x),Uf(c)),{},{payload:f,payloadIndex:p,className:ir("recharts-tooltip-cursor",M)});return w.createElement(vs,{zIndex:(e=t.zIndex)!==null&&e!==void 0?e:g},w.createElement(o4e,{cursor:c,cursorComp:v,cursorProps:C}))}function c4e(t){var e=MOe(),n=kZ(),r=nm(),a=$ee();return e==null||n==null||r==null||a==null?null:w.createElement(l4e,aR({},t,{offset:n,layout:r,tooltipAxisBandSize:e,chartName:a}))}var Kee=w.createContext(null),u4e=()=>w.useContext(Kee),Nj={exports:{}},CG;function d4e(){return CG||(CG=1,(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function a(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function s(c,u,d,h,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var p=new a(d,h||c,f),x=n?n+u:u;return c._events[x]?c._events[x].fn?c._events[x]=[c._events[x],p]:c._events[x].push(p):(c._events[x]=p,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,h;if(this._eventsCount===0)return u;for(h in d=this._events)e.call(d,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,p=h.length,x=new Array(p);f<p;f++)x[f]=h[f].fn;return x},l.prototype.listenerCount=function(u){var d=n?n+u:u,h=this._events[d];return h?h.fn?1:h.length:0},l.prototype.emit=function(u,d,h,f,p,x){var v=n?n+u:u;if(!this._events[v])return!1;var g=this._events[v],y=arguments.length,_,N;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,d),!0;case 3:return g.fn.call(g.context,d,h),!0;case 4:return g.fn.call(g.context,d,h,f),!0;case 5:return g.fn.call(g.context,d,h,f,p),!0;case 6:return g.fn.call(g.context,d,h,f,p,x),!0}for(N=1,_=new Array(y-1);N<y;N++)_[N-1]=arguments[N];g.fn.apply(g.context,_)}else{var k=g.length,A;for(N=0;N<k;N++)switch(g[N].once&&this.removeListener(u,g[N].fn,void 0,!0),y){case 1:g[N].fn.call(g[N].context);break;case 2:g[N].fn.call(g[N].context,d);break;case 3:g[N].fn.call(g[N].context,d,h);break;case 4:g[N].fn.call(g[N].context,d,h,f);break;default:if(!_)for(A=1,_=new Array(y-1);A<y;A++)_[A-1]=arguments[A];g[N].fn.apply(g[N].context,_)}}return!0},l.prototype.on=function(u,d,h){return s(this,u,d,h,!1)},l.prototype.once=function(u,d,h){return s(this,u,d,h,!0)},l.prototype.removeListener=function(u,d,h,f){var p=n?n+u:u;if(!this._events[p])return this;if(!d)return o(this,p),this;var x=this._events[p];if(x.fn)x.fn===d&&(!f||x.once)&&(!h||x.context===h)&&o(this,p);else{for(var v=0,g=[],y=x.length;v<y;v++)(x[v].fn!==d||f&&!x[v].once||h&&x[v].context!==h)&&g.push(x[v]);g.length?this._events[p]=g.length===1?g[0]:g:o(this,p)}return this},l.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&o(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,t.exports=l})(Nj)),Nj.exports}var h4e=d4e();const m4e=nc(h4e);var $v=new m4e,iR="recharts.syncEvent.tooltip",kG="recharts.syncEvent.brush",Qk=(t,e)=>{if(e&&Array.isArray(t)){var n=Number.parseInt(e,10);if(!Jl(n))return t[n]}},f4e={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},Xee=lo({name:"options",initialState:f4e,reducers:{createEventEmitter:t=>{t.eventEmitter==null&&(t.eventEmitter=Symbol("rechartsEventEmitter"))}}}),p4e=Xee.reducer,{createEventEmitter:g4e}=Xee.actions;function b4e(t){return t.tooltip.syncInteraction}var x4e={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},Yee=lo({name:"chartData",initialState:x4e,reducers:{setChartData(t,e){if(t.chartData=e.payload,e.payload==null){t.dataStartIndex=0,t.dataEndIndex=0;return}e.payload.length>0&&t.dataEndIndex!==e.payload.length-1&&(t.dataEndIndex=e.payload.length-1)},setComputedData(t,e){t.computedData=e.payload},setDataStartEndIndexes(t,e){var{startIndex:n,endIndex:r}=e.payload;n!=null&&(t.dataStartIndex=n),r!=null&&(t.dataEndIndex=r)}}}),{setChartData:AG,setDataStartEndIndexes:y4e,setComputedData:$tt}=Yee.actions,v4e=Yee.reducer,w4e=["x","y"];function TG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Ng(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?TG(Object(n),!0).forEach(function(r){S4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):TG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function S4e(t,e,n){return(e=_4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function _4e(t){var e=N4e(t,"string");return typeof e=="symbol"?e:e+""}function N4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function C4e(t,e){if(t==null)return{};var n,r,a=k4e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function k4e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function A4e(){var t=Kt(dO),e=Kt(hO),n=qr(),r=Kt($J),a=Kt(xd),s=nm(),o=N0(),l=Kt(c=>c.rootProps.className);w.useEffect(()=>{if(t==null)return em;var c=(u,d,h)=>{if(e!==h&&t===u){if(r==="index"){var f;if(o&&d!==null&&d!==void 0&&(f=d.payload)!==null&&f!==void 0&&f.coordinate&&d.payload.sourceViewBox){var p=d.payload.coordinate,{x,y:v}=p,g=C4e(p,w4e),{x:y,y:_,width:N,height:k}=d.payload.sourceViewBox,A=Ng(Ng({},g),{},{x:o.x+(N?(x-y)/N:0)*o.width,y:o.y+(k?(v-_)/k:0)*o.height});n(Ng(Ng({},d),{},{payload:Ng(Ng({},d.payload),{},{coordinate:A})}))}else n(d);return}if(a!=null){var M;if(typeof r=="function"){var C={activeTooltipIndex:d.payload.index==null?void 0:Number(d.payload.index),isTooltipActive:d.payload.active,activeIndex:d.payload.index==null?void 0:Number(d.payload.index),activeLabel:d.payload.label,activeDataKey:d.payload.dataKey,activeCoordinate:d.payload.coordinate},j=r(a,C);M=a[j]}else r==="value"&&(M=a.find(G=>String(G.value)===d.payload.label));var{coordinate:P}=d.payload;if(M==null||d.payload.active===!1||P==null||o==null){n(nR({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}var{x:E,y:U}=P,L=Math.min(E,o.x+o.width),B=Math.min(U,o.y+o.height),D={x:s==="horizontal"?M.coordinate:L,y:s==="horizontal"?B:M.coordinate},$=nR({active:d.payload.active,coordinate:D,dataKey:d.payload.dataKey,index:String(M.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n($)}}};return $v.on(iR,c),()=>{$v.off(iR,c)}},[l,n,e,t,r,a,s,o])}function T4e(){var t=Kt(dO),e=Kt(hO),n=qr();w.useEffect(()=>{if(t==null)return em;var r=(a,s,o)=>{e!==o&&t===a&&n(y4e(s))};return $v.on(kG,r),()=>{$v.off(kG,r)}},[n,e,t])}function M4e(){var t=qr();w.useEffect(()=>{t(g4e())},[t]),A4e(),T4e()}function P4e(t,e,n,r,a,s){var o=Kt(p=>OOe(p,t,e)),l=Kt(hO),c=Kt(dO),u=Kt($J),d=Kt(b4e),h=d?.active,f=N0();w.useEffect(()=>{if(!h&&c!=null&&l!=null){var p=nR({active:s,coordinate:n,dataKey:o,index:a,label:typeof r=="number"?String(r):r,sourceViewBox:f,graphicalItemId:void 0});$v.emit(iR,c,p,l)}},[h,n,o,a,r,l,c,u,s,f])}function MG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function PG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?MG(Object(n),!0).forEach(function(r){E4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):MG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function E4e(t,e,n){return(e=j4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function j4e(t){var e=D4e(t,"string");return typeof e=="symbol"?e:e+""}function D4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function R4e(t){return t.dataKey}function F4e(t,e){return w.isValidElement(t)?w.cloneElement(t,e):typeof t=="function"?w.createElement(t,e):w.createElement(y2e,e)}var EG=[],L4e={allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",axisId:0,contentStyle:{},cursor:!0,filterNull:!0,includeHidden:!1,isAnimationActive:"auto",itemSorter:"name",itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,wrapperStyle:{}};function a1(t){var e,n,r=ba(t,L4e),{active:a,allowEscapeViewBox:s,animationDuration:o,animationEasing:l,content:c,filterNull:u,isAnimationActive:d,offset:h,payloadUniqBy:f,position:p,reverseDirection:x,useTranslate3d:v,wrapperStyle:g,cursor:y,shared:_,trigger:N,defaultIndex:k,portal:A,axisId:M}=r,C=qr(),j=typeof k=="number"?String(k):k;w.useEffect(()=>{C(jLe({shared:_,trigger:N,axisId:M,active:a,defaultIndex:j}))},[C,_,N,M,a,j]);var P=N0(),E=IZ(),U=kLe(_),{activeIndex:L,isActive:B}=(e=Kt(ee=>UOe(ee,U,N,j)))!==null&&e!==void 0?e:{},D=Kt(ee=>zOe(ee,U,N,j)),$=Kt(ee=>Gee(ee,U,N,j)),G=Kt(ee=>IOe(ee,U,N,j)),z=D,W=u4e(),X=(n=a??B)!==null&&n!==void 0?n:!1,[ae,H]=UQ([z,X]),K=U==="axis"?$:void 0;P4e(U,N,G,K,L,X);var te=A??W;if(te==null||P==null||U==null)return null;var Z=z??EG;X||(Z=EG),u&&Z.length&&(Z=RQ(Z.filter(ee=>ee.value!=null&&(ee.hide!==!0||r.includeHidden)),f,R4e));var ve=Z.length>0,ce=w.createElement(k2e,{allowEscapeViewBox:s,animationDuration:o,animationEasing:l,isAnimationActive:d,active:X,coordinate:G,hasPayload:ve,offset:h,position:p,reverseDirection:x,useTranslate3d:v,viewBox:P,wrapperStyle:g,lastBoundingBox:ae,innerRef:H,hasPortalFromProps:!!A},F4e(c,PG(PG({},r),{},{payload:Z,label:K,active:X,activeIndex:L,coordinate:G,accessibilityLayer:E})));return w.createElement(w.Fragment,null,Fu.createPortal(ce,te),X&&w.createElement(c4e,{cursor:y,tooltipEventType:U,coordinate:G,payload:Z,index:L}))}var U0=t=>null;U0.displayName="Cell";function O4e(t,e,n){return(e=I4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function I4e(t){var e=z4e(t,"string");return typeof e=="symbol"?e:e+""}function z4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}class U4e{constructor(e){O4e(this,"cache",new Map),this.maxSize=e}get(e){var n=this.cache.get(e);return n!==void 0&&(this.cache.delete(e),this.cache.set(e,n)),n}set(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(e,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function jG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function B4e(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?jG(Object(n),!0).forEach(function(r){H4e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):jG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function H4e(t,e,n){return(e=$4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $4e(t){var e=V4e(t,"string");return typeof e=="symbol"?e:e+""}function V4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var q4e={cacheSize:2e3,enableCache:!0},Qee=B4e({},q4e),DG=new U4e(Qee.cacheSize),G4e={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},RG="recharts_measurement_span";function W4e(t,e){var n=e.fontSize||"",r=e.fontFamily||"",a=e.fontWeight||"",s=e.fontStyle||"",o=e.letterSpacing||"",l=e.textTransform||"";return"".concat(t,"|").concat(n,"|").concat(r,"|").concat(a,"|").concat(s,"|").concat(o,"|").concat(l)}var FG=(t,e)=>{try{var n=document.getElementById(RG);n||(n=document.createElement("span"),n.setAttribute("id",RG),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,G4e,e),n.textContent="".concat(t);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},Yy=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||A0.isSsr)return{width:0,height:0};if(!Qee.enableCache)return FG(e,n);var r=W4e(e,n),a=DG.get(r);if(a)return a;var s=FG(e,n);return DG.set(r,s),s},Zee;function K4e(t,e,n){return(e=X4e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function X4e(t){var e=Y4e(t,"string");return typeof e=="symbol"?e:e+""}function Y4e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var LG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,OG=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,Q4e=/^px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q$/,Z4e=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,J4e={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},eIe=["cm","mm","pt","pc","in","Q","px"];function tIe(t){return eIe.includes(t)}var Hg="NaN";function nIe(t,e){return t*J4e[e]}class Ki{static parse(e){var n,[,r,a]=(n=Z4e.exec(e))!==null&&n!==void 0?n:[];return r==null?Ki.NaN:new Ki(parseFloat(r),a??"")}constructor(e,n){this.num=e,this.unit=n,this.num=e,this.unit=n,Jl(e)&&(this.unit=""),n!==""&&!Q4e.test(n)&&(this.num=NaN,this.unit=""),tIe(n)&&(this.num=nIe(e,n),this.unit="px")}add(e){return this.unit!==e.unit?new Ki(NaN,""):new Ki(this.num+e.num,this.unit)}subtract(e){return this.unit!==e.unit?new Ki(NaN,""):new Ki(this.num-e.num,this.unit)}multiply(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ki(NaN,""):new Ki(this.num*e.num,this.unit||e.unit)}divide(e){return this.unit!==""&&e.unit!==""&&this.unit!==e.unit?new Ki(NaN,""):new Ki(this.num/e.num,this.unit||e.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return Jl(this.num)}}Zee=Ki;K4e(Ki,"NaN",new Zee(NaN,""));function Jee(t){if(t==null||t.includes(Hg))return Hg;for(var e=t;e.includes("*")||e.includes("/");){var n,[,r,a,s]=(n=LG.exec(e))!==null&&n!==void 0?n:[],o=Ki.parse(r??""),l=Ki.parse(s??""),c=a==="*"?o.multiply(l):o.divide(l);if(c.isNaN())return Hg;e=e.replace(LG,c.toString())}for(;e.includes("+")||/.-\d+(?:\.\d+)?/.test(e);){var u,[,d,h,f]=(u=OG.exec(e))!==null&&u!==void 0?u:[],p=Ki.parse(d??""),x=Ki.parse(f??""),v=h==="+"?p.add(x):p.subtract(x);if(v.isNaN())return Hg;e=e.replace(OG,v.toString())}return e}var IG=/\(([^()]*)\)/;function rIe(t){for(var e=t,n;(n=IG.exec(e))!=null;){var[,r]=n;e=e.replace(IG,Jee(r))}return e}function aIe(t){var e=t.replace(/\s+/g,"");return e=rIe(e),e=Jee(e),e}function iIe(t){try{return aIe(t)}catch{return Hg}}function Cj(t){var e=iIe(t.slice(5,-1));return e===Hg?"":e}var sIe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],oIe=["dx","dy","angle","className","breakAll"];function sR(){return sR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},sR.apply(null,arguments)}function zG(t,e){if(t==null)return{};var n,r,a=lIe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function lIe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var ete=/[ \f\n\r\t\v\u2028\u2029]+/,tte=t=>{var{children:e,breakAll:n,style:r}=t;try{var a=[];ha(e)||(n?a=e.toString().split(""):a=e.toString().split(ete));var s=a.map(l=>({word:l,width:Yy(l,r).width})),o=n?0:Yy(" ",r).width;return{wordsWithComputedWidth:s,spaceWidth:o}}catch{return null}};function cIe(t){return t==="start"||t==="middle"||t==="end"||t==="inherit"}var nte=(t,e,n,r)=>t.reduce((a,s)=>{var{word:o,width:l}=s,c=a[a.length-1];if(c&&l!=null&&(e==null||r||c.width+l+n<Number(e)))c.words.push(o),c.width+=l+n;else{var u={words:[o],width:l};a.push(u)}return a},[]),rte=t=>t.reduce((e,n)=>e.width>n.width?e:n),uIe="…",UG=(t,e,n,r,a,s,o,l)=>{var c=t.slice(0,e),u=tte({breakAll:n,style:r,children:c+uIe});if(!u)return[!1,[]];var d=nte(u.wordsWithComputedWidth,s,o,l),h=d.length>a||rte(d).width>Number(s);return[h,d]},dIe=(t,e,n,r,a)=>{var{maxLines:s,children:o,style:l,breakAll:c}=t,u=qt(s),d=String(o),h=nte(e,r,n,a);if(!u||a)return h;var f=h.length>s||rte(h).width>Number(r);if(!f)return h;for(var p=0,x=d.length-1,v=0,g;p<=x&&v<=d.length-1;){var y=Math.floor((p+x)/2),_=y-1,[N,k]=UG(d,_,c,l,s,r,n,a),[A]=UG(d,y,c,l,s,r,n,a);if(!N&&!A&&(p=y+1),N&&A&&(x=y-1),!N&&A){g=k;break}v++}return g||h},BG=t=>{var e=ha(t)?[]:t.toString().split(ete);return[{words:e,width:void 0}]},hIe=t=>{var{width:e,scaleToFit:n,children:r,style:a,breakAll:s,maxLines:o}=t;if((e||n)&&!A0.isSsr){var l,c,u=tte({breakAll:s,children:r,style:a});if(u){var{wordsWithComputedWidth:d,spaceWidth:h}=u;l=d,c=h}else return BG(r);return dIe({breakAll:s,children:r,maxLines:o,style:a},l,c,e,!!n)}return BG(r)},ate="#808080",mIe={angle:0,breakAll:!1,capHeight:"0.71em",fill:ate,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},Zk=w.forwardRef((t,e)=>{var n=ba(t,mIe),{x:r,y:a,lineHeight:s,capHeight:o,fill:l,scaleToFit:c,textAnchor:u,verticalAnchor:d}=n,h=zG(n,sIe),f=w.useMemo(()=>hIe({breakAll:h.breakAll,children:h.children,maxLines:h.maxLines,scaleToFit:c,style:h.style,width:h.width}),[h.breakAll,h.children,h.maxLines,c,h.style,h.width]),{dx:p,dy:x,angle:v,className:g,breakAll:y}=h,_=zG(h,oIe);if(!_l(r)||!_l(a)||f.length===0)return null;var N=Number(r)+(qt(p)?p:0),k=Number(a)+(qt(x)?x:0);if(!Nn(N)||!Nn(k))return null;var A;switch(d){case"start":A=Cj("calc(".concat(o,")"));break;case"middle":A=Cj("calc(".concat((f.length-1)/2," * -").concat(s," + (").concat(o," / 2))"));break;default:A=Cj("calc(".concat(f.length-1," * -").concat(s,")"));break}var M=[],C=f[0];if(c&&C!=null){var j=C.width,{width:P}=h;M.push("scale(".concat(qt(P)&&qt(j)?P/j:1,")"))}return v&&M.push("rotate(".concat(v,", ").concat(N,", ").concat(k,")")),M.length&&(_.transform=M.join(" ")),w.createElement("text",sR({},ts(_),{ref:e,x:N,y:k,className:ir("recharts-text",g),textAnchor:u,fill:l.includes("url")?ate:l}),f.map((E,U)=>{var L=E.words.join(y?"":" ");return w.createElement("tspan",{x:N,dy:U===0?A:s,key:"".concat(L,"-").concat(U)},L)}))});Zk.displayName="Text";function HG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function bc(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?HG(Object(n),!0).forEach(function(r){fIe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):HG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function fIe(t,e,n){return(e=pIe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function pIe(t){var e=gIe(t,"string");return typeof e=="symbol"?e:e+""}function gIe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var bIe=t=>{var{viewBox:e,position:n,offset:r=0,parentViewBox:a}=t,{x:s,y:o,height:l,upperWidth:c,lowerWidth:u}=EL(e),d=s,h=s+(c-u)/2,f=(d+h)/2,p=(c+u)/2,x=d+c/2,v=l>=0?1:-1,g=v*r,y=v>0?"end":"start",_=v>0?"start":"end",N=c>=0?1:-1,k=N*r,A=N>0?"end":"start",M=N>0?"start":"end",C=a;if(n==="top"){var j={x:d+c/2,y:o-g,horizontalAnchor:"middle",verticalAnchor:y};return C&&(j.height=Math.max(o-C.y,0),j.width=c),j}if(n==="bottom"){var P={x:h+u/2,y:o+l+g,horizontalAnchor:"middle",verticalAnchor:_};return C&&(P.height=Math.max(C.y+C.height-(o+l),0),P.width=u),P}if(n==="left"){var E={x:f-k,y:o+l/2,horizontalAnchor:A,verticalAnchor:"middle"};return C&&(E.width=Math.max(E.x-C.x,0),E.height=l),E}if(n==="right"){var U={x:f+p+k,y:o+l/2,horizontalAnchor:M,verticalAnchor:"middle"};return C&&(U.width=Math.max(C.x+C.width-U.x,0),U.height=l),U}var L=C?{width:p,height:l}:{};return n==="insideLeft"?bc({x:f+k,y:o+l/2,horizontalAnchor:M,verticalAnchor:"middle"},L):n==="insideRight"?bc({x:f+p-k,y:o+l/2,horizontalAnchor:A,verticalAnchor:"middle"},L):n==="insideTop"?bc({x:d+c/2,y:o+g,horizontalAnchor:"middle",verticalAnchor:_},L):n==="insideBottom"?bc({x:h+u/2,y:o+l-g,horizontalAnchor:"middle",verticalAnchor:y},L):n==="insideTopLeft"?bc({x:d+k,y:o+g,horizontalAnchor:M,verticalAnchor:_},L):n==="insideTopRight"?bc({x:d+c-k,y:o+g,horizontalAnchor:A,verticalAnchor:_},L):n==="insideBottomLeft"?bc({x:h+k,y:o+l-g,horizontalAnchor:M,verticalAnchor:y},L):n==="insideBottomRight"?bc({x:h+u-k,y:o+l-g,horizontalAnchor:A,verticalAnchor:y},L):n&&typeof n=="object"&&(qt(n.x)||$f(n.x))&&(qt(n.y)||$f(n.y))?bc({x:s+bs(n.x,p),y:o+bs(n.y,l),horizontalAnchor:"end",verticalAnchor:"end"},L):bc({x,y:o+l/2,horizontalAnchor:"middle",verticalAnchor:"middle"},L)},xIe=["labelRef"],yIe=["content"];function $G(t,e){if(t==null)return{};var n,r,a=vIe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function vIe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function VG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function jy(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?VG(Object(n),!0).forEach(function(r){wIe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):VG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function wIe(t,e,n){return(e=SIe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function SIe(t){var e=_Ie(t,"string");return typeof e=="symbol"?e:e+""}function _Ie(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ru(){return Ru=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ru.apply(null,arguments)}var ite=w.createContext(null),ste=t=>{var{x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o,children:l}=t,c=w.useMemo(()=>({x:e,y:n,upperWidth:r,lowerWidth:a,width:s,height:o}),[e,n,r,a,s,o]);return w.createElement(ite.Provider,{value:c},l)},ote=()=>{var t=w.useContext(ite),e=N0();return t||(e?EL(e):void 0)},NIe=w.createContext(null),CIe=()=>{var t=w.useContext(NIe),e=Kt(KJ);return t||e},kIe=t=>{var{value:e,formatter:n}=t,r=ha(t.children)?e:t.children;return typeof n=="function"?n(r):r},WO=t=>t!=null&&typeof t=="function",AIe=(t,e)=>{var n=Ri(e-t),r=Math.min(Math.abs(e-t),360);return n*r},TIe=(t,e,n,r,a)=>{var{offset:s,className:o}=t,{cx:l,cy:c,innerRadius:u,outerRadius:d,startAngle:h,endAngle:f,clockWise:p}=a,x=(u+d)/2,v=AIe(h,f),g=v>=0?1:-1,y,_;switch(e){case"insideStart":y=h+g*s,_=p;break;case"insideEnd":y=f-g*s,_=!p;break;case"end":y=f+g*s,_=p;break;default:throw new Error("Unsupported position ".concat(e))}_=v<=0?_:!_;var N=ei(l,c,x,y),k=ei(l,c,x,y+(_?1:-1)*359),A="M".concat(N.x,",").concat(N.y,`
  8101. A`).concat(x,",").concat(x,",0,1,").concat(_?0:1,`,
  8102. `).concat(k.x,",").concat(k.y),M=ha(t.id)?Pv("recharts-radial-line-"):t.id;return w.createElement("text",Ru({},r,{dominantBaseline:"central",className:ir("recharts-radial-bar-label",o)}),w.createElement("defs",null,w.createElement("path",{id:M,d:A})),w.createElement("textPath",{xlinkHref:"#".concat(M)},n))},MIe=(t,e,n)=>{var{cx:r,cy:a,innerRadius:s,outerRadius:o,startAngle:l,endAngle:c}=t,u=(l+c)/2;if(n==="outside"){var{x:d,y:h}=ei(r,a,o+e,u);return{x:d,y:h,textAnchor:d>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"end"};var f=(s+o)/2,{x:p,y:x}=ei(r,a,f,u);return{x:p,y:x,textAnchor:"middle",verticalAnchor:"middle"}},i1=t=>t!=null&&"cx"in t&&qt(t.cx),PIe={angle:0,offset:5,zIndex:Da.label,position:"middle",textBreakAll:!1};function EIe(t){if(!i1(t))return t;var{cx:e,cy:n,outerRadius:r}=t,a=r*2;return{x:e-r,y:n-r,width:a,upperWidth:a,lowerWidth:a,height:a}}function lh(t){var e=ba(t,PIe),{viewBox:n,parentViewBox:r,position:a,value:s,children:o,content:l,className:c="",textBreakAll:u,labelRef:d}=e,h=CIe(),f=ote(),p=a==="center"?f:h??f,x,v,g;n==null?x=p:i1(n)?x=n:x=EL(n);var y=EIe(x);if(!x||ha(s)&&ha(o)&&!w.isValidElement(l)&&typeof l!="function")return null;var _=jy(jy({},e),{},{viewBox:x});if(w.isValidElement(l)){var{labelRef:N}=_,k=$G(_,xIe);return w.cloneElement(l,k)}if(typeof l=="function"){var{content:A}=_,M=$G(_,yIe);if(v=w.createElement(l,M),w.isValidElement(v))return v}else v=kIe(e);var C=ts(e);if(i1(x)){if(a==="insideStart"||a==="insideEnd"||a==="end")return TIe(e,a,v,C,x);g=MIe(x,e.offset,e.position)}else{if(!y)return null;var j=bIe({viewBox:y,position:a,offset:e.offset,parentViewBox:i1(r)?void 0:r});g=jy(jy({x:j.x,y:j.y,textAnchor:j.horizontalAnchor,verticalAnchor:j.verticalAnchor},j.width!==void 0?{width:j.width}:{}),j.height!==void 0?{height:j.height}:{})}return w.createElement(vs,{zIndex:e.zIndex},w.createElement(Zk,Ru({ref:d,className:ir("recharts-label",c)},C,g,{textAnchor:cIe(C.textAnchor)?C.textAnchor:g.textAnchor,breakAll:u}),v))}lh.displayName="Label";var jIe=(t,e,n)=>{if(!t)return null;var r={viewBox:e,labelRef:n};return t===!0?w.createElement(lh,Ru({key:"label-implicit"},r)):_l(t)?w.createElement(lh,Ru({key:"label-implicit",value:t},r)):w.isValidElement(t)?t.type===lh?w.cloneElement(t,jy({key:"label-implicit"},r)):w.createElement(lh,Ru({key:"label-implicit",content:t},r)):WO(t)?w.createElement(lh,Ru({key:"label-implicit",content:t},r)):t&&typeof t=="object"?w.createElement(lh,Ru({},t,{key:"label-implicit"},r)):null};function lte(t){var{label:e,labelRef:n}=t,r=ote();return jIe(e,r,n)||null}var kj={},Aj={},qG;function DIe(){return qG||(qG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return n[n.length-1]}t.last=e})(Aj)),Aj}var Tj={},GG;function RIe(){return GG||(GG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){return Array.isArray(n)?n:Array.from(n)}t.toArray=e})(Tj)),Tj}var WG;function FIe(){return WG||(WG=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});const e=DIe(),n=RIe(),r=vL();function a(s){if(r.isArrayLike(s))return e.last(n.toArray(s))}t.last=a})(kj)),kj}var Mj,KG;function LIe(){return KG||(KG=1,Mj=FIe().last),Mj}var OIe=LIe();const IIe=nc(OIe);var zIe=["valueAccessor"],UIe=["dataKey","clockWise","id","textBreakAll","zIndex"];function TN(){return TN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},TN.apply(null,arguments)}function XG(t,e){if(t==null)return{};var n,r,a=BIe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function BIe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var HIe=t=>Array.isArray(t.value)?IIe(t.value):t.value,cte=w.createContext(void 0),KO=cte.Provider,ute=w.createContext(void 0),$Ie=ute.Provider;function VIe(){return w.useContext(cte)}function qIe(){return w.useContext(ute)}function s1(t){var{valueAccessor:e=HIe}=t,n=XG(t,zIe),{dataKey:r,clockWise:a,id:s,textBreakAll:o,zIndex:l}=n,c=XG(n,UIe),u=VIe(),d=qIe(),h=u||d;return!h||!h.length?null:w.createElement(vs,{zIndex:l??Da.label},w.createElement(ga,{className:"recharts-label-list"},h.map((f,p)=>{var x,v=ha(r)?e(f,p):yr(f.payload,r),g=ha(s)?{}:{id:"".concat(s,"-").concat(p)};return w.createElement(lh,TN({key:"label-".concat(p)},ts(f),c,g,{fill:(x=n.fill)!==null&&x!==void 0?x:f.fill,parentViewBox:f.parentViewBox,value:v,textBreakAll:o,viewBox:f.viewBox,index:p,zIndex:0}))})))}s1.displayName="LabelList";function Jk(t){var{label:e}=t;return e?e===!0?w.createElement(s1,{key:"labelList-implicit"}):w.isValidElement(e)||WO(e)?w.createElement(s1,{key:"labelList-implicit",content:e}):typeof e=="object"?w.createElement(s1,TN({key:"labelList-implicit"},e,{type:String(e.type)})):null:null}function oR(){return oR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},oR.apply(null,arguments)}var dte=t=>{var{cx:e,cy:n,r,className:a}=t,s=ir("recharts-dot",a);return qt(e)&&qt(n)&&qt(r)?w.createElement("circle",oR({},Fs(t),yL(t),{className:s,cx:e,cy:n,r})):null},hte=t=>t.graphicalItems.polarItems,GIe=ct([xa,D0],bO),eA=ct([hte,La,GIe],xO),WIe=ct([eA],yO),tA=ct([WIe,zk],vO),KIe=ct([tA,La,eA],SO);ct([tA,La,eA],(t,e,n)=>n.length>0?t.flatMap(r=>n.flatMap(a=>{var s,o=yr(r,(s=e.dataKey)!==null&&s!==void 0?s:a.dataKey);return{value:o,errorDomain:[]}})).filter(Boolean):e?.dataKey!=null?t.map(r=>({value:yr(r,e.dataKey),errorDomain:[]})):t.map(r=>({value:r,errorDomain:[]})));var YG=()=>{},XIe=ct([tA,La,eA,Kk,xa],kO),YIe=ct([La,NO,CO,YG,XIe,YG,ar,xa],AO),mte=ct([La,ar,tA,KIe,j0,xa,YIe],TO),QIe=ct([mte,rx,im],EO),ZIe=ct([La,mte,QIe,xa],DO);ct([im,ZIe],YJ);var JIe={radiusAxis:{},angleAxis:{}},fte=lo({name:"polarAxis",initialState:JIe,reducers:{addRadiusAxis(t,e){t.radiusAxis[e.payload.id]=e.payload},removeRadiusAxis(t,e){delete t.radiusAxis[e.payload.id]},addAngleAxis(t,e){t.angleAxis[e.payload.id]=e.payload},removeAngleAxis(t,e){delete t.angleAxis[e.payload.id]}}}),{addRadiusAxis:Vtt,removeRadiusAxis:qtt,addAngleAxis:Gtt,removeAngleAxis:Wtt}=fte.actions,eze=fte.reducer;function pte(t){return t&&typeof t=="object"&&"className"in t&&typeof t.className=="string"?t.className:""}function QG(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ZG(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?QG(Object(n),!0).forEach(function(r){tze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):QG(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function tze(t,e,n){return(e=nze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function nze(t){var e=rze(t,"string");return typeof e=="symbol"?e:e+""}function rze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var aze=(t,e)=>e,XO=ct([hte,aze],(t,e)=>t.filter(n=>n.type==="pie").find(n=>n.id===e)),ize=[],YO=(t,e,n)=>n?.length===0?ize:n,gte=ct([zk,XO,YO],(t,e,n)=>{var{chartData:r}=t;if(e!=null){var a;if(e?.data!=null&&e.data.length>0?a=e.data:a=r,(!a||!a.length)&&n!=null&&(a=n.map(s=>ZG(ZG({},e.presentationProps),s.props))),a!=null)return a}}),sze=ct([gte,XO,YO],(t,e,n)=>{if(!(t==null||e==null))return t.map((r,a)=>{var s,o=yr(r,e.nameKey,e.name),l;return n!=null&&(s=n[a])!==null&&s!==void 0&&(s=s.props)!==null&&s!==void 0&&s.fill?l=n[a].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=e.fill,{value:tm(o,e.dataKey),color:l,payload:r,type:e.legendType}})}),oze=ct([gte,XO,YO,vi],(t,e,n,r)=>{if(!(e==null||t==null))return l5e({offset:r,pieSettings:e,displayedData:t,cells:n})}),Pj={exports:{}},jr={};var JG;function lze(){if(JG)return jr;JG=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.suspense_list"),d=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),f=Symbol.for("react.view_transition"),p=Symbol.for("react.client.reference");function x(v){if(typeof v=="object"&&v!==null){var g=v.$$typeof;switch(g){case t:switch(v=v.type,v){case n:case a:case r:case c:case u:case f:return v;default:switch(v=v&&v.$$typeof,v){case o:case l:case h:case d:return v;case s:return v;default:return g}}case e:return g}}}return jr.ContextConsumer=s,jr.ContextProvider=o,jr.Element=t,jr.ForwardRef=l,jr.Fragment=n,jr.Lazy=h,jr.Memo=d,jr.Portal=e,jr.Profiler=a,jr.StrictMode=r,jr.Suspense=c,jr.SuspenseList=u,jr.isContextConsumer=function(v){return x(v)===s},jr.isContextProvider=function(v){return x(v)===o},jr.isElement=function(v){return typeof v=="object"&&v!==null&&v.$$typeof===t},jr.isForwardRef=function(v){return x(v)===l},jr.isFragment=function(v){return x(v)===n},jr.isLazy=function(v){return x(v)===h},jr.isMemo=function(v){return x(v)===d},jr.isPortal=function(v){return x(v)===e},jr.isProfiler=function(v){return x(v)===a},jr.isStrictMode=function(v){return x(v)===r},jr.isSuspense=function(v){return x(v)===c},jr.isSuspenseList=function(v){return x(v)===u},jr.isValidElementType=function(v){return typeof v=="string"||typeof v=="function"||v===n||v===a||v===r||v===c||v===u||typeof v=="object"&&v!==null&&(v.$$typeof===h||v.$$typeof===d||v.$$typeof===o||v.$$typeof===s||v.$$typeof===l||v.$$typeof===p||v.getModuleId!==void 0)},jr.typeOf=x,jr}var e7;function cze(){return e7||(e7=1,Pj.exports=lze()),Pj.exports}var uze=cze(),t7=t=>typeof t=="string"?t:t?t.displayName||t.name||"Component":"",n7=null,Ej=null,bte=t=>{if(t===n7&&Array.isArray(Ej))return Ej;var e=[];return w.Children.forEach(t,n=>{ha(n)||(uze.isFragment(n)?e=e.concat(bte(n.props.children)):e.push(n))}),Ej=e,n7=t,e};function QO(t,e){var n=[],r=[];return Array.isArray(e)?r=e.map(a=>t7(a)):r=[t7(e)],bte(t).forEach(a=>{var s=Hf(a,"type.displayName")||Hf(a,"type.name");s&&r.indexOf(s)!==-1&&n.push(a)}),n}var ZO=t=>t&&typeof t=="object"&&"clipDot"in t?!!t.clipDot:!0,jj={},r7;function dze(){return r7||(r7=1,(function(t){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});function e(n){if(typeof n!="object"||n==null)return!1;if(Object.getPrototypeOf(n)===null)return!0;if(Object.prototype.toString.call(n)!=="[object Object]"){const a=n[Symbol.toStringTag];return a==null||!Object.getOwnPropertyDescriptor(n,Symbol.toStringTag)?.writable?!1:n.toString()===`[object ${a}]`}let r=n;for(;Object.getPrototypeOf(r)!==null;)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(n)===r}t.isPlainObject=e})(jj)),jj}var Dj,a7;function hze(){return a7||(a7=1,Dj=dze().isPlainObject),Dj}var mze=hze();const fze=nc(mze);var i7,s7,o7,l7,c7;function u7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function d7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?u7(Object(n),!0).forEach(function(r){pze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):u7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function pze(t,e,n){return(e=gze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gze(t){var e=bze(t,"string");return typeof e=="symbol"?e:e+""}function bze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function MN(){return MN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},MN.apply(null,arguments)}function Sy(t,e){return e||(e=t.slice(0)),Object.freeze(Object.defineProperties(t,{raw:{value:Object.freeze(e)}}))}var h7=(t,e,n,r,a)=>{var s=n-r,o;return o=Ta(i7||(i7=Sy(["M ",",",""])),t,e),o+=Ta(s7||(s7=Sy(["L ",",",""])),t+n,e),o+=Ta(o7||(o7=Sy(["L ",",",""])),t+n-s/2,e+a),o+=Ta(l7||(l7=Sy(["L ",",",""])),t+n-s/2-r,e+a),o+=Ta(c7||(c7=Sy(["L ",","," Z"])),t,e),o},xze={x:0,y:0,upperWidth:0,lowerWidth:0,height:0,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},yze=t=>{var e=ba(t,xze),{x:n,y:r,upperWidth:a,lowerWidth:s,height:o,className:l}=e,{animationEasing:c,animationDuration:u,animationBegin:d,isUpdateAnimationActive:h}=e,f=w.useRef(null),[p,x]=w.useState(-1),v=w.useRef(a),g=w.useRef(s),y=w.useRef(o),_=w.useRef(n),N=w.useRef(r),k=Zb(t,"trapezoid-");if(w.useEffect(()=>{if(f.current&&f.current.getTotalLength)try{var D=f.current.getTotalLength();D&&x(D)}catch{}},[]),n!==+n||r!==+r||a!==+a||s!==+s||o!==+o||a===0&&s===0||o===0)return null;var A=ir("recharts-trapezoid",l);if(!h)return w.createElement("g",null,w.createElement("path",MN({},ts(e),{className:A,d:h7(n,r,a,s,o)})));var M=v.current,C=g.current,j=y.current,P=_.current,E=N.current,U="0px ".concat(p===-1?1:p,"px"),L="".concat(p,"px 0px"),B=zZ(["strokeDasharray"],u,c);return w.createElement(Qb,{animationId:k,key:k,canBegin:p>0,duration:u,easing:c,isActive:h,begin:d},D=>{var $=br(M,a,D),G=br(C,s,D),z=br(j,o,D),W=br(P,n,D),X=br(E,r,D);f.current&&(v.current=$,g.current=G,y.current=z,_.current=W,N.current=X);var ae=D>0?{transition:B,strokeDasharray:L}:{strokeDasharray:U};return w.createElement("path",MN({},ts(e),{className:A,d:h7(W,X,$,G,z),ref:f,style:d7(d7({},ae),e.style)}))})},vze=["option","shapeType","activeClassName"];function wze(t,e){if(t==null)return{};var n,r,a=Sze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function Sze(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function m7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function PN(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?m7(Object(n),!0).forEach(function(r){_ze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):m7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function _ze(t,e,n){return(e=Nze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Nze(t){var e=Cze(t,"string");return typeof e=="symbol"?e:e+""}function Cze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function kze(t,e){return PN(PN({},e),t)}function Aze(t,e){return t==="symbols"}function f7(t){var{shapeType:e,elementProps:n}=t;switch(e){case"rectangle":return w.createElement($Z,n);case"trapezoid":return w.createElement(yze,n);case"sector":return w.createElement(WZ,n);case"symbols":if(Aze(e))return w.createElement(xL,n);break;case"curve":return w.createElement(nb,n);default:return null}}function Tze(t){return w.isValidElement(t)?t.props:t}function JO(t){var{option:e,shapeType:n,activeClassName:r="recharts-active-shape"}=t,a=wze(t,vze),s;if(w.isValidElement(e))s=w.cloneElement(e,PN(PN({},a),Tze(e)));else if(typeof e=="function")s=e(a,a.index);else if(fze(e)&&typeof e!="boolean"){var o=kze(e,a);s=w.createElement(f7,{shapeType:n,elementProps:o})}else{var l=a;s=w.createElement(f7,{shapeType:n,elementProps:l})}return a.isActive?w.createElement(ga,{className:r},s):s}var e4=(t,e,n)=>{var r=qr();return(a,s)=>o=>{t?.(a,s,o),r(kee({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}},t4=t=>{var e=qr();return(n,r)=>a=>{t?.(n,r,a),e(DLe())}},n4=(t,e,n)=>{var r=qr();return(a,s)=>o=>{t?.(a,s,o),r(RLe({activeIndex:String(s),activeDataKey:e,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}};function nA(t){var{tooltipEntrySettings:e}=t,n=qr(),r=wi(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(MLe(e)):a.current!==e&&n(PLe({prev:a.current,next:e})),a.current=e)},[e,n,r]),w.useLayoutEffect(()=>()=>{a.current&&(n(ELe(a.current)),a.current=null)},[n]),null}function r4(t){var{legendPayload:e}=t,n=qr(),r=wi(),a=w.useRef(null);return w.useLayoutEffect(()=>{r||(a.current===null?n(FZ(e)):a.current!==e&&n(LZ({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(OZ(a.current)),a.current=null)},[n]),null}function Mze(t){var{legendPayload:e}=t,n=qr(),r=Kt(ar),a=w.useRef(null);return w.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(a.current===null?n(FZ(e)):a.current!==e&&n(LZ({prev:a.current,next:e})),a.current=e)},[n,r,e]),w.useLayoutEffect(()=>()=>{a.current&&(n(OZ(a.current)),a.current=null)},[n]),null}var Rj,Pze=()=>{var[t]=w.useState(()=>Pv("uid-"));return t},Eze=(Rj=nle.useId)!==null&&Rj!==void 0?Rj:Pze;function jze(t,e){var n=Eze();return e||(t?"".concat(t,"-").concat(n):n)}var Dze=w.createContext(void 0),rA=t=>{var{id:e,type:n,children:r}=t,a=jze("recharts-".concat(n),e);return w.createElement(Dze.Provider,{value:a},r(a))},Rze={cartesianItems:[],polarItems:[]},xte=lo({name:"graphicalItems",initialState:Rze,reducers:{addCartesianGraphicalItem:{reducer(t,e){t.cartesianItems.push(e.payload)},prepare:la()},replaceCartesianGraphicalItem:{reducer(t,e){var{prev:n,next:r}=e.payload,a=Kl(t).cartesianItems.indexOf(n);a>-1&&(t.cartesianItems[a]=r)},prepare:la()},removeCartesianGraphicalItem:{reducer(t,e){var n=Kl(t).cartesianItems.indexOf(e.payload);n>-1&&t.cartesianItems.splice(n,1)},prepare:la()},addPolarGraphicalItem:{reducer(t,e){t.polarItems.push(e.payload)},prepare:la()},removePolarGraphicalItem:{reducer(t,e){var n=Kl(t).polarItems.indexOf(e.payload);n>-1&&t.polarItems.splice(n,1)},prepare:la()}}}),{addCartesianGraphicalItem:Fze,replaceCartesianGraphicalItem:Lze,removeCartesianGraphicalItem:Oze,addPolarGraphicalItem:Ize,removePolarGraphicalItem:zze}=xte.actions,Uze=xte.reducer,Bze=t=>{var e=qr(),n=w.useRef(null);return w.useLayoutEffect(()=>{n.current===null?e(Fze(t)):n.current!==t&&e(Lze({prev:n.current,next:t})),n.current=t},[e,t]),w.useLayoutEffect(()=>()=>{n.current&&(e(Oze(n.current)),n.current=null)},[e]),null},a4=w.memo(Bze);function Hze(t){var e=qr();return w.useLayoutEffect(()=>(e(Ize(t)),()=>{e(zze(t))}),[e,t]),null}var $ze=["key"],Vze=["onMouseEnter","onClick","onMouseLeave"],qze=["id"],Gze=["id"];function p7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Ma(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?p7(Object(n),!0).forEach(function(r){Wze(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):p7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Wze(t,e,n){return(e=Kze(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Kze(t){var e=Xze(t,"string");return typeof e=="symbol"?e:e+""}function Xze(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Qh(){return Qh=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Qh.apply(null,arguments)}function aA(t,e){if(t==null)return{};var n,r,a=Yze(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function Yze(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function Qze(t){var e=w.useMemo(()=>QO(t.children,U0),[t.children]),n=Kt(r=>sze(r,t.id,e));return n==null?null:w.createElement(Mze,{legendPayload:n})}var Zze=w.memo(t=>{var{dataKey:e,nameKey:n,sectors:r,stroke:a,strokeWidth:s,fill:o,name:l,hide:c,tooltipType:u,id:d}=t,h={dataDefinedOnItem:r.map(f=>f.tooltipPayload),getPosition:f=>{var p;return(p=r[Number(f)])===null||p===void 0?void 0:p.tooltipPosition},settings:{stroke:a,strokeWidth:s,fill:o,dataKey:e,nameKey:n,name:tm(l,e),hide:c,type:u,color:o,unit:"",graphicalItemId:d}};return w.createElement(nA,{tooltipEntrySettings:h})}),Jze=(t,e)=>t>e?"start":t<e?"end":"middle",e5e=(t,e,n)=>bs(typeof e=="function"?e(t):e,n,n*.8),t5e=(t,e,n)=>{var{top:r,left:a,width:s,height:o}=e,l=VZ(s,o),c=a+bs(t.cx,s,s/2),u=r+bs(t.cy,o,o/2),d=bs(t.innerRadius,l,0),h=e5e(n,t.outerRadius,l),f=t.maxRadius||Math.sqrt(s*s+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:h,maxRadius:f}},n5e=(t,e)=>{var n=Ri(e-t),r=Math.min(Math.abs(e-t),360);return n*r},r5e=(t,e)=>{if(w.isValidElement(t))return w.cloneElement(t,e);if(typeof t=="function")return t(e);var n=ir("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:r}=e,a=aA(e,$ze);return w.createElement(nb,Qh({},a,{type:"linear",className:n}))},a5e=(t,e,n)=>{if(w.isValidElement(t))return w.cloneElement(t,e);var r=n;if(typeof t=="function"&&(r=t(e),w.isValidElement(r)))return r;var a=ir("recharts-pie-label-text",pte(t));return w.createElement(Zk,Qh({},e,{alignmentBaseline:"middle",className:a}),r)};function i5e(t){var{sectors:e,props:n,showLabels:r}=t,{label:a,labelLine:s,dataKey:o}=n;if(!r||!a||!e)return null;var l=Fs(n),c=Uf(a),u=Uf(s),d=typeof a=="object"&&"offsetRadius"in a&&typeof a.offsetRadius=="number"&&a.offsetRadius||20,h=e.map((f,p)=>{var x=(f.startAngle+f.endAngle)/2,v=ei(f.cx,f.cy,f.outerRadius+d,x),g=Ma(Ma(Ma(Ma({},l),f),{},{stroke:"none"},c),{},{index:p,textAnchor:Jze(v.x,f.cx)},v),y=Ma(Ma(Ma(Ma({},l),f),{},{fill:"none",stroke:f.fill},u),{},{index:p,points:[ei(f.cx,f.cy,f.outerRadius,x),v],key:"line"});return w.createElement(vs,{zIndex:Da.label,key:"label-".concat(f.startAngle,"-").concat(f.endAngle,"-").concat(f.midAngle,"-").concat(p)},w.createElement(ga,null,s&&r5e(s,y),a5e(a,g,yr(f,o))))});return w.createElement(ga,{className:"recharts-pie-labels"},h)}function s5e(t){var{sectors:e,props:n,showLabels:r}=t,{label:a}=n;return typeof a=="object"&&a!=null&&"position"in a?w.createElement(Jk,{label:a}):w.createElement(i5e,{sectors:e,props:n,showLabels:r})}function o5e(t){var{sectors:e,activeShape:n,inactiveShape:r,allOtherPieProps:a,shape:s,id:o}=t,l=Kt(Yh),c=Kt(HO),u=Kt(yOe),{onMouseEnter:d,onClick:h,onMouseLeave:f}=a,p=aA(a,Vze),x=e4(d,a.dataKey,o),v=t4(f),g=n4(h,a.dataKey,o);return e==null||e.length===0?null:w.createElement(w.Fragment,null,e.map((y,_)=>{if(y?.startAngle===0&&y?.endAngle===0&&e.length!==1)return null;var N=u==null||u===o,k=String(_)===l&&(c==null||a.dataKey===c)&&N,A=l?r:null,M=n&&k?n:A,C=Ma(Ma({},y),{},{stroke:y.stroke,tabIndex:-1,[wZ]:_,[SZ]:o});return w.createElement(ga,Qh({key:"sector-".concat(y?.startAngle,"-").concat(y?.endAngle,"-").concat(y.midAngle,"-").concat(_),tabIndex:-1,className:"recharts-pie-sector"},v0(p,y,_),{onMouseEnter:x(y,_),onMouseLeave:v(y,_),onClick:g(y,_)}),w.createElement(JO,Qh({option:s??M,index:_,shapeType:"sector",isActive:k},C)))}))}function l5e(t){var e,{pieSettings:n,displayedData:r,cells:a,offset:s}=t,{cornerRadius:o,startAngle:l,endAngle:c,dataKey:u,nameKey:d,tooltipType:h}=n,f=Math.abs(n.minAngle),p=n5e(l,c),x=Math.abs(p),v=r.length<=1?0:(e=n.paddingAngle)!==null&&e!==void 0?e:0,g=r.filter(M=>yr(M,u,0)!==0).length,y=(x>=360?g:g-1)*v,_=x-g*f-y,N=r.reduce((M,C)=>{var j=yr(C,u,0);return M+(qt(j)?j:0)},0),k;if(N>0){var A;k=r.map((M,C)=>{var j=yr(M,u,0),P=yr(M,d,C),E=t5e(n,s,M),U=(qt(j)?j:0)/N,L,B=Ma(Ma({},M),a&&a[C]&&a[C].props);C?L=A.endAngle+Ri(p)*v*(j!==0?1:0):L=l;var D=L+Ri(p)*((j!==0?f:0)+U*_),$=(L+D)/2,G=(E.innerRadius+E.outerRadius)/2,z=[{name:P,value:j,payload:B,dataKey:u,type:h,graphicalItemId:n.id}],W=ei(E.cx,E.cy,G,$);return A=Ma(Ma(Ma(Ma({},n.presentationProps),{},{percent:U,cornerRadius:typeof o=="string"?parseFloat(o):o,name:P,tooltipPayload:z,midAngle:$,middleRadius:G,tooltipPosition:W},B),E),{},{value:j,dataKey:u,startAngle:L,endAngle:D,payload:B,paddingAngle:Ri(p)*v}),A})}return k}function c5e(t){var{showLabels:e,sectors:n,children:r}=t,a=w.useMemo(()=>!e||!n?[]:n.map(s=>({value:s.value,payload:s.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:s.cx,cy:s.cy,innerRadius:s.innerRadius,outerRadius:s.outerRadius,startAngle:s.startAngle,endAngle:s.endAngle,clockWise:!1},fill:s.fill})),[n,e]);return w.createElement($Ie,{value:e?a:void 0},r)}function u5e(t){var{props:e,previousSectorsRef:n,id:r}=t,{sectors:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,activeShape:u,inactiveShape:d,onAnimationStart:h,onAnimationEnd:f}=e,p=Zb(e,"recharts-pie-"),x=n.current,[v,g]=w.useState(!1),y=w.useCallback(()=>{typeof f=="function"&&f(),g(!1)},[f]),_=w.useCallback(()=>{typeof h=="function"&&h(),g(!0)},[h]);return w.createElement(c5e,{showLabels:!v,sectors:a},w.createElement(Qb,{animationId:p,begin:o,duration:l,isActive:s,easing:c,onAnimationStart:_,onAnimationEnd:y,key:p},N=>{var k,A=[],M=a&&a[0],C=(k=M?.startAngle)!==null&&k!==void 0?k:0;return a?.forEach((j,P)=>{var E=x&&x[P],U=P>0?Hf(j,"paddingAngle",0):0;if(E){var L=br(E.endAngle-E.startAngle,j.endAngle-j.startAngle,N),B=Ma(Ma({},j),{},{startAngle:C+U,endAngle:C+L+U});A.push(B),C=B.endAngle}else{var{endAngle:D,startAngle:$}=j,G=br(0,D-$,N),z=Ma(Ma({},j),{},{startAngle:C+U,endAngle:C+G+U});A.push(z),C=z.endAngle}}),n.current=A,w.createElement(ga,null,w.createElement(o5e,{sectors:A,activeShape:u,inactiveShape:d,allOtherPieProps:e,shape:e.shape,id:r}))}),w.createElement(s5e,{showLabels:!v,sectors:a,props:e}),e.children)}var d5e={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:Da.area};function h5e(t){var{id:e}=t,n=aA(t,qze),{hide:r,className:a,rootTabIndex:s}=t,o=w.useMemo(()=>QO(t.children,U0),[t.children]),l=Kt(d=>oze(d,e,o)),c=w.useRef(null),u=ir("recharts-pie",a);return r||l==null?(c.current=null,w.createElement(ga,{tabIndex:s,className:u})):w.createElement(vs,{zIndex:t.zIndex},w.createElement(Zze,{dataKey:t.dataKey,nameKey:t.nameKey,sectors:l,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,tooltipType:t.tooltipType,id:e}),w.createElement(ga,{tabIndex:s,className:u},w.createElement(u5e,{props:Ma(Ma({},n),{},{sectors:l}),previousSectorsRef:c,id:e})))}function yte(t){var e=ba(t,d5e),{id:n}=e,r=aA(e,Gze),a=Fs(r);return w.createElement(rA,{id:n,type:"pie"},s=>w.createElement(w.Fragment,null,w.createElement(Hze,{type:"pie",id:s,data:r.data,dataKey:r.dataKey,hide:r.hide,angleAxisId:0,radiusAxisId:0,name:r.name,nameKey:r.nameKey,tooltipType:r.tooltipType,legendType:r.legendType,fill:r.fill,cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,paddingAngle:r.paddingAngle,minAngle:r.minAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius,cornerRadius:r.cornerRadius,presentationProps:a,maxRadius:e.maxRadius}),w.createElement(Qze,Qh({},r,{id:s})),w.createElement(h5e,Qh({},r,{id:s}))))}yte.displayName="Pie";var m5e=["points"];function g7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Fj(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?g7(Object(n),!0).forEach(function(r){f5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):g7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function f5e(t,e,n){return(e=p5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function p5e(t){var e=g5e(t,"string");return typeof e=="symbol"?e:e+""}function g5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function EN(){return EN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},EN.apply(null,arguments)}function b5e(t,e){if(t==null)return{};var n,r,a=x5e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function x5e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function y5e(t){var{option:e,dotProps:n,className:r}=t;if(w.isValidElement(e))return w.cloneElement(e,n);if(typeof e=="function")return e(n);var a=ir(r,typeof e!="boolean"?e.className:""),s=n??{},{points:o}=s,l=b5e(s,m5e);return w.createElement(dte,EN({},l,{className:a}))}function v5e(t,e){return t==null?!1:e?!0:t.length===1}function vte(t){var{points:e,dot:n,className:r,dotClassName:a,dataKey:s,baseProps:o,needClip:l,clipPathId:c,zIndex:u=Da.scatter}=t;if(!v5e(e,n))return null;var d=ZO(n),h=HTe(n),f=e.map((x,v)=>{var g,y,_=Fj(Fj(Fj({r:3},o),h),{},{index:v,cx:(g=x.x)!==null&&g!==void 0?g:void 0,cy:(y=x.y)!==null&&y!==void 0?y:void 0,dataKey:s,value:x.value,payload:x.payload,points:e});return w.createElement(y5e,{key:"dot-".concat(v),option:n,dotProps:_,className:a})}),p={};return l&&c!=null&&(p.clipPath="url(#clipPath-".concat(d?"":"dots-").concat(c,")")),w.createElement(vs,{zIndex:u},w.createElement(ga,EN({className:r},p),f))}function b7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function x7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?b7(Object(n),!0).forEach(function(r){w5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):b7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function w5e(t,e,n){return(e=S5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function S5e(t){var e=_5e(t,"string");return typeof e=="symbol"?e:e+""}function _5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var wte=0,N5e={xAxis:{},yAxis:{},zAxis:{}},Ste=lo({name:"cartesianAxis",initialState:N5e,reducers:{addXAxis:{reducer(t,e){t.xAxis[e.payload.id]=e.payload},prepare:la()},replaceXAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.xAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.xAxis[n.id],t.xAxis[r.id]=r)},prepare:la()},removeXAxis:{reducer(t,e){delete t.xAxis[e.payload.id]},prepare:la()},addYAxis:{reducer(t,e){t.yAxis[e.payload.id]=e.payload},prepare:la()},replaceYAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.yAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.yAxis[n.id],t.yAxis[r.id]=r)},prepare:la()},removeYAxis:{reducer(t,e){delete t.yAxis[e.payload.id]},prepare:la()},addZAxis:{reducer(t,e){t.zAxis[e.payload.id]=e.payload},prepare:la()},replaceZAxis:{reducer(t,e){var{prev:n,next:r}=e.payload;t.zAxis[n.id]!==void 0&&(n.id!==r.id&&delete t.zAxis[n.id],t.zAxis[r.id]=r)},prepare:la()},removeZAxis:{reducer(t,e){delete t.zAxis[e.payload.id]},prepare:la()},updateYAxisWidth(t,e){var{id:n,width:r}=e.payload,a=t.yAxis[n];if(a){var s,o=a.widthHistory||[];if(o.length===3&&o[0]===o[2]&&r===o[1]&&r!==a.width&&Math.abs(r-((s=o[0])!==null&&s!==void 0?s:0))<=1)return;var l=[...o,r].slice(-3);t.yAxis[n]=x7(x7({},a),{},{width:r,widthHistory:l})}}}}),{addXAxis:C5e,replaceXAxis:k5e,removeXAxis:A5e,addYAxis:T5e,replaceYAxis:M5e,removeYAxis:P5e,addZAxis:Ktt,replaceZAxis:Xtt,removeZAxis:Ytt,updateYAxisWidth:E5e}=Ste.actions,j5e=Ste.reducer,D5e=ct([vi],t=>({top:t.top,bottom:t.bottom,left:t.left,right:t.right})),R5e=ct([D5e,fd,pd],(t,e,n)=>{if(!(!t||e==null||n==null))return{x:t.left,y:t.top,width:Math.max(0,e-t.left-t.right),height:Math.max(0,n-t.top-t.bottom)}}),iA=()=>Kt(R5e),F5e=()=>Kt(NOe);function y7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Lj(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?y7(Object(n),!0).forEach(function(r){L5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):y7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function L5e(t,e,n){return(e=O5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function O5e(t){var e=I5e(t,"string");return typeof e=="symbol"?e:e+""}function I5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var z5e=t=>{var{point:e,childIndex:n,mainColor:r,activeDot:a,dataKey:s,clipPath:o}=t;if(a===!1||e.x==null||e.y==null)return null;var l={index:n,dataKey:s,cx:e.x,cy:e.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:e.payload,value:e.value},c=Lj(Lj(Lj({},l),Uf(a)),yL(a)),u;return w.isValidElement(a)?u=w.cloneElement(a,c):typeof a=="function"?u=a(c):u=w.createElement(dte,c),w.createElement(ga,{className:"recharts-active-dot",clipPath:o},u)};function lR(t){var{points:e,mainColor:n,activeDot:r,itemDataKey:a,clipPath:s,zIndex:o=Da.activeDot}=t,l=Kt(Yh),c=F5e();if(e==null||c==null)return null;var u=e.find(d=>c.includes(d.payload));return ha(u)?null:w.createElement(vs,{zIndex:o},w.createElement(z5e,{point:u,childIndex:Number(l),mainColor:n,dataKey:a,activeDot:r,clipPath:s}))}var v7=(t,e,n)=>{var r=n??t;if(!ha(r))return bs(r,e,0)},U5e=(t,e,n)=>{var r={},a=t.filter(Vk),s=t.filter(u=>u.stackId==null),o=a.reduce((u,d)=>{var h=u[d.stackId];return h==null&&(h=[]),h.push(d),u[d.stackId]=h,u},r),l=Object.entries(o).map(u=>{var d,[h,f]=u,p=f.map(v=>v.dataKey),x=v7(e,n,(d=f[0])===null||d===void 0?void 0:d.barSize);return{stackId:h,dataKeys:p,barSize:x}}),c=s.map(u=>{var d=[u.dataKey].filter(f=>f!=null),h=v7(e,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:h}});return[...l,...c]};function w7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function v_(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?w7(Object(n),!0).forEach(function(r){B5e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):w7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function B5e(t,e,n){return(e=H5e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function H5e(t){var e=$5e(t,"string");return typeof e=="symbol"?e:e+""}function $5e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function V5e(t,e,n,r,a){var s,o=r.length;if(!(o<1)){var l=bs(t,n,0,!0),c,u=[];if(Nn((s=r[0])===null||s===void 0?void 0:s.barSize)){var d=!1,h=n/o,f=r.reduce((_,N)=>_+(N.barSize||0),0);f+=(o-1)*l,f>=n&&(f-=(o-1)*l,l=0),f>=n&&h>0&&(d=!0,h*=.9,f=o*h);var p=(n-f)/2>>0,x={offset:p-l,size:0};c=r.reduce((_,N)=>{var k,A={stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:x.offset+x.size+l,size:d?h:(k=N.barSize)!==null&&k!==void 0?k:0}},M=[..._,A];return x=A.position,M},u)}else{var v=bs(e,n,0,!0);n-2*v-(o-1)*l<=0&&(l=0);var g=(n-2*v-(o-1)*l)/o;g>1&&(g>>=0);var y=Nn(a)?Math.min(g,a):g;c=r.reduce((_,N,k)=>[..._,{stackId:N.stackId,dataKeys:N.dataKeys,position:{offset:v+(g+l)*k+(g-y)/2,size:y}}],u)}return c}}var q5e=(t,e,n,r,a,s,o)=>{var l=ha(o)?e:o,c=V5e(n,r,a!==s?a:s,t,l);return a!==s&&c!=null&&(c=c.map(u=>v_(v_({},u),{},{position:v_(v_({},u.position),{},{offset:u.position.offset-a/2})}))),c},G5e=(t,e)=>{var n=$k(e);if(!(!t||n==null||e==null)){var{stackId:r}=e;if(r!=null){var a=t[r];if(a){var{stackedData:s}=a;if(s)return s.find(o=>o.key===n)}}}},W5e=(t,e)=>{if(!(t==null||e==null)){var n=t.find(r=>r.stackId===e.stackId&&e.dataKey!=null&&r.dataKeys.includes(e.dataKey));if(n!=null)return n.position}};function K5e(t,e){return t&&typeof t=="object"&&"zIndex"in t&&typeof t.zIndex=="number"&&Nn(t.zIndex)?t.zIndex:e}var _te=t=>{var{chartData:e}=t,n=qr(),r=wi();return w.useEffect(()=>r?()=>{}:(n(AG(e)),()=>{n(AG(void 0))}),[e,n,r]),null},S7={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},Nte=lo({name:"brush",initialState:S7,reducers:{setBrushSettings(t,e){return e.payload==null?S7:e.payload}}}),{setBrushSettings:Qtt}=Nte.actions,X5e=Nte.reducer,Y5e=(t,e)=>{var{x:n,y:r}=t,{x:a,y:s}=e;return{x:Math.min(n,a),y:Math.min(r,s),width:Math.abs(a-n),height:Math.abs(s-r)}},Q5e=t=>{var{x1:e,y1:n,x2:r,y2:a}=t;return Y5e({x:e,y:n},{x:r,y:a})};function Z5e(t){return(t%180+180)%180}var J5e=function(e){var{width:n,height:r}=e,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,s=Z5e(a),o=s*Math.PI/180,l=Math.atan(r/n),c=o>l&&o<Math.PI-l?r/Math.sin(o):n/Math.cos(o);return Math.abs(c)},eUe={dots:[],areas:[],lines:[]},Cte=lo({name:"referenceElements",initialState:eUe,reducers:{addDot:(t,e)=>{t.dots.push(e.payload)},removeDot:(t,e)=>{var n=Kl(t).dots.findIndex(r=>r===e.payload);n!==-1&&t.dots.splice(n,1)},addArea:(t,e)=>{t.areas.push(e.payload)},removeArea:(t,e)=>{var n=Kl(t).areas.findIndex(r=>r===e.payload);n!==-1&&t.areas.splice(n,1)},addLine:(t,e)=>{t.lines.push(e.payload)},removeLine:(t,e)=>{var n=Kl(t).lines.findIndex(r=>r===e.payload);n!==-1&&t.lines.splice(n,1)}}}),{addDot:Ztt,removeDot:Jtt,addArea:ent,removeArea:tnt,addLine:tUe,removeLine:nUe}=Cte.actions,rUe=Cte.reducer,kte=w.createContext(void 0),aUe=t=>{var{children:e}=t,[n]=w.useState("".concat(Pv("recharts"),"-clip")),r=iA();if(r==null)return null;var{x:a,y:s,width:o,height:l}=r;return w.createElement(kte.Provider,{value:n},w.createElement("defs",null,w.createElement("clipPath",{id:n},w.createElement("rect",{x:a,y:s,height:l,width:o}))),e)},iUe=()=>w.useContext(kte);class sUe{constructor(e){var{x:n,y:r}=e;this.xAxisScale=n,this.yAxisScale=r}map(e,n){var r,a,{position:s}=n;return{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:0,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:0}}mapWithFallback(e,n){var r,a,{position:s,fallback:o}=n,l,c;return o==="rangeMin"?l=this.yAxisScale.rangeMin():o==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,o==="rangeMin"?c=this.xAxisScale.rangeMin():o==="rangeMax"?c=this.xAxisScale.rangeMax():c=0,{x:(r=this.xAxisScale.map(e.x,{position:s}))!==null&&r!==void 0?r:c,y:(a=this.yAxisScale.map(e.y,{position:s}))!==null&&a!==void 0?a:l}}isInRange(e){var{x:n,y:r}=e,a=n==null||this.xAxisScale.isInRange(n),s=r==null||this.yAxisScale.isInRange(r);return a&&s}}function _7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function N7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?_7(Object(n),!0).forEach(function(r){oUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function oUe(t,e,n){return(e=lUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function lUe(t){var e=cUe(t,"string");return typeof e=="symbol"?e:e+""}function cUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jN(){return jN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},jN.apply(null,arguments)}var uUe=(t,e)=>{var n;if(w.isValidElement(t))n=w.cloneElement(t,e);else if(typeof t=="function")n=t(e);else{if(!Nn(e.x1)||!Nn(e.y1)||!Nn(e.x2)||!Nn(e.y2))return null;n=w.createElement("line",jN({},e,{className:"recharts-reference-line-line"}))}return n},dUe=(t,e,n,r,a,s)=>{var{x:o,width:l}=s,c=a.map(t,{position:n});if(!Nn(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},hUe=(t,e,n,r,a,s)=>{var{y:o,height:l}=s,c=a.map(t,{position:n});if(!Nn(c)||e==="discard"&&!a.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},mUe=(t,e,n,r)=>{var a=[r.mapWithFallback(t[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(t[1],{position:n,fallback:"rangeMax"})];return e==="discard"&&a.some(s=>!r.isInRange(s))?null:a},fUe=(t,e,n,r,a,s,o)=>{var{x:l,y:c,segment:u,ifOverflow:d}=o,h=_l(l),f=_l(c);return f?dUe(c,d,r,s,e,n):h?hUe(l,d,r,a,t,n):u!=null&&u.length===2?mUe(u,d,r,new sUe({x:t,y:e})):null};function pUe(t){var e=qr();return w.useEffect(()=>(e(tUe(t)),()=>{e(nUe(t))})),null}function gUe(t){var{xAxisId:e,yAxisId:n,shape:r,className:a,ifOverflow:s}=t,o=wi(),l=iUe(),c=Kt(C=>qc(C,e)),u=Kt(C=>Gc(C,n)),d=Kt(C=>Mb(C,"xAxis",e,o)),h=Kt(C=>Mb(C,"yAxis",n,o)),f=N0();if(!l||!f||c==null||u==null||d==null||h==null)return null;var p=fUe(d,h,f,t.position,c.orientation,u.orientation,t);if(!p)return null;var x=p[0],v=p[1];if(x==null||v==null)return null;var{x:g,y}=x,{x:_,y:N}=v,k=s==="hidden"?"url(#".concat(l,")"):void 0,A=N7(N7({clipPath:k},ts(t)),{},{x1:g,y1:y,x2:_,y2:N}),M=Q5e({x1:g,y1:y,x2:_,y2:N});return w.createElement(vs,{zIndex:t.zIndex},w.createElement(ga,{className:ir("recharts-reference-line",a)},uUe(r,A),w.createElement(ste,jN({},M,{lowerWidth:M.width,upperWidth:M.width}),w.createElement(lte,{label:t.label}),t.children)))}var bUe={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:Da.line};function Dy(t){var e=ba(t,bUe);return w.createElement(w.Fragment,null,w.createElement(pUe,{yAxisId:e.yAxisId,xAxisId:e.xAxisId,ifOverflow:e.ifOverflow,x:e.x,y:e.y,segment:e.segment}),w.createElement(gUe,e))}Dy.displayName="ReferenceLine";function Ate(t,e){if(e<1)return[];if(e===1)return t;for(var n=[],r=0;r<t.length;r+=e){var a=t[r];a!==void 0&&n.push(a)}return n}function xUe(t,e,n){var r={width:t.width+e.width,height:t.height+e.height};return J5e(r,n)}function yUe(t,e,n){var r=n==="width",{x:a,y:s,width:o,height:l}=t;return e===1?{start:r?a:s,end:r?a+o:s+l}:{start:r?a+o:s+l,end:r?a:s}}function Vv(t,e,n,r,a){if(t*e<t*r||t*e>t*a)return!1;var s=n();return t*(e-t*s/2-r)>=0&&t*(e+t*s/2-a)<=0}function vUe(t,e){return Ate(t,e+1)}function wUe(t,e,n,r,a){for(var s=(r||[]).slice(),{start:o,end:l}=e,c=0,u=1,d=o,h=function(){var x=r?.[c];if(x===void 0)return{v:Ate(r,u)};var v=c,g,y=()=>(g===void 0&&(g=n(x,v)),g),_=x.coordinate,N=c===0||Vv(t,_,y,d,l);N||(c=0,d=o,u+=1),N&&(d=_+t*(y()/2+a),c+=u)},f;u<=s.length;)if(f=h(),f)return f.v;return[]}function SUe(t,e,n,r,a){var s=(r||[]).slice(),o=s.length;if(o===0)return[];for(var{start:l,end:c}=e,u=1;u<=o;u++){for(var d=(o-1)%u,h=l,f=!0,p=function(){var k=r[v];if(k==null)return 0;var A=v,M,C=()=>(M===void 0&&(M=n(k,A)),M),j=k.coordinate,P=v===d||Vv(t,j,C,h,c);if(!P)return f=!1,1;P&&(h=j+t*(C()/2+a))},x,v=d;v<o&&(x=p(),!(x!==0&&x===1));v+=u);if(f){for(var g=[],y=d;y<o;y+=u){var _=r[y];_!=null&&g.push(_)}return g}}return[]}function C7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function ds(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?C7(Object(n),!0).forEach(function(r){_Ue(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):C7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function _Ue(t,e,n){return(e=NUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function NUe(t){var e=CUe(t,"string");return typeof e=="symbol"?e:e+""}function CUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function kUe(t,e,n,r,a){for(var s=(r||[]).slice(),o=s.length,{start:l}=e,{end:c}=e,u=function(f){var p=s[f];if(p==null)return 1;var x=p,v,g=()=>(v===void 0&&(v=n(p,f)),v);if(f===o-1){var y=t*(x.coordinate+t*g()/2-c);s[f]=x=ds(ds({},x),{},{tickCoord:y>0?x.coordinate-y*t:x.coordinate})}else s[f]=x=ds(ds({},x),{},{tickCoord:x.coordinate});if(x.tickCoord!=null){var _=Vv(t,x.tickCoord,g,l,c);_&&(c=x.tickCoord-t*(g()/2+a),s[f]=ds(ds({},x),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return s}function AUe(t,e,n,r,a,s){var o=(r||[]).slice(),l=o.length,{start:c,end:u}=e;if(s){var d=r[l-1];if(d!=null){var h=n(d,l-1),f=t*(d.coordinate+t*h/2-u);if(o[l-1]=d=ds(ds({},d),{},{tickCoord:f>0?d.coordinate-f*t:d.coordinate}),d.tickCoord!=null){var p=Vv(t,d.tickCoord,()=>h,c,u);p&&(u=d.tickCoord-t*(h/2+a),o[l-1]=ds(ds({},d),{},{isShow:!0}))}}}for(var x=s?l-1:l,v=function(_){var N=o[_];if(N==null)return 1;var k=N,A,M=()=>(A===void 0&&(A=n(N,_)),A);if(_===0){var C=t*(k.coordinate-t*M()/2-c);o[_]=k=ds(ds({},k),{},{tickCoord:C<0?k.coordinate-C*t:k.coordinate})}else o[_]=k=ds(ds({},k),{},{tickCoord:k.coordinate});if(k.tickCoord!=null){var j=Vv(t,k.tickCoord,M,c,u);j&&(c=k.tickCoord+t*(M()/2+a),o[_]=ds(ds({},k),{},{isShow:!0}))}},g=0;g<x;g++)v(g);return o}function i4(t,e,n){var{tick:r,ticks:a,viewBox:s,minTickGap:o,orientation:l,interval:c,tickFormatter:u,unit:d,angle:h}=t;if(!a||!a.length||!r)return[];if(qt(c)||A0.isSsr){var f;return(f=vUe(a,qt(c)?c:0))!==null&&f!==void 0?f:[]}var p=[],x=l==="top"||l==="bottom"?"width":"height",v=d&&x==="width"?Yy(d,{fontSize:e,letterSpacing:n}):{width:0,height:0},g=(A,M)=>{var C=typeof u=="function"?u(A.value,M):A.value;return x==="width"?xUe(Yy(C,{fontSize:e,letterSpacing:n}),v,h):Yy(C,{fontSize:e,letterSpacing:n})[x]},y=a[0],_=a[1],N=a.length>=2&&y!=null&&_!=null?Ri(_.coordinate-y.coordinate):1,k=yUe(s,N,x);return c==="equidistantPreserveStart"?wUe(N,k,g,a,o):c==="equidistantPreserveEnd"?SUe(N,k,g,a,o):(c==="preserveStart"||c==="preserveStartEnd"?p=AUe(N,k,g,a,o,c==="preserveStartEnd"):p=kUe(N,k,g,a,o),p.filter(A=>A.isShow))}var TUe=t=>{var{ticks:e,label:n,labelGapWithTick:r=5,tickSize:a=0,tickMargin:s=0}=t,o=0;if(e){Array.from(e).forEach(d=>{if(d){var h=d.getBoundingClientRect();h.width>o&&(o=h.width)}});var l=n?n.getBoundingClientRect().width:0,c=a+s,u=o+c+l+(n?r:0);return Math.round(u)}return 0},MUe=["axisLine","width","height","className","hide","ticks","axisType"];function PUe(t,e){if(t==null)return{};var n,r,a=EUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function EUe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function Kf(){return Kf=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Kf.apply(null,arguments)}function k7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Aa(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?k7(Object(n),!0).forEach(function(r){jUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):k7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function jUe(t,e,n){return(e=DUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function DUe(t){var e=RUe(t,"string");return typeof e=="symbol"?e:e+""}function RUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Ku={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd",zIndex:Da.axis};function FUe(t){var{x:e,y:n,width:r,height:a,orientation:s,mirror:o,axisLine:l,otherSvgProps:c}=t;if(!l)return null;var u=Aa(Aa(Aa({},c),Fs(l)),{},{fill:"none"});if(s==="top"||s==="bottom"){var d=+(s==="top"&&!o||s==="bottom"&&o);u=Aa(Aa({},u),{},{x1:e,y1:n+d*a,x2:e+r,y2:n+d*a})}else{var h=+(s==="left"&&!o||s==="right"&&o);u=Aa(Aa({},u),{},{x1:e+h*r,y1:n,x2:e+h*r,y2:n+a})}return w.createElement("line",Kf({},u,{className:ir("recharts-cartesian-axis-line",Hf(l,"className"))}))}function LUe(t,e,n,r,a,s,o,l,c){var u,d,h,f,p,x,v=l?-1:1,g=t.tickSize||o,y=qt(t.tickCoord)?t.tickCoord:t.coordinate;switch(s){case"top":u=d=t.coordinate,f=n+ +!l*a,h=f-v*g,x=h-v*c,p=y;break;case"left":h=f=t.coordinate,d=e+ +!l*r,u=d-v*g,p=u-v*c,x=y;break;case"right":h=f=t.coordinate,d=e+ +l*r,u=d+v*g,p=u+v*c,x=y;break;default:u=d=t.coordinate,f=n+ +l*a,h=f+v*g,x=h+v*c,p=y;break}return{line:{x1:u,y1:h,x2:d,y2:f},tick:{x:p,y:x}}}function OUe(t,e){switch(t){case"left":return e?"start":"end";case"right":return e?"end":"start";default:return"middle"}}function IUe(t,e){switch(t){case"left":case"right":return"middle";case"top":return e?"start":"end";default:return e?"end":"start"}}function zUe(t){var{option:e,tickProps:n,value:r}=t,a,s=ir(n.className,"recharts-cartesian-axis-tick-value");if(w.isValidElement(e))a=w.cloneElement(e,Aa(Aa({},n),{},{className:s}));else if(typeof e=="function")a=e(Aa(Aa({},n),{},{className:s}));else{var o="recharts-cartesian-axis-tick-value";typeof e!="boolean"&&(o=ir(o,pte(e))),a=w.createElement(Zk,Kf({},n,{className:o}),r)}return a}var UUe=w.forwardRef((t,e)=>{var{ticks:n=[],tick:r,tickLine:a,stroke:s,tickFormatter:o,unit:l,padding:c,tickTextProps:u,orientation:d,mirror:h,x:f,y:p,width:x,height:v,tickSize:g,tickMargin:y,fontSize:_,letterSpacing:N,getTicksConfig:k,events:A,axisType:M}=t,C=i4(Aa(Aa({},k),{},{ticks:n}),_,N),j=OUe(d,h),P=IUe(d,h),E=Fs(k),U=Uf(r),L={};typeof a=="object"&&(L=a);var B=Aa(Aa({},E),{},{fill:"none"},L),D=C.map(z=>Aa({entry:z},LUe(z,f,p,x,v,d,g,h,y))),$=D.map(z=>{var{entry:W,line:X}=z;return w.createElement(ga,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(W.value,"-").concat(W.coordinate,"-").concat(W.tickCoord)},a&&w.createElement("line",Kf({},B,X,{className:ir("recharts-cartesian-axis-tick-line",Hf(a,"className"))})))}),G=D.map((z,W)=>{var X,ae,{entry:H,tick:K}=z,te=Aa(Aa(Aa(Aa({verticalAnchor:P},E),{},{textAnchor:j,stroke:"none",fill:s},K),{},{index:W,payload:H,visibleTicksCount:C.length,tickFormatter:o,padding:c},u),{},{angle:(X=(ae=u?.angle)!==null&&ae!==void 0?ae:E.angle)!==null&&X!==void 0?X:0}),Z=Aa(Aa({},te),U);return w.createElement(ga,Kf({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(H.value,"-").concat(H.coordinate,"-").concat(H.tickCoord)},v0(A,H,W)),r&&w.createElement(zUe,{option:r,tickProps:Z,value:"".concat(typeof o=="function"?o(H.value,W):H.value).concat(l||"")}))});return w.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(M,"-ticks")},G.length>0&&w.createElement(vs,{zIndex:Da.label},w.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(M,"-tick-labels"),ref:e},G)),$.length>0&&w.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(M,"-tick-lines")},$))}),BUe=w.forwardRef((t,e)=>{var{axisLine:n,width:r,height:a,className:s,hide:o,ticks:l,axisType:c}=t,u=PUe(t,MUe),[d,h]=w.useState(""),[f,p]=w.useState(""),x=w.useRef(null);w.useImperativeHandle(e,()=>({getCalculatedWidth:()=>{var g;return TUe({ticks:x.current,label:(g=t.labelRef)===null||g===void 0?void 0:g.current,labelGapWithTick:5,tickSize:t.tickSize,tickMargin:t.tickMargin})}}));var v=w.useCallback(g=>{if(g){var y=g.getElementsByClassName("recharts-cartesian-axis-tick-value");x.current=y;var _=y[0];if(_){var N=window.getComputedStyle(_),k=N.fontSize,A=N.letterSpacing;(k!==d||A!==f)&&(h(k),p(A))}}},[d,f]);return o||r!=null&&r<=0||a!=null&&a<=0?null:w.createElement(vs,{zIndex:t.zIndex},w.createElement(ga,{className:ir("recharts-cartesian-axis",s)},w.createElement(FUe,{x:t.x,y:t.y,width:r,height:a,orientation:t.orientation,mirror:t.mirror,axisLine:n,otherSvgProps:Fs(t)}),w.createElement(UUe,{ref:v,axisType:c,events:u,fontSize:d,getTicksConfig:t,height:t.height,letterSpacing:f,mirror:t.mirror,orientation:t.orientation,padding:t.padding,stroke:t.stroke,tick:t.tick,tickFormatter:t.tickFormatter,tickLine:t.tickLine,tickMargin:t.tickMargin,tickSize:t.tickSize,tickTextProps:t.tickTextProps,ticks:l,unit:t.unit,width:t.width,x:t.x,y:t.y}),w.createElement(ste,{x:t.x,y:t.y,width:t.width,height:t.height,lowerWidth:t.width,upperWidth:t.width},w.createElement(lte,{label:t.label,labelRef:t.labelRef}),t.children)))}),s4=w.forwardRef((t,e)=>{var n=ba(t,Ku);return w.createElement(BUe,Kf({},n,{ref:e}))});s4.displayName="CartesianAxis";var HUe=["x1","y1","x2","y2","key"],$Ue=["offset"],VUe=["xAxisId","yAxisId"],qUe=["xAxisId","yAxisId"];function A7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function fs(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?A7(Object(n),!0).forEach(function(r){GUe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):A7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function GUe(t,e,n){return(e=WUe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function WUe(t){var e=KUe(t,"string");return typeof e=="symbol"?e:e+""}function KUe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function sf(){return sf=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},sf.apply(null,arguments)}function DN(t,e){if(t==null)return{};var n,r,a=XUe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function XUe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var YUe=t=>{var{fill:e}=t;if(!e||e==="none")return null;var{fillOpacity:n,x:r,y:a,width:s,height:o,ry:l}=t;return w.createElement("rect",{x:r,y:a,ry:l,width:s,height:o,stroke:"none",fill:e,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Tte(t){var{option:e,lineItemProps:n}=t,r;if(w.isValidElement(e))r=w.cloneElement(e,n);else if(typeof e=="function")r=e(n);else{var a,{x1:s,y1:o,x2:l,y2:c,key:u}=n,d=DN(n,HUe),h=(a=Fs(d))!==null&&a!==void 0?a:{},{offset:f}=h,p=DN(h,$Ue);r=w.createElement("line",sf({},p,{x1:s,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function QUe(t){var{x:e,width:n,horizontal:r=!0,horizontalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=DN(t,VUe),c=a.map((u,d)=>{var h=fs(fs({},l),{},{x1:e,y1:u,x2:e+n,y2:u,key:"line-".concat(d),index:d});return w.createElement(Tte,{key:"line-".concat(d),option:r,lineItemProps:h})});return w.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function ZUe(t){var{y:e,height:n,vertical:r=!0,verticalPoints:a}=t;if(!r||!a||!a.length)return null;var{xAxisId:s,yAxisId:o}=t,l=DN(t,qUe),c=a.map((u,d)=>{var h=fs(fs({},l),{},{x1:u,y1:e,x2:u,y2:e+n,key:"line-".concat(d),index:d});return w.createElement(Tte,{option:r,lineItemProps:h,key:"line-".concat(d)})});return w.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function JUe(t){var{horizontalFill:e,fillOpacity:n,x:r,y:a,width:s,height:o,horizontalPoints:l,horizontal:c=!0}=t;if(!c||!e||!e.length||l==null)return null;var u=l.map(h=>Math.round(h+a-a)).sort((h,f)=>h-f);a!==u[0]&&u.unshift(0);var d=u.map((h,f)=>{var p=u[f+1],x=p==null,v=x?a+o-h:p-h;if(v<=0)return null;var g=f%e.length;return w.createElement("rect",{key:"react-".concat(f),y:h,x:r,height:v,width:s,stroke:"none",fill:e[g],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},d)}function eBe(t){var{vertical:e=!0,verticalFill:n,fillOpacity:r,x:a,y:s,width:o,height:l,verticalPoints:c}=t;if(!e||!n||!n.length)return null;var u=c.map(h=>Math.round(h+a-a)).sort((h,f)=>h-f);a!==u[0]&&u.unshift(0);var d=u.map((h,f)=>{var p=u[f+1],x=p==null,v=x?a+o-h:p-h;if(v<=0)return null;var g=f%n.length;return w.createElement("rect",{key:"react-".concat(f),x:h,y:s,width:v,height:l,stroke:"none",fill:n[g],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return w.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},d)}var tBe=(t,e)=>{var{xAxis:n,width:r,height:a,offset:s}=t;return bZ(i4(fs(fs(fs({},Ku),n),{},{ticks:xZ(n),viewBox:{x:0,y:0,width:r,height:a}})),s.left,s.left+s.width,e)},nBe=(t,e)=>{var{yAxis:n,width:r,height:a,offset:s}=t;return bZ(i4(fs(fs(fs({},Ku),n),{},{ticks:xZ(n),viewBox:{x:0,y:0,width:r,height:a}})),s.top,s.top+s.height,e)},rBe={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:Da.grid};function RN(t){var e=jL(),n=DL(),r=kZ(),a=fs(fs({},ba(t,rBe)),{},{x:qt(t.x)?t.x:r.left,y:qt(t.y)?t.y:r.top,width:qt(t.width)?t.width:r.width,height:qt(t.height)?t.height:r.height}),{xAxisId:s,yAxisId:o,x:l,y:c,width:u,height:d,syncWithTicks:h,horizontalValues:f,verticalValues:p}=a,x=wi(),v=Kt(P=>pG(P,"xAxis",s,x)),g=Kt(P=>pG(P,"yAxis",o,x));if(!Oc(u)||!Oc(d)||!qt(l)||!qt(c))return null;var y=a.verticalCoordinatesGenerator||tBe,_=a.horizontalCoordinatesGenerator||nBe,{horizontalPoints:N,verticalPoints:k}=a;if((!N||!N.length)&&typeof _=="function"){var A=f&&f.length,M=_({yAxis:g?fs(fs({},g),{},{ticks:A?f:g.ticks}):void 0,width:e??u,height:n??d,offset:r},A?!0:h);rN(Array.isArray(M),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof M,"]")),Array.isArray(M)&&(N=M)}if((!k||!k.length)&&typeof y=="function"){var C=p&&p.length,j=y({xAxis:v?fs(fs({},v),{},{ticks:C?p:v.ticks}):void 0,width:e??u,height:n??d,offset:r},C?!0:h);rN(Array.isArray(j),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof j,"]")),Array.isArray(j)&&(k=j)}return w.createElement(vs,{zIndex:a.zIndex},w.createElement("g",{className:"recharts-cartesian-grid"},w.createElement(YUe,{fill:a.fill,fillOpacity:a.fillOpacity,x:a.x,y:a.y,width:a.width,height:a.height,ry:a.ry}),w.createElement(JUe,sf({},a,{horizontalPoints:N})),w.createElement(eBe,sf({},a,{verticalPoints:k})),w.createElement(QUe,sf({},a,{offset:r,horizontalPoints:N,xAxis:v,yAxis:g})),w.createElement(ZUe,sf({},a,{offset:r,verticalPoints:k,xAxis:v,yAxis:g}))))}RN.displayName="CartesianGrid";var aBe={},Mte=lo({name:"errorBars",initialState:aBe,reducers:{addErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]||(t[n]=[]),t[n].push(r)},replaceErrorBar:(t,e)=>{var{itemId:n,prev:r,next:a}=e.payload;t[n]&&(t[n]=t[n].map(s=>s.dataKey===r.dataKey&&s.direction===r.direction?a:s))},removeErrorBar:(t,e)=>{var{itemId:n,errorBar:r}=e.payload;t[n]&&(t[n]=t[n].filter(a=>a.dataKey!==r.dataKey||a.direction!==r.direction))}}}),{addErrorBar:nnt,replaceErrorBar:rnt,removeErrorBar:ant}=Mte.actions,iBe=Mte.reducer,sBe=["children"];function oBe(t,e){if(t==null)return{};var n,r,a=lBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function lBe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var cBe={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},uBe=w.createContext(cBe);function Pte(t){var{children:e}=t,n=oBe(t,sBe);return w.createElement(uBe.Provider,{value:n},e)}function sA(t,e){var n,r,a=Kt(u=>qc(u,t)),s=Kt(u=>Gc(u,e)),o=(n=a?.allowDataOverflow)!==null&&n!==void 0?n:Mi.allowDataOverflow,l=(r=s?.allowDataOverflow)!==null&&r!==void 0?r:Pi.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function o4(t){var{xAxisId:e,yAxisId:n,clipPathId:r}=t,a=iA(),{needClipX:s,needClipY:o,needClip:l}=sA(e,n);if(!l||!a)return null;var{x:c,y:u,width:d,height:h}=a;return w.createElement("clipPath",{id:"clipPath-".concat(r)},w.createElement("rect",{x:s?c:c-d/2,y:o?u:u-h/2,width:s?d:d*2,height:o?h:h*2}))}var Ete=(t,e,n,r)=>Uc(t,"xAxis",e,r),jte=(t,e,n,r)=>zc(t,"xAxis",e,r),Dte=(t,e,n,r)=>Uc(t,"yAxis",n,r),Rte=(t,e,n,r)=>zc(t,"yAxis",n,r),dBe=ct([ar,Ete,Dte,jte,Rte],(t,e,n,r,a)=>sc(t,"xAxis")?Xh(e,r,!1):Xh(n,a,!1)),hBe=(t,e,n,r,a)=>a;function mBe(t){return t.type==="line"}var fBe=ct([R0,hBe],(t,e)=>t.filter(mBe).find(n=>n.id===e)),pBe=ct([ar,Ete,Dte,jte,Rte,fBe,dBe,oO],(t,e,n,r,a,s,o,l)=>{var{chartData:c,dataStartIndex:u,dataEndIndex:d}=l;if(!(s==null||e==null||n==null||r==null||a==null||r.length===0||a.length===0||o==null||t!=="horizontal"&&t!=="vertical")){var{dataKey:h,data:f}=s,p;if(f!=null&&f.length>0?p=f:p=c?.slice(u,d+1),p!=null)return t8e({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataKey:h,bandSize:o,displayedData:p})}});function Fte(t){var e=Uf(t),n=3,r=2;if(e!=null){var{r:a,strokeWidth:s}=e,o=Number(a),l=Number(s);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(l)||l<0)&&(l=r),{r:o,strokeWidth:l}}return{r:n,strokeWidth:r}}var Oj={exports:{}},Ij={};var T7;function gBe(){if(T7)return Ij;T7=1;var t=zb();function e(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:e,r=t.useSyncExternalStore,a=t.useRef,s=t.useEffect,o=t.useMemo,l=t.useDebugValue;return Ij.useSyncExternalStoreWithSelector=function(c,u,d,h,f){var p=a(null);if(p.current===null){var x={hasValue:!1,value:null};p.current=x}else x=p.current;p=o(function(){function g(A){if(!y){if(y=!0,_=A,A=h(A),f!==void 0&&x.hasValue){var M=x.value;if(f(M,A))return N=M}return N=A}if(M=N,n(_,A))return M;var C=h(A);return f!==void 0&&f(M,C)?(_=A,M):(_=A,N=C)}var y=!1,_,N,k=d===void 0?null:d;return[function(){return g(u())},k===null?void 0:function(){return g(k())}]},[u,d,h,f]);var v=r(c,p[0],p[1]);return s(function(){x.hasValue=!0,x.value=v},[v]),l(v),v},Ij}var M7;function bBe(){return M7||(M7=1,Oj.exports=gBe()),Oj.exports}bBe();function xBe(t){t()}function yBe(){let t=null,e=null;return{clear(){t=null,e=null},notify(){xBe(()=>{let n=t;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=t;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const a=e={callback:n,next:null,prev:e};return a.prev?a.prev.next=a:t=a,function(){!r||t===null||(r=!1,a.next?a.next.prev=a.prev:e=a.prev,a.prev?a.prev.next=a.next:t=a.next)}}}}var P7={notify(){},get:()=>[]};function vBe(t,e){let n,r=P7,a=0,s=!1;function o(v){d();const g=r.subscribe(v);let y=!1;return()=>{y||(y=!0,g(),h())}}function l(){r.notify()}function c(){x.onStateChange&&x.onStateChange()}function u(){return s}function d(){a++,n||(n=t.subscribe(c),r=yBe())}function h(){a--,n&&a===0&&(n(),n=void 0,r.clear(),r=P7)}function f(){s||(s=!0,d())}function p(){s&&(s=!1,h())}const x={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:f,tryUnsubscribe:p,getListeners:()=>r};return x}var wBe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",SBe=wBe(),_Be=()=>typeof navigator<"u"&&navigator.product==="ReactNative",NBe=_Be(),CBe=()=>SBe||NBe?w.useLayoutEffect:w.useEffect,kBe=CBe();function E7(t,e){return t===e?t!==0||e!==0||1/t===1/e:t!==t&&e!==e}function ABe(t,e){if(E7(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let a=0;a<n.length;a++)if(!Object.prototype.hasOwnProperty.call(e,n[a])||!E7(t[n[a]],e[n[a]]))return!1;return!0}var TBe=Symbol.for("react-redux-context"),MBe=typeof globalThis<"u"?globalThis:{};function PBe(){if(!w.createContext)return{};const t=MBe[TBe]??=new Map;let e=t.get(w.createContext);return e||(e=w.createContext(null),t.set(w.createContext,e)),e}var EBe=PBe();function jBe(t){const{children:e,context:n,serverState:r,store:a}=t,s=w.useMemo(()=>{const c=vBe(a);return{store:a,subscription:c,getServerState:r?()=>r:void 0}},[a,r]),o=w.useMemo(()=>a.getState(),[a]);kBe(()=>{const{subscription:c}=s;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==a.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[s,o]);const l=n||EBe;return w.createElement(l.Provider,{value:s},e)}var DBe=jBe,RBe=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius"]);function FBe(t,e){return t==null&&e==null?!0:typeof t=="number"&&typeof e=="number"?t===e||t!==t&&e!==e:t===e}function B0(t,e){var n=new Set([...Object.keys(t),...Object.keys(e)]);for(var r of n)if(RBe.has(r)){if(t[r]==null&&e[r]==null)continue;if(!ABe(t[r],e[r]))return!1}else if(!FBe(t[r],e[r]))return!1;return!0}var LBe=["id"],OBe=["type","layout","connectNulls","needClip","shape"],IBe=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function qv(){return qv=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},qv.apply(null,arguments)}function j7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Sc(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?j7(Object(n),!0).forEach(function(r){zBe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):j7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function zBe(t,e,n){return(e=UBe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function UBe(t){var e=BBe(t,"string");return typeof e=="symbol"?e:e+""}function BBe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function l4(t,e){if(t==null)return{};var n,r,a=HBe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function HBe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var $Be=t=>{var{dataKey:e,name:n,stroke:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:tm(n,e),payload:t}]},VBe=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,h={dataDefinedOnItem:n,getPosition:em,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:tm(o,e),hide:l,type:u,color:r,unit:c,graphicalItemId:d}};return w.createElement(nA,{tooltipEntrySettings:h})}),Lte=(t,e)=>"".concat(e,"px ").concat(t-e,"px");function qBe(t,e){for(var n=t.length%2!==0?[...t,0]:t,r=[],a=0;a<e;++a)r=[...r,...n];return r}var GBe=(t,e,n)=>{var r=n.reduce((p,x)=>p+x);if(!r)return Lte(e,t);for(var a=Math.floor(t/r),s=t%r,o=e-t,l=[],c=0,u=0;c<n.length;u+=(d=n[c])!==null&&d!==void 0?d:0,++c){var d,h=n[c];if(h!=null&&u+h>s){l=[...n.slice(0,c),s-u];break}}var f=l.length%2===0?[0,o]:[o];return[...qBe(n,a),...l,...f].map(p=>"".concat(p,"px")).join(", ")};function WBe(t){var{clipPathId:e,points:n,props:r}=t,{dot:a,dataKey:s,needClip:o}=r,{id:l}=r,c=l4(r,LBe),u=Fs(c);return w.createElement(vte,{points:n,dot:a,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:s,baseProps:u,needClip:o,clipPathId:e})}function KBe(t){var{showLabels:e,children:n,points:r}=t,a=w.useMemo(()=>r?.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Sc(Sc({},c),{},{value:s.value,payload:s.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return w.createElement(KO,{value:e?a:void 0},n)}function D7(t){var{clipPathId:e,pathRef:n,points:r,strokeDasharray:a,props:s}=t,{type:o,layout:l,connectNulls:c,needClip:u,shape:d}=s,h=l4(s,OBe),f=Sc(Sc({},ts(h)),{},{fill:"none",className:"recharts-line-curve",clipPath:u?"url(#clipPath-".concat(e,")"):void 0,points:r,type:o,layout:l,connectNulls:c,strokeDasharray:a??s.strokeDasharray});return w.createElement(w.Fragment,null,r?.length>1&&w.createElement(JO,qv({shapeType:"curve",option:d},f,{pathRef:n})),w.createElement(WBe,{points:r,clipPathId:e,props:s}))}function XBe(t){try{return t&&t.getTotalLength&&t.getTotalLength()||0}catch{return 0}}function YBe(t){var{clipPathId:e,props:n,pathRef:r,previousPointsRef:a,longestAnimatedLengthRef:s}=t,{points:o,strokeDasharray:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:h,animateNewValues:f,width:p,height:x,onAnimationEnd:v,onAnimationStart:g}=n,y=a.current,_=Zb(o,"recharts-line-"),N=w.useRef(_),[k,A]=w.useState(!1),M=!k,C=w.useCallback(()=>{typeof v=="function"&&v(),A(!1)},[v]),j=w.useCallback(()=>{typeof g=="function"&&g(),A(!0)},[g]),P=XBe(r.current),E=w.useRef(0);N.current!==_&&(E.current=s.current,N.current=_);var U=E.current;return w.createElement(KBe,{points:o,showLabels:M},n.children,w.createElement(Qb,{animationId:_,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:C,onAnimationStart:j,key:_},L=>{var B=br(U,P+U,L),D=Math.min(B,P),$;if(c)if(l){var G="".concat(l).split(/[,\s]+/gim).map(X=>parseFloat(X));$=GBe(D,P,G)}else $=Lte(P,D);else $=l==null?void 0:String(l);if(L>0&&P>0&&(a.current=o,s.current=Math.max(s.current,D)),y){var z=y.length/o.length,W=L===1?o:o.map((X,ae)=>{var H=Math.floor(ae*z);if(y[H]){var K=y[H];return Sc(Sc({},X),{},{x:br(K.x,X.x,L),y:br(K.y,X.y,L)})}return f?Sc(Sc({},X),{},{x:br(p*2,X.x,L),y:br(x/2,X.y,L)}):Sc(Sc({},X),{},{x:X.x,y:X.y})});return a.current=W,w.createElement(D7,{props:n,points:W,clipPathId:e,pathRef:r,strokeDasharray:$})}return w.createElement(D7,{props:n,points:o,clipPathId:e,pathRef:r,strokeDasharray:$})}),w.createElement(Jk,{label:n.label}))}function QBe(t){var{clipPathId:e,props:n}=t,r=w.useRef(null),a=w.useRef(0),s=w.useRef(null);return w.createElement(YBe,{props:n,clipPathId:e,previousPointsRef:r,longestAnimatedLengthRef:a,pathRef:s})}var ZBe=(t,e)=>{var n,r;return{x:(n=t.x)!==null&&n!==void 0?n:void 0,y:(r=t.y)!==null&&r!==void 0?r:void 0,value:t.value,errorVal:yr(t.payload,e)}};class JBe extends w.Component{render(){var{hide:e,dot:n,points:r,className:a,xAxisId:s,yAxisId:o,top:l,left:c,width:u,height:d,id:h,needClip:f,zIndex:p}=this.props;if(e)return null;var x=ir("recharts-line",a),v=h,{r:g,strokeWidth:y}=Fte(n),_=ZO(n),N=g*2+y,k=f?"url(#clipPath-".concat(_?"":"dots-").concat(v,")"):void 0;return w.createElement(vs,{zIndex:p},w.createElement(ga,{className:x},f&&w.createElement("defs",null,w.createElement(o4,{clipPathId:v,xAxisId:s,yAxisId:o}),!_&&w.createElement("clipPath",{id:"clipPath-dots-".concat(v)},w.createElement("rect",{x:c-N/2,y:l-N/2,width:u+N,height:d+N}))),w.createElement(Pte,{xAxisId:s,yAxisId:o,data:r,dataPointFormatter:ZBe,errorBarOffset:0},w.createElement(QBe,{props:this.props,clipPathId:v}))),w.createElement(lR,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:k}))}}var Ote={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:Da.line,type:"linear"};function e8e(t){var e=ba(t,Ote),{activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,hide:u,isAnimationActive:d,label:h,legendType:f,xAxisId:p,yAxisId:x,id:v}=e,g=l4(e,IBe),{needClip:y}=sA(p,x),_=iA(),N=nm(),k=wi(),A=Kt(E=>pBe(E,p,x,k,v));if(N!=="horizontal"&&N!=="vertical"||A==null||_==null)return null;var{height:M,width:C,x:j,y:P}=_;return w.createElement(JBe,qv({},g,{id:v,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:s,animationEasing:o,isAnimationActive:d,hide:u,label:h,legendType:f,xAxisId:p,yAxisId:x,points:A,layout:N,height:M,width:C,left:j,top:P,needClip:y}))}function t8e(t){var{layout:e,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,dataKey:o,bandSize:l,displayedData:c}=t;return c.map((u,d)=>{var h=yr(u,o);if(e==="horizontal"){var f=nN({axis:n,ticks:a,bandSize:l,entry:u,index:d}),p=ha(h)?null:r.scale.map(h);return{x:f,y:p??null,value:h,payload:u}}var x=ha(h)?null:n.scale.map(h),v=nN({axis:r,ticks:s,bandSize:l,entry:u,index:d});return x==null||v==null?null:{x,y:v,value:h,payload:u}}).filter(Boolean)}function n8e(t){var e=ba(t,Ote),n=wi();return w.createElement(rA,{id:e.id,type:"line"},r=>w.createElement(w.Fragment,null,w.createElement(r4,{legendPayload:$Be(e)}),w.createElement(VBe,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:r}),w.createElement(a4,{type:"line",id:r,data:e.data,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,hide:e.hide,isPanorama:n}),w.createElement(e8e,qv({},e,{id:r}))))}var Ite=w.memo(n8e,B0);Ite.displayName="Line";function Wc(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:wte}function Kc(t,e){var n,r;return(n=(r=t.graphicalItems.cartesianItems.find(a=>a.id===e))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:wte}var zte=(t,e,n)=>Uc(t,"xAxis",Wc(t,e),n),Ute=(t,e,n)=>zc(t,"xAxis",Wc(t,e),n),Bte=(t,e,n)=>Uc(t,"yAxis",Kc(t,e),n),Hte=(t,e,n)=>zc(t,"yAxis",Kc(t,e),n),r8e=ct([ar,zte,Bte,Ute,Hte],(t,e,n,r,a)=>sc(t,"xAxis")?Xh(e,r,!1):Xh(n,a,!1)),a8e=(t,e)=>e,$te=ct([R0,a8e],(t,e)=>t.filter(n=>n.type==="area").find(n=>n.id===e)),Vte=t=>{var e=ar(t),n=sc(e,"xAxis");return n?"yAxis":"xAxis"},i8e=(t,e)=>{var n=Vte(t);return n==="yAxis"?Kc(t,e):Wc(t,e)},s8e=(t,e,n)=>CN(t,Vte(t),i8e(t,e),n),o8e=ct([$te,s8e],(t,e)=>{var n;if(!(t==null||e==null)){var{stackId:r}=t,a=$k(t);if(!(r==null||a==null)){var s=(n=e[r])===null||n===void 0?void 0:n.stackedData,o=s?.find(l=>l.key===a);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),l8e=ct([ar,zte,Bte,Ute,Hte,o8e,TJ,r8e,$te,yFe],(t,e,n,r,a,s,o,l,c,u)=>{var{chartData:d,dataStartIndex:h,dataEndIndex:f}=o;if(!(c==null||t!=="horizontal"&&t!=="vertical"||e==null||n==null||r==null||a==null||r.length===0||a.length===0||l==null)){var{data:p}=c,x;if(p&&p.length>0?x=p:x=d?.slice(h,f+1),x!=null)return A8e({layout:t,xAxis:e,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataStartIndex:h,areaSettings:c,stackedData:s,displayedData:x,chartBaseValue:u,bandSize:l})}}),c8e=["id"],u8e=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function yf(){return yf=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},yf.apply(null,arguments)}function qte(t,e){if(t==null)return{};var n,r,a=d8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function d8e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function R7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function $g(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?R7(Object(n),!0).forEach(function(r){h8e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):R7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function h8e(t,e,n){return(e=m8e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function m8e(t){var e=f8e(t,"string");return typeof e=="symbol"?e:e+""}function f8e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function FN(t,e){return t&&t!=="none"?t:e}var p8e=t=>{var{dataKey:e,name:n,stroke:r,fill:a,legendType:s,hide:o}=t;return[{inactive:o,dataKey:e,type:s,color:FN(r,a),value:tm(n,e),payload:t}]},g8e=w.memo(t=>{var{dataKey:e,data:n,stroke:r,strokeWidth:a,fill:s,name:o,hide:l,unit:c,tooltipType:u,id:d}=t,h={dataDefinedOnItem:n,getPosition:em,settings:{stroke:r,strokeWidth:a,fill:s,dataKey:e,nameKey:void 0,name:tm(o,e),hide:l,type:u,color:FN(r,s),unit:c,graphicalItemId:d}};return w.createElement(nA,{tooltipEntrySettings:h})});function b8e(t){var{clipPathId:e,points:n,props:r}=t,{needClip:a,dot:s,dataKey:o}=r,l=Fs(r);return w.createElement(vte,{points:n,dot:s,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:a,clipPathId:e})}function x8e(t){var{showLabels:e,children:n,points:r}=t,a=r.map(s=>{var o,l,c={x:(o=s.x)!==null&&o!==void 0?o:0,y:(l=s.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return $g($g({},c),{},{value:s.value,payload:s.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return w.createElement(KO,{value:e?a:void 0},n)}function F7(t){var{points:e,baseLine:n,needClip:r,clipPathId:a,props:s}=t,{layout:o,type:l,stroke:c,connectNulls:u,isRange:d}=s,{id:h}=s,f=qte(s,c8e),p=Fs(f),x=ts(f);return w.createElement(w.Fragment,null,e?.length>1&&w.createElement(ga,{clipPath:r?"url(#clipPath-".concat(a,")"):void 0},w.createElement(nb,yf({},x,{id:h,points:e,connectNulls:u,type:l,baseLine:n,layout:o,stroke:"none",className:"recharts-area-area"})),c!=="none"&&w.createElement(nb,yf({},p,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:e})),c!=="none"&&d&&w.createElement(nb,yf({},p,{className:"recharts-area-curve",layout:o,type:l,connectNulls:u,fill:"none",points:n}))),w.createElement(b8e,{points:e,props:f,clipPathId:a}))}function y8e(t){var e,n,{alpha:r,baseLine:a,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.y,c=(n=s[s.length-1])===null||n===void 0?void 0:n.y;if(!Nn(l)||!Nn(c))return null;var u=r*Math.abs(l-c),d=Math.max(...s.map(h=>h.x||0));return qt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(h=>h.x||0),d)),qt(d)?w.createElement("rect",{x:0,y:l<c?l:l-u,width:d+(o?parseInt("".concat(o),10):1),height:Math.floor(u)}):null}function v8e(t){var e,n,{alpha:r,baseLine:a,points:s,strokeWidth:o}=t,l=(e=s[0])===null||e===void 0?void 0:e.x,c=(n=s[s.length-1])===null||n===void 0?void 0:n.x;if(!Nn(l)||!Nn(c))return null;var u=r*Math.abs(l-c),d=Math.max(...s.map(h=>h.y||0));return qt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(h=>h.y||0),d)),qt(d)?w.createElement("rect",{x:l<c?l:l-u,y:0,width:u,height:Math.floor(d+(o?parseInt("".concat(o),10):1))}):null}function w8e(t){var{alpha:e,layout:n,points:r,baseLine:a,strokeWidth:s}=t;return n==="vertical"?w.createElement(y8e,{alpha:e,points:r,baseLine:a,strokeWidth:s}):w.createElement(v8e,{alpha:e,points:r,baseLine:a,strokeWidth:s})}function S8e(t){var{needClip:e,clipPathId:n,props:r,previousPointsRef:a,previousBaselineRef:s}=t,{points:o,baseLine:l,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:h,onAnimationStart:f,onAnimationEnd:p}=r,x=w.useMemo(()=>({points:o,baseLine:l}),[o,l]),v=Zb(x,"recharts-area-"),g=RL(),[y,_]=w.useState(!1),N=!y,k=w.useCallback(()=>{typeof p=="function"&&p(),_(!1)},[p]),A=w.useCallback(()=>{typeof f=="function"&&f(),_(!0)},[f]);if(g==null)return null;var M=a.current,C=s.current;return w.createElement(x8e,{showLabels:N,points:o},r.children,w.createElement(Qb,{animationId:v,begin:u,duration:d,isActive:c,easing:h,onAnimationEnd:k,onAnimationStart:A,key:v},j=>{if(M){var P=M.length/o.length,E=j===1?o:o.map((L,B)=>{var D=Math.floor(B*P);if(M[D]){var $=M[D];return $g($g({},L),{},{x:br($.x,L.x,j),y:br($.y,L.y,j)})}return L}),U;return qt(l)?U=br(C,l,j):ha(l)||Jl(l)?U=br(C,0,j):U=l.map((L,B)=>{var D=Math.floor(B*P);if(Array.isArray(C)&&C[D]){var $=C[D];return $g($g({},L),{},{x:br($.x,L.x,j),y:br($.y,L.y,j)})}return L}),j>0&&(a.current=E,s.current=U),w.createElement(F7,{points:E,baseLine:U,needClip:e,clipPathId:n,props:r})}return j>0&&(a.current=o,s.current=l),w.createElement(ga,null,c&&w.createElement("defs",null,w.createElement("clipPath",{id:"animationClipPath-".concat(n)},w.createElement(w8e,{alpha:j,points:o,baseLine:l,layout:g,strokeWidth:r.strokeWidth}))),w.createElement(ga,{clipPath:"url(#animationClipPath-".concat(n,")")},w.createElement(F7,{points:o,baseLine:l,needClip:e,clipPathId:n,props:r})))}),w.createElement(Jk,{label:r.label}))}function _8e(t){var{needClip:e,clipPathId:n,props:r}=t,a=w.useRef(null),s=w.useRef();return w.createElement(S8e,{needClip:e,clipPathId:n,props:r,previousPointsRef:a,previousBaselineRef:s})}class N8e extends w.PureComponent{render(){var{hide:e,dot:n,points:r,className:a,top:s,left:o,needClip:l,xAxisId:c,yAxisId:u,width:d,height:h,id:f,baseLine:p,zIndex:x}=this.props;if(e)return null;var v=ir("recharts-area",a),g=f,{r:y,strokeWidth:_}=Fte(n),N=ZO(n),k=y*2+_,A=l?"url(#clipPath-".concat(N?"":"dots-").concat(g,")"):void 0;return w.createElement(vs,{zIndex:x},w.createElement(ga,{className:v},l&&w.createElement("defs",null,w.createElement(o4,{clipPathId:g,xAxisId:c,yAxisId:u}),!N&&w.createElement("clipPath",{id:"clipPath-dots-".concat(g)},w.createElement("rect",{x:o-k/2,y:s-k/2,width:d+k,height:h+k}))),w.createElement(_8e,{needClip:l,clipPathId:g,props:this.props})),w.createElement(lR,{points:r,mainColor:FN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:A}),this.props.isRange&&Array.isArray(p)&&w.createElement(lR,{points:p,mainColor:FN(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:A}))}}var Gte={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,xAxisId:0,yAxisId:0,zIndex:Da.area};function C8e(t){var e,n=ba(t,Gte),{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,connectNulls:l,dot:c,fill:u,fillOpacity:d,hide:h,isAnimationActive:f,legendType:p,stroke:x,xAxisId:v,yAxisId:g}=n,y=qte(n,u8e),_=nm(),N=$ee(),{needClip:k}=sA(v,g),A=wi(),{points:M,isRange:C,baseLine:j}=(e=Kt(D=>l8e(D,t.id,A)))!==null&&e!==void 0?e:{},P=iA();if(_!=="horizontal"&&_!=="vertical"||P==null||N!=="AreaChart"&&N!=="ComposedChart")return null;var{height:E,width:U,x:L,y:B}=P;return!M||!M.length?null:w.createElement(N8e,yf({},y,{activeDot:r,animationBegin:a,animationDuration:s,animationEasing:o,baseLine:j,connectNulls:l,dot:c,fill:u,fillOpacity:d,height:E,hide:h,layout:_,isAnimationActive:f==="auto"?!A0.isSsr:f,isRange:C,legendType:p,needClip:k,points:M,stroke:x,width:U,left:L,top:B,xAxisId:v,yAxisId:g}))}var k8e=(t,e,n,r,a)=>{var s=n??e;if(qt(s))return s;var o=t==="horizontal"?a:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),u=Math.min(l[0],l[1]);return s==="dataMin"?u:s==="dataMax"||c<0?c:Math.max(Math.min(l[0],l[1]),0)}return s==="dataMin"?l[0]:s==="dataMax"?l[1]:l[0]};function A8e(t){var{areaSettings:{connectNulls:e,baseValue:n,dataKey:r},stackedData:a,layout:s,chartBaseValue:o,xAxis:l,yAxis:c,displayedData:u,dataStartIndex:d,xAxisTicks:h,yAxisTicks:f,bandSize:p}=t,x=a&&a.length,v=k8e(s,o,n,l,c),g=s==="horizontal",y=!1,_=u.map((k,A)=>{var M,C,j,P;if(x)P=a[d+A];else{var E=yr(k,r);Array.isArray(E)?(P=E,y=!0):P=[v,E]}var U=(M=(C=P)===null||C===void 0?void 0:C[1])!==null&&M!==void 0?M:null,L=U==null||x&&!e&&yr(k,r)==null;if(g){var B;return{x:nN({axis:l,ticks:h,bandSize:p,entry:k,index:A}),y:L?null:(B=c.scale.map(U))!==null&&B!==void 0?B:null,value:P,payload:k}}return{x:L?null:(j=l.scale.map(U))!==null&&j!==void 0?j:null,y:nN({axis:c,ticks:f,bandSize:p,entry:k,index:A}),value:P,payload:k}}),N;return x||y?N=_.map(k=>{var A,M=Array.isArray(k.value)?k.value[0]:null;if(g){var C;return{x:k.x,y:M!=null&&k.y!=null&&(C=c.scale.map(M))!==null&&C!==void 0?C:null,payload:k.payload}}return{x:M!=null&&(A=l.scale.map(M))!==null&&A!==void 0?A:null,y:k.y,payload:k.payload}}):N=g?c.scale.map(v):l.scale.map(v),{points:_,baseLine:N??0,isRange:y}}function T8e(t){var e=ba(t,Gte),n=wi();return w.createElement(rA,{id:e.id,type:"area"},r=>w.createElement(w.Fragment,null,w.createElement(r4,{legendPayload:p8e(e)}),w.createElement(g8e,{dataKey:e.dataKey,data:e.data,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:r}),w.createElement(a4,{type:"area",id:r,data:e.data,dataKey:e.dataKey,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,stackId:yZ(e.stackId),hide:e.hide,barSize:void 0,baseValue:e.baseValue,isPanorama:n,connectNulls:e.connectNulls}),w.createElement(C8e,yf({},e,{id:r}))))}var Wte=w.memo(T8e,B0);Wte.displayName="Area";var M8e="Invariant failed";function P8e(t,e){throw new Error(M8e)}function cR(){return cR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},cR.apply(null,arguments)}function LN(t){return w.createElement(JO,cR({shapeType:"rectangle",activeClassName:"recharts-active-bar"},t))}var E8e=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(r,a)=>{if(qt(e))return e;var s=qt(r)||ha(r);return s?e(r,a):(s||P8e(),n)}},j8e=(t,e,n)=>n,D8e=(t,e)=>e,H0=ct([R0,D8e],(t,e)=>t.filter(n=>n.type==="bar").find(n=>n.id===e)),R8e=ct([H0],t=>t?.maxBarSize),F8e=(t,e,n,r)=>r,L8e=ct([ar,R0,Wc,Kc,j8e],(t,e,n,r,a)=>e.filter(s=>t==="horizontal"?s.xAxisId===n:s.yAxisId===r).filter(s=>s.isPanorama===a).filter(s=>s.hide===!1).filter(s=>s.type==="bar")),O8e=(t,e,n)=>{var r=ar(t),a=Wc(t,e),s=Kc(t,e);if(!(a==null||s==null))return r==="horizontal"?CN(t,"yAxis",s,n):CN(t,"xAxis",a,n)},I8e=(t,e)=>{var n=ar(t),r=Wc(t,e),a=Kc(t,e);if(!(r==null||a==null))return n==="horizontal"?fG(t,"xAxis",r):fG(t,"yAxis",a)},z8e=ct([L8e,xFe,I8e],U5e),U8e=(t,e,n)=>{var r,a,s=H0(t,e);if(s==null)return 0;var o=Wc(t,e),l=Kc(t,e);if(o==null||l==null)return 0;var c=ar(t),u=UJ(t),{maxBarSize:d}=s,h=ha(d)?u:d,f,p;return c==="horizontal"?(f=Uc(t,"xAxis",o,n),p=zc(t,"xAxis",o,n)):(f=Uc(t,"yAxis",l,n),p=zc(t,"yAxis",l,n)),(r=(a=Xh(f,p,!0))!==null&&a!==void 0?a:h)!==null&&r!==void 0?r:0},Kte=(t,e,n)=>{var r=ar(t),a=Wc(t,e),s=Kc(t,e);if(!(a==null||s==null)){var o,l;return r==="horizontal"?(o=Uc(t,"xAxis",a,n),l=zc(t,"xAxis",a,n)):(o=Uc(t,"yAxis",s,n),l=zc(t,"yAxis",s,n)),Xh(o,l)}},B8e=ct([z8e,UJ,bFe,BJ,U8e,Kte,R8e],q5e),H8e=(t,e,n)=>{var r=Wc(t,e);if(r!=null)return Uc(t,"xAxis",r,n)},$8e=(t,e,n)=>{var r=Kc(t,e);if(r!=null)return Uc(t,"yAxis",r,n)},V8e=(t,e,n)=>{var r=Wc(t,e);if(r!=null)return zc(t,"xAxis",r,n)},q8e=(t,e,n)=>{var r=Kc(t,e);if(r!=null)return zc(t,"yAxis",r,n)},G8e=ct([B8e,H0],W5e),W8e=ct([O8e,H0],G5e),K8e=ct([vi,ML,H8e,$8e,V8e,q8e,G8e,ar,TJ,Kte,W8e,H0,F8e],(t,e,n,r,a,s,o,l,c,u,d,h,f)=>{var{chartData:p,dataStartIndex:x,dataEndIndex:v}=c;if(!(h==null||o==null||e==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||a==null||s==null||u==null)){var{data:g}=h,y;if(g!=null&&g.length>0?y=g:y=p?.slice(x,v+1),y!=null)return S6e({layout:l,barSettings:h,pos:o,parentViewBox:e,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:s,stackedData:d,displayedData:y,offset:t,cells:f,dataStartIndex:x})}}),X8e=["index"];function uR(){return uR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},uR.apply(null,arguments)}function Y8e(t,e){if(t==null)return{};var n,r,a=Q8e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function Q8e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var Xte=w.createContext(void 0),Z8e=t=>{var e=w.useContext(Xte);if(e!=null)return e.stackId;if(t!=null)return yZ(t)},J8e=(t,e)=>"recharts-bar-stack-clip-path-".concat(t,"-").concat(e),e6e=t=>{var e=w.useContext(Xte);if(e!=null){var{stackId:n}=e;return"url(#".concat(J8e(n,t),")")}},Yte=t=>{var{index:e}=t,n=Y8e(t,X8e),r=e6e(e);return w.createElement(ga,uR({className:"recharts-bar-stack-layer",clipPath:r},n))},t6e=["onMouseEnter","onMouseLeave","onClick"],n6e=["value","background","tooltipPosition"],r6e=["id"],a6e=["onMouseEnter","onClick","onMouseLeave"];function hd(){return hd=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},hd.apply(null,arguments)}function L7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function Ts(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?L7(Object(n),!0).forEach(function(r){i6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):L7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function i6e(t,e,n){return(e=s6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function s6e(t){var e=o6e(t,"string");return typeof e=="symbol"?e:e+""}function o6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ON(t,e){if(t==null)return{};var n,r,a=l6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function l6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var c6e=t=>{var{dataKey:e,name:n,fill:r,legendType:a,hide:s}=t;return[{inactive:s,dataKey:e,type:a,color:r,value:tm(n,e),payload:t}]},u6e=w.memo(t=>{var{dataKey:e,stroke:n,strokeWidth:r,fill:a,name:s,hide:o,unit:l,tooltipType:c,id:u}=t,d={dataDefinedOnItem:void 0,getPosition:em,settings:{stroke:n,strokeWidth:r,fill:a,dataKey:e,nameKey:void 0,name:tm(s,e),hide:o,type:c,color:a,unit:l,graphicalItemId:u}};return w.createElement(nA,{tooltipEntrySettings:d})});function d6e(t){var e=Kt(Yh),{data:n,dataKey:r,background:a,allOtherBarProps:s}=t,{onMouseEnter:o,onMouseLeave:l,onClick:c}=s,u=ON(s,t6e),d=e4(o,r,s.id),h=t4(l),f=n4(c,r,s.id);if(!a||n==null)return null;var p=Uf(a);return w.createElement(vs,{zIndex:K5e(a,Da.barBackground)},n.map((x,v)=>{var{value:g,background:y,tooltipPosition:_}=x,N=ON(x,n6e);if(!y)return null;var k=d(x,v),A=h(x,v),M=f(x,v),C=Ts(Ts(Ts(Ts(Ts({option:a,isActive:String(v)===e},N),{},{fill:"#eee"},y),p),v0(u,x,v)),{},{onMouseEnter:k,onMouseLeave:A,onClick:M,dataKey:r,index:v,className:"recharts-bar-background-rectangle"});return w.createElement(LN,hd({key:"background-bar-".concat(v)},C))}))}function h6e(t){var{showLabels:e,children:n,rects:r}=t,a=r?.map(s=>{var o={x:s.x,y:s.y,width:s.width,lowerWidth:s.width,upperWidth:s.width,height:s.height};return Ts(Ts({},o),{},{value:s.value,payload:s.payload,parentViewBox:s.parentViewBox,viewBox:o,fill:s.fill})});return w.createElement(KO,{value:e?a:void 0},n)}function m6e(t){var{shape:e,activeBar:n,baseProps:r,entry:a,index:s,dataKey:o}=t,l=Kt(Yh),c=Kt(HO),u=n&&String(s)===l&&(c==null||o===c),d=u?n:e;return u?w.createElement(vs,{zIndex:Da.activeBar},w.createElement(Yte,{index:s},w.createElement(LN,hd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o})))):w.createElement(LN,hd({},r,{name:String(r.name)},a,{isActive:u,option:d,index:s,dataKey:o}))}function f6e(t){var{shape:e,baseProps:n,entry:r,index:a,dataKey:s}=t;return w.createElement(LN,hd({},n,{name:String(n.name)},r,{isActive:!1,option:e,index:a,dataKey:s}))}function p6e(t){var e,{data:n,props:r}=t,a=(e=Fs(r))!==null&&e!==void 0?e:{},{id:s}=a,o=ON(a,r6e),{shape:l,dataKey:c,activeBar:u}=r,{onMouseEnter:d,onClick:h,onMouseLeave:f}=r,p=ON(r,a6e),x=e4(d,c,s),v=t4(f),g=n4(h,c,s);return n?w.createElement(w.Fragment,null,n.map((y,_)=>w.createElement(Yte,hd({index:_,key:"rectangle-".concat(y?.x,"-").concat(y?.y,"-").concat(y?.value,"-").concat(_),className:"recharts-bar-rectangle"},v0(p,y,_),{onMouseEnter:x(y,_),onMouseLeave:v(y,_),onClick:g(y,_)}),u?w.createElement(m6e,{shape:l,activeBar:u,baseProps:o,entry:y,index:_,dataKey:c}):w.createElement(f6e,{shape:l,baseProps:o,entry:y,index:_,dataKey:c})))):null}function g6e(t){var{props:e,previousRectanglesRef:n}=t,{data:r,layout:a,isAnimationActive:s,animationBegin:o,animationDuration:l,animationEasing:c,onAnimationEnd:u,onAnimationStart:d}=e,h=n.current,f=Zb(e,"recharts-bar-"),[p,x]=w.useState(!1),v=!p,g=w.useCallback(()=>{typeof u=="function"&&u(),x(!1)},[u]),y=w.useCallback(()=>{typeof d=="function"&&d(),x(!0)},[d]);return w.createElement(h6e,{showLabels:v,rects:r},w.createElement(Qb,{animationId:f,begin:o,duration:l,isActive:s,easing:c,onAnimationEnd:g,onAnimationStart:y,key:f},_=>{var N=_===1?r:r?.map((k,A)=>{var M=h&&h[A];if(M)return Ts(Ts({},k),{},{x:br(M.x,k.x,_),y:br(M.y,k.y,_),width:br(M.width,k.width,_),height:br(M.height,k.height,_)});if(a==="horizontal"){var C=br(0,k.height,_),j=br(k.stackedBarStart,k.y,_);return Ts(Ts({},k),{},{y:j,height:C})}var P=br(0,k.width,_),E=br(k.stackedBarStart,k.x,_);return Ts(Ts({},k),{},{width:P,x:E})});return _>0&&(n.current=N??null),N==null?null:w.createElement(ga,null,w.createElement(p6e,{props:e,data:N}))}),w.createElement(Jk,{label:e.label}),e.children)}function b6e(t){var e=w.useRef(null);return w.createElement(g6e,{previousRectanglesRef:e,props:t})}var Qte=0,x6e=(t,e)=>{var n=Array.isArray(t.value)?t.value[1]:t.value;return{x:t.x,y:t.y,value:n,errorVal:yr(t,e)}};class y6e extends w.PureComponent{render(){var{hide:e,data:n,dataKey:r,className:a,xAxisId:s,yAxisId:o,needClip:l,background:c,id:u}=this.props;if(e||n==null)return null;var d=ir("recharts-bar",a),h=u;return w.createElement(ga,{className:d,id:u},l&&w.createElement("defs",null,w.createElement(o4,{clipPathId:h,xAxisId:s,yAxisId:o})),w.createElement(ga,{className:"recharts-bar-rectangles",clipPath:l?"url(#clipPath-".concat(h,")"):void 0},w.createElement(d6e,{data:n,dataKey:r,background:c,allOtherBarProps:this.props}),w.createElement(b6e,this.props)))}}var v6e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendType:"rect",minPointSize:Qte,xAxisId:0,yAxisId:0,zIndex:Da.bar};function w6e(t){var{xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d}=t,{needClip:h}=sA(e,n),f=nm(),p=wi(),x=QO(t.children,U0),v=Kt(_=>K8e(_,t.id,p,x));if(f!=="vertical"&&f!=="horizontal")return null;var g,y=v?.[0];return y==null||y.height==null||y.width==null?g=0:g=f==="vertical"?y.height/2:y.width/2,w.createElement(Pte,{xAxisId:e,yAxisId:n,data:v,dataPointFormatter:x6e,errorBarOffset:g},w.createElement(y6e,hd({},t,{layout:f,needClip:h,data:v,xAxisId:e,yAxisId:n,hide:r,legendType:a,minPointSize:s,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function S6e(t){var{layout:e,barSettings:{dataKey:n,minPointSize:r},pos:a,bandSize:s,xAxis:o,yAxis:l,xAxisTicks:c,yAxisTicks:u,stackedData:d,displayedData:h,offset:f,cells:p,parentViewBox:x,dataStartIndex:v}=t,g=e==="horizontal"?l:o,y=d?g.scale.domain():null,_=ije({numericAxis:g}),N=g.scale.map(_);return h.map((k,A)=>{var M,C,j,P,E,U;if(d){var L=d[A+v];if(L==null)return null;M=eje(L,y)}else M=yr(k,n),Array.isArray(M)||(M=[_,M]);var B=E8e(r,Qte)(M[1],A);if(e==="horizontal"){var D,$=l.scale.map(M[0]),G=l.scale.map(M[1]);if($==null||G==null)return null;C=mV({axis:o,ticks:c,bandSize:s,offset:a.offset,entry:k,index:A}),j=(D=G??$)!==null&&D!==void 0?D:void 0,P=a.size;var z=$-G;if(E=Jl(z)?0:z,U={x:C,y:f.top,width:P,height:f.height},Math.abs(B)>0&&Math.abs(E)<Math.abs(B)){var W=Ri(E||B)*(Math.abs(B)-Math.abs(E));j-=W,E+=W}}else{var X=o.scale.map(M[0]),ae=o.scale.map(M[1]);if(X==null||ae==null)return null;if(C=X,j=mV({axis:l,ticks:u,bandSize:s,offset:a.offset,entry:k,index:A}),P=ae-X,E=a.size,U={x:f.left,y:j,width:f.width,height:E},Math.abs(B)>0&&Math.abs(P)<Math.abs(B)){var H=Ri(P||B)*(Math.abs(B)-Math.abs(P));P+=H}}if(C==null||j==null||P==null||E==null)return null;var K=Ts(Ts({},k),{},{stackedBarStart:N,x:C,y:j,width:P,height:E,value:d?M:M[1],payload:k,background:U,tooltipPosition:{x:C+P/2,y:j+E/2},parentViewBox:x},p&&p[A]&&p[A].props);return K}).filter(Boolean)}function _6e(t){var e=ba(t,v6e),n=Z8e(e.stackId),r=wi();return w.createElement(rA,{id:e.id,type:"bar"},a=>w.createElement(w.Fragment,null,w.createElement(r4,{legendPayload:c6e(e)}),w.createElement(u6e,{dataKey:e.dataKey,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,unit:e.unit,tooltipType:e.tooltipType,id:a}),w.createElement(a4,{type:"bar",id:a,data:void 0,xAxisId:e.xAxisId,yAxisId:e.yAxisId,zAxisId:0,dataKey:e.dataKey,stackId:n,hide:e.hide,barSize:e.barSize,minPointSize:e.minPointSize,maxBarSize:e.maxBarSize,isPanorama:r}),w.createElement(vs,{zIndex:e.zIndex},w.createElement(w6e,hd({},e,{id:a})))))}var Zte=w.memo(_6e,B0);Zte.displayName="Bar";var N6e=["domain","range"],C6e=["domain","range"];function O7(t,e){if(t==null)return{};var n,r,a=k6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function k6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function I7(t,e){return t===e?!0:Array.isArray(t)&&t.length===2&&Array.isArray(e)&&e.length===2?t[0]===e[0]&&t[1]===e[1]:!1}function Jte(t,e){if(t===e)return!0;var{domain:n,range:r}=t,a=O7(t,N6e),{domain:s,range:o}=e,l=O7(e,C6e);return!I7(n,s)||!I7(r,o)?!1:B0(a,l)}var A6e=["type"],T6e=["dangerouslySetInnerHTML","ticks","scale"],M6e=["id","scale"];function dR(){return dR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},dR.apply(null,arguments)}function z7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function U7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?z7(Object(n),!0).forEach(function(r){P6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):z7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function P6e(t,e,n){return(e=E6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function E6e(t){var e=j6e(t,"string");return typeof e=="symbol"?e:e+""}function j6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function hR(t,e){if(t==null)return{};var n,r,a=D6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function D6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function R6e(t){var e=qr(),n=w.useRef(null),r=RL(),{type:a}=t,s=hR(t,A6e),o=Bk(r,"xAxis",a),l=w.useMemo(()=>{if(o!=null)return U7(U7({},s),{},{type:o})},[s,o]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(C5e(l)):n.current!==l&&e(k5e({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(A5e(n.current)),n.current=null)},[e]),null}var F6e=t=>{var{xAxisId:e,className:n}=t,r=Kt(ML),a=wi(),s="xAxis",o=Kt(y=>vee(y,s,e,a)),l=Kt(y=>gee(y,e)),c=Kt(y=>yLe(y,e)),u=Kt(y=>QJ(y,e));if(l==null||c==null||u==null)return null;var{dangerouslySetInnerHTML:d,ticks:h,scale:f}=t,p=hR(t,T6e),{id:x,scale:v}=u,g=hR(u,M6e);return w.createElement(s4,dR({},p,g,{x:c.x,y:c.y,width:l.width,height:l.height,className:ir("recharts-".concat(s," ").concat(s),n),viewBox:r,ticks:o,axisType:s}))},L6e={allowDataOverflow:Mi.allowDataOverflow,allowDecimals:Mi.allowDecimals,allowDuplicatedCategory:Mi.allowDuplicatedCategory,angle:Mi.angle,axisLine:Ku.axisLine,height:Mi.height,hide:!1,includeHidden:Mi.includeHidden,interval:Mi.interval,label:!1,minTickGap:Mi.minTickGap,mirror:Mi.mirror,orientation:Mi.orientation,padding:Mi.padding,reversed:Mi.reversed,scale:Mi.scale,tick:Mi.tick,tickCount:Mi.tickCount,tickLine:Ku.tickLine,tickSize:Ku.tickSize,type:Mi.type,xAxisId:0},O6e=t=>{var e=ba(t,L6e);return w.createElement(w.Fragment,null,w.createElement(R6e,{allowDataOverflow:e.allowDataOverflow,allowDecimals:e.allowDecimals,allowDuplicatedCategory:e.allowDuplicatedCategory,angle:e.angle,dataKey:e.dataKey,domain:e.domain,height:e.height,hide:e.hide,id:e.xAxisId,includeHidden:e.includeHidden,interval:e.interval,minTickGap:e.minTickGap,mirror:e.mirror,name:e.name,orientation:e.orientation,padding:e.padding,reversed:e.reversed,scale:e.scale,tick:e.tick,tickCount:e.tickCount,tickFormatter:e.tickFormatter,ticks:e.ticks,type:e.type,unit:e.unit}),w.createElement(F6e,e))},IN=w.memo(O6e,Jte);IN.displayName="XAxis";var I6e=["type"],z6e=["dangerouslySetInnerHTML","ticks","scale"],U6e=["id","scale"];function mR(){return mR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},mR.apply(null,arguments)}function B7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function H7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?B7(Object(n),!0).forEach(function(r){B6e(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):B7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function B6e(t,e,n){return(e=H6e(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function H6e(t){var e=$6e(t,"string");return typeof e=="symbol"?e:e+""}function $6e(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function fR(t,e){if(t==null)return{};var n,r,a=V6e(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function V6e(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function q6e(t){var e=qr(),n=w.useRef(null),r=RL(),{type:a}=t,s=fR(t,I6e),o=Bk(r,"yAxis",a),l=w.useMemo(()=>{if(o!=null)return H7(H7({},s),{},{type:o})},[o,s]);return w.useLayoutEffect(()=>{l!=null&&(n.current===null?e(T5e(l)):n.current!==l&&e(M5e({prev:n.current,next:l})),n.current=l)},[l,e]),w.useLayoutEffect(()=>()=>{n.current&&(e(P5e(n.current)),n.current=null)},[e]),null}function G6e(t){var{yAxisId:e,className:n,width:r,label:a}=t,s=w.useRef(null),o=w.useRef(null),l=Kt(ML),c=wi(),u=qr(),d="yAxis",h=Kt(M=>bee(M,e)),f=Kt(M=>wLe(M,e)),p=Kt(M=>vee(M,d,e,c)),x=Kt(M=>ZJ(M,e));if(w.useLayoutEffect(()=>{if(!(r!=="auto"||!h||WO(a)||w.isValidElement(a)||x==null)){var M=s.current;if(M){var C=M.getCalculatedWidth();Math.round(h.width)!==Math.round(C)&&u(E5e({id:e,width:C}))}}},[p,h,u,a,e,r,x]),h==null||f==null||x==null)return null;var{dangerouslySetInnerHTML:v,ticks:g,scale:y}=t,_=fR(t,z6e),{id:N,scale:k}=x,A=fR(x,U6e);return w.createElement(s4,mR({},_,A,{ref:s,labelRef:o,x:f.x,y:f.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:h.width,height:h.height,className:ir("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:p,axisType:d}))}var W6e={allowDataOverflow:Pi.allowDataOverflow,allowDecimals:Pi.allowDecimals,allowDuplicatedCategory:Pi.allowDuplicatedCategory,angle:Pi.angle,axisLine:Ku.axisLine,hide:!1,includeHidden:Pi.includeHidden,interval:Pi.interval,label:!1,minTickGap:Pi.minTickGap,mirror:Pi.mirror,orientation:Pi.orientation,padding:Pi.padding,reversed:Pi.reversed,scale:Pi.scale,tick:Pi.tick,tickCount:Pi.tickCount,tickLine:Ku.tickLine,tickSize:Ku.tickSize,type:Pi.type,width:Pi.width,yAxisId:0},K6e=t=>{var e=ba(t,W6e);return w.createElement(w.Fragment,null,w.createElement(q6e,{interval:e.interval,id:e.yAxisId,scale:e.scale,type:e.type,domain:e.domain,allowDataOverflow:e.allowDataOverflow,dataKey:e.dataKey,allowDuplicatedCategory:e.allowDuplicatedCategory,allowDecimals:e.allowDecimals,tickCount:e.tickCount,padding:e.padding,includeHidden:e.includeHidden,reversed:e.reversed,ticks:e.ticks,width:e.width,orientation:e.orientation,mirror:e.mirror,hide:e.hide,unit:e.unit,name:e.name,angle:e.angle,minTickGap:e.minTickGap,tick:e.tick,tickFormatter:e.tickFormatter}),w.createElement(G6e,e))},zN=w.memo(K6e,Jte);zN.displayName="YAxis";var X6e=(t,e)=>e,c4=ct([X6e,ar,KJ,Ii,Oee,xd,LOe,vi],$Oe),u4=t=>{var e=t.currentTarget.getBoundingClientRect(),n=e.width/t.currentTarget.offsetWidth,r=e.height/t.currentTarget.offsetHeight;return{chartX:Math.round((t.clientX-e.left)/n),chartY:Math.round((t.clientY-e.top)/r)}},ene=Nl("mouseClick"),tne=S0();tne.startListening({actionCreator:ene,effect:(t,e)=>{var n=t.payload,r=c4(e.getState(),u4(n));r?.activeIndex!=null&&e.dispatch(FLe({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var pR=Nl("mouseMove"),nne=S0(),w_=null;nne.startListening({actionCreator:pR,effect:(t,e)=>{var n=t.payload;w_!==null&&cancelAnimationFrame(w_);var r=u4(n);w_=requestAnimationFrame(()=>{var a=e.getState(),s=LO(a,a.tooltip.settings.shared);if(s==="axis"){var o=c4(a,r);o?.activeIndex!=null?e.dispatch(Tee({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate})):e.dispatch(Aee())}w_=null})}});function Y6e(t,e){return e instanceof HTMLElement?"HTMLElement <".concat(e.tagName,' class="').concat(e.className,'">'):e===window?"global.window":t==="children"&&typeof e=="object"&&e!==null?"<<CHILDREN>>":e}var $7={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},rne=lo({name:"rootProps",initialState:$7,reducers:{updateOptions:(t,e)=>{var n;t.accessibilityLayer=e.payload.accessibilityLayer,t.barCategoryGap=e.payload.barCategoryGap,t.barGap=(n=e.payload.barGap)!==null&&n!==void 0?n:$7.barGap,t.barSize=e.payload.barSize,t.maxBarSize=e.payload.maxBarSize,t.stackOffset=e.payload.stackOffset,t.syncId=e.payload.syncId,t.syncMethod=e.payload.syncMethod,t.className=e.payload.className,t.baseValue=e.payload.baseValue,t.reverseStackOrder=e.payload.reverseStackOrder}}}),Q6e=rne.reducer,{updateOptions:Z6e}=rne.actions,J6e=null,eHe={updatePolarOptions:(t,e)=>e.payload},ane=lo({name:"polarOptions",initialState:J6e,reducers:eHe}),{updatePolarOptions:tHe}=ane.actions,nHe=ane.reducer,ine=Nl("keyDown"),sne=Nl("focus"),d4=S0();d4.startListening({actionCreator:ine,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip,s=t.payload;if(!(s!=="ArrowRight"&&s!=="ArrowLeft"&&s!=="Enter")){var o=OO(a,ox(n),L0(n),I0(n)),l=o==null?-1:Number(o);if(!(!Number.isFinite(l)||l<0)){var c=xd(n);if(s==="Enter"){var u=AN(n,"axis","hover",String(a.index));e.dispatch(rR({active:!a.active,activeIndex:a.index,activeCoordinate:u}));return}var d=CLe(n),h=d==="left-to-right"?1:-1,f=s==="ArrowRight"?1:-1,p=l+f*h;if(!(c==null||p>=c.length||p<0)){var x=AN(n,"axis","hover",String(p));e.dispatch(rR({active:!0,activeIndex:p.toString(),activeCoordinate:x}))}}}}}});d4.startListening({actionCreator:sne,effect:(t,e)=>{var n=e.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var{keyboardInteraction:a}=n.tooltip;if(!a.active&&a.index==null){var s="0",o=AN(n,"axis","hover",String(s));e.dispatch(rR({active:!0,activeIndex:s,activeCoordinate:o}))}}}});var Zo=Nl("externalEvent"),one=S0(),zj=new Map;one.startListening({actionCreator:Zo,effect:(t,e)=>{var{handler:n,reactEvent:r}=t.payload;if(n!=null){r.persist();var a=r.type,s=zj.get(a);s!==void 0&&cancelAnimationFrame(s);var o=requestAnimationFrame(()=>{try{var l=e.getState(),c={activeCoordinate:wOe(l),activeDataKey:HO(l),activeIndex:Yh(l),activeLabel:Uee(l),activeTooltipIndex:Yh(l),isTooltipActive:SOe(l)};n(c,r)}finally{zj.delete(a)}});zj.set(a,o)}}});var rHe=ct([ix],t=>t.tooltipItemPayloads),aHe=ct([rHe,(t,e)=>e,(t,e,n)=>n],(t,e,n)=>{if(e!=null){var r=t.find(s=>s.settings.graphicalItemId===n);if(r!=null){var{getPosition:a}=r;if(a!=null)return a(e)}}}),lne=Nl("touchMove"),cne=S0();cne.startListening({actionCreator:lne,effect:(t,e)=>{var n=t.payload;if(!(n.touches==null||n.touches.length===0)){var r=e.getState(),a=LO(r,r.tooltip.settings.shared);if(a==="axis"){var s=n.touches[0];if(s==null)return;var o=c4(r,u4({clientX:s.clientX,clientY:s.clientY,currentTarget:n.currentTarget}));o?.activeIndex!=null&&e.dispatch(Tee({activeIndex:o.activeIndex,activeDataKey:void 0,activeCoordinate:o.activeCoordinate}))}else if(a==="item"){var l,c=n.touches[0];if(document.elementFromPoint==null||c==null)return;var u=document.elementFromPoint(c.clientX,c.clientY);if(!u||!u.getAttribute)return;var d=u.getAttribute(wZ),h=(l=u.getAttribute(SZ))!==null&&l!==void 0?l:void 0,f=sx(r).find(v=>v.id===h);if(d==null||f==null||h==null)return;var{dataKey:p}=f,x=aHe(r,d,h);e.dispatch(kee({activeDataKey:p,activeIndex:d,activeCoordinate:x,activeGraphicalItemId:h}))}}}});var iHe=HQ({brush:X5e,cartesianAxis:j5e,chartData:v4e,errorBars:iBe,graphicalItems:Uze,layout:XEe,legend:t2e,options:p4e,polarAxis:eze,polarOptions:nHe,referenceElements:rUe,rootProps:Q6e,tooltip:LLe,zIndex:r4e}),sHe=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return vEe({reducer:iHe,preloadedState:e,middleware:r=>{var a;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((a="es6")!==null&&a!==void 0?a:"")}).concat([tne.middleware,nne.middleware,d4.middleware,one.middleware,cne.middleware])},enhancers:r=>{var a=r;return typeof r=="function"&&(a=r()),a.concat(rZ({type:"raf"}))},devTools:{serialize:{replacer:Y6e},name:"recharts-".concat(n)}})};function une(t){var{preloadedState:e,children:n,reduxStoreName:r}=t,a=wi(),s=w.useRef(null);if(a)return n;s.current==null&&(s.current=sHe(e,r));var o=SL;return w.createElement(DBe,{context:o,store:s.current},n)}function oHe(t){var{layout:e,margin:n}=t,r=qr(),a=wi();return w.useEffect(()=>{a||(r(GEe(e)),r(qEe(n)))},[r,a,e,n]),null}var dne=w.memo(oHe,B0);function hne(t){var e=qr();return w.useEffect(()=>{e(Z6e(t))},[e,t]),null}function V7(t){var{zIndex:e,isPanorama:n}=t,r=w.useRef(null),a=qr();return w.useLayoutEffect(()=>(r.current&&a(t4e({zIndex:e,element:r.current,isPanorama:n})),()=>{a(n4e({zIndex:e,isPanorama:n}))}),[a,e,n]),w.createElement("g",{tabIndex:-1,ref:r})}function q7(t){var{children:e,isPanorama:n}=t,r=Kt(qOe);if(!r||r.length===0)return e;var a=r.filter(o=>o<0),s=r.filter(o=>o>0);return w.createElement(w.Fragment,null,a.map(o=>w.createElement(V7,{key:o,zIndex:o,isPanorama:n})),e,s.map(o=>w.createElement(V7,{key:o,zIndex:o,isPanorama:n})))}var lHe=["children"];function cHe(t,e){if(t==null)return{};var n,r,a=uHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function uHe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function UN(){return UN=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},UN.apply(null,arguments)}var dHe={width:"100%",height:"100%",display:"block"},hHe=w.forwardRef((t,e)=>{var n=jL(),r=DL(),a=IZ();if(!Oc(n)||!Oc(r))return null;var{children:s,otherAttributes:o,title:l,desc:c}=t,u,d;return o!=null&&(typeof o.tabIndex=="number"?u=o.tabIndex:u=a?0:void 0,typeof o.role=="string"?d=o.role:d=a?"application":void 0),w.createElement(dL,UN({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:dHe,ref:e}),s)}),mHe=t=>{var{children:e}=t,n=Kt(Mk);if(!n)return null;var{width:r,height:a,y:s,x:o}=n;return w.createElement(dL,{width:r,height:a,x:o,y:s},e)},G7=w.forwardRef((t,e)=>{var{children:n}=t,r=cHe(t,lHe),a=wi();return a?w.createElement(mHe,null,w.createElement(q7,{isPanorama:!0},n)):w.createElement(hHe,UN({ref:e},r),w.createElement(q7,{isPanorama:!1},n))});function fHe(){var t=qr(),[e,n]=w.useState(null),r=Kt(dje);return w.useEffect(()=>{if(e!=null){var a=e.getBoundingClientRect(),s=a.width/e.offsetWidth;Nn(s)&&s!==r&&t(KEe(s))}},[e,t,r]),n}function W7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function pHe(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?W7(Object(n),!0).forEach(function(r){gHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):W7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function gHe(t,e,n){return(e=bHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function bHe(t){var e=xHe(t,"string");return typeof e=="symbol"?e:e+""}function xHe(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zh(){return zh=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},zh.apply(null,arguments)}var yHe=()=>(M4e(),null);function BN(t){if(typeof t=="number")return t;if(typeof t=="string"){var e=parseFloat(t);if(!Number.isNaN(e))return e}return 0}var vHe=w.forwardRef((t,e)=>{var n,r,a=w.useRef(null),[s,o]=w.useState({containerWidth:BN((n=t.style)===null||n===void 0?void 0:n.width),containerHeight:BN((r=t.style)===null||r===void 0?void 0:r.height)}),l=w.useCallback((u,d)=>{o(h=>{var f=Math.round(u),p=Math.round(d);return h.containerWidth===f&&h.containerHeight===p?h:{containerWidth:f,containerHeight:p}})},[]),c=w.useCallback(u=>{if(typeof e=="function"&&e(u),u!=null&&typeof ResizeObserver<"u"){var{width:d,height:h}=u.getBoundingClientRect();l(d,h);var f=x=>{var v=x[0];if(v!=null){var{width:g,height:y}=v.contentRect;l(g,y)}},p=new ResizeObserver(f);p.observe(u),a.current=p}},[e,l]);return w.useEffect(()=>()=>{var u=a.current;u?.disconnect()},[l]),w.createElement(w.Fragment,null,w.createElement(C0,{width:s.containerWidth,height:s.containerHeight}),w.createElement("div",zh({ref:c},t)))}),wHe=w.forwardRef((t,e)=>{var{width:n,height:r}=t,[a,s]=w.useState({containerWidth:BN(n),containerHeight:BN(r)}),o=w.useCallback((c,u)=>{s(d=>{var h=Math.round(c),f=Math.round(u);return d.containerWidth===h&&d.containerHeight===f?d:{containerWidth:h,containerHeight:f}})},[]),l=w.useCallback(c=>{if(typeof e=="function"&&e(c),c!=null){var{width:u,height:d}=c.getBoundingClientRect();o(u,d)}},[e,o]);return w.createElement(w.Fragment,null,w.createElement(C0,{width:a.containerWidth,height:a.containerHeight}),w.createElement("div",zh({ref:l},t)))}),SHe=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return w.createElement(w.Fragment,null,w.createElement(C0,{width:n,height:r}),w.createElement("div",zh({ref:e},t)))}),_He=w.forwardRef((t,e)=>{var{width:n,height:r}=t;return typeof n=="string"||typeof r=="string"?w.createElement(wHe,zh({},t,{ref:e})):typeof n=="number"&&typeof r=="number"?w.createElement(SHe,zh({},t,{width:n,height:r,ref:e})):w.createElement(w.Fragment,null,w.createElement(C0,{width:n,height:r}),w.createElement("div",zh({ref:e},t)))});function NHe(t){return t?vHe:_He}var CHe=w.forwardRef((t,e)=>{var{children:n,className:r,height:a,onClick:s,onContextMenu:o,onDoubleClick:l,onMouseDown:c,onMouseEnter:u,onMouseLeave:d,onMouseMove:h,onMouseUp:f,onTouchEnd:p,onTouchMove:x,onTouchStart:v,style:g,width:y,responsive:_,dispatchTouchEvents:N=!0}=t,k=w.useRef(null),A=qr(),[M,C]=w.useState(null),[j,P]=w.useState(null),E=fHe(),U=PL(),L=U?.width>0?U.width:y,B=U?.height>0?U.height:a,D=w.useCallback(he=>{E(he),typeof e=="function"&&e(he),C(he),P(he),he!=null&&(k.current=he)},[E,e,C,P]),$=w.useCallback(he=>{A(ene(he)),A(Zo({handler:s,reactEvent:he}))},[A,s]),G=w.useCallback(he=>{A(pR(he)),A(Zo({handler:u,reactEvent:he}))},[A,u]),z=w.useCallback(he=>{A(Aee()),A(Zo({handler:d,reactEvent:he}))},[A,d]),W=w.useCallback(he=>{A(pR(he)),A(Zo({handler:h,reactEvent:he}))},[A,h]),X=w.useCallback(()=>{A(sne())},[A]),ae=w.useCallback(he=>{A(ine(he.key))},[A]),H=w.useCallback(he=>{A(Zo({handler:o,reactEvent:he}))},[A,o]),K=w.useCallback(he=>{A(Zo({handler:l,reactEvent:he}))},[A,l]),te=w.useCallback(he=>{A(Zo({handler:c,reactEvent:he}))},[A,c]),Z=w.useCallback(he=>{A(Zo({handler:f,reactEvent:he}))},[A,f]),ve=w.useCallback(he=>{A(Zo({handler:v,reactEvent:he}))},[A,v]),ce=w.useCallback(he=>{N&&A(lne(he)),A(Zo({handler:x,reactEvent:he}))},[A,N,x]),ee=w.useCallback(he=>{A(Zo({handler:p,reactEvent:he}))},[A,p]),je=NHe(_);return w.createElement(Kee.Provider,{value:M},w.createElement(aQ.Provider,{value:j},w.createElement(je,{width:L??g?.width,height:B??g?.height,className:ir("recharts-wrapper",r),style:pHe({position:"relative",cursor:"default",width:L,height:B},g),onClick:$,onContextMenu:H,onDoubleClick:K,onFocus:X,onKeyDown:ae,onMouseDown:te,onMouseEnter:G,onMouseLeave:z,onMouseMove:W,onMouseUp:Z,onTouchEnd:ee,onTouchMove:ce,onTouchStart:ve,ref:D},w.createElement(yHe,null),n)))}),kHe=["width","height","responsive","children","className","style","compact","title","desc"];function AHe(t,e){if(t==null)return{};var n,r,a=THe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function THe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var mne=w.forwardRef((t,e)=>{var{width:n,height:r,responsive:a,children:s,className:o,style:l,compact:c,title:u,desc:d}=t,h=AHe(t,kHe),f=Fs(h);return c?w.createElement(w.Fragment,null,w.createElement(C0,{width:n,height:r}),w.createElement(G7,{otherAttributes:f,title:u,desc:d},s)):w.createElement(CHe,{className:o,style:l,width:n,height:r,responsive:a??!1,onClick:t.onClick,onMouseLeave:t.onMouseLeave,onMouseEnter:t.onMouseEnter,onMouseMove:t.onMouseMove,onMouseDown:t.onMouseDown,onMouseUp:t.onMouseUp,onContextMenu:t.onContextMenu,onDoubleClick:t.onDoubleClick,onTouchStart:t.onTouchStart,onTouchMove:t.onTouchMove,onTouchEnd:t.onTouchEnd},w.createElement(G7,{otherAttributes:f,title:u,desc:d,ref:e},w.createElement(aUe,null,s)))});function gR(){return gR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},gR.apply(null,arguments)}var MHe={top:5,right:5,bottom:5,left:5},PHe={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:MHe,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},h4=w.forwardRef(function(e,n){var r,a=ba(e.categoricalChartProps,PHe),{chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,categoricalChartProps:u}=e,d={chartName:s,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return w.createElement(une,{preloadedState:{options:d},reduxStoreName:(r=u.id)!==null&&r!==void 0?r:s},w.createElement(_te,{chartData:u.data}),w.createElement(dne,{layout:a.layout,margin:a.margin}),w.createElement(hne,{baseValue:a.baseValue,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),w.createElement(mne,gR({},a,{ref:n})))}),EHe=["axis"],jHe=w.forwardRef((t,e)=>w.createElement(h4,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:EHe,tooltipPayloadSearcher:Qk,categoricalChartProps:t,ref:e})),DHe=["axis","item"],RHe=w.forwardRef((t,e)=>w.createElement(h4,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:DHe,tooltipPayloadSearcher:Qk,categoricalChartProps:t,ref:e}));function FHe(t){var e=qr();return w.useEffect(()=>{e(tHe(t))},[e,t]),null}var LHe=["layout"];function bR(){return bR=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},bR.apply(null,arguments)}function OHe(t,e){if(t==null)return{};var n,r,a=IHe(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(r=0;r<s.length;r++)n=s[r],e.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(a[n]=t[n])}return a}function IHe(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var zHe={top:5,right:5,bottom:5,left:5},fne={accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:zHe,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},UHe=w.forwardRef(function(e,n){var r,a=ba(e.categoricalChartProps,fne),{layout:s}=a,o=OHe(a,LHe),{chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:u,tooltipPayloadSearcher:d}=e,h={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:u,tooltipPayloadSearcher:d,eventEmitter:void 0};return w.createElement(une,{preloadedState:{options:h},reduxStoreName:(r=a.id)!==null&&r!==void 0?r:l},w.createElement(_te,{chartData:a.data}),w.createElement(dne,{layout:s,margin:a.margin}),w.createElement(hne,{baseValue:void 0,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),w.createElement(FHe,{cx:a.cx,cy:a.cy,startAngle:a.startAngle,endAngle:a.endAngle,innerRadius:a.innerRadius,outerRadius:a.outerRadius}),w.createElement(mne,bR({},o,{ref:n})))});function K7(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),n.push.apply(n,r)}return n}function X7(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?K7(Object(n),!0).forEach(function(r){BHe(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):K7(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function BHe(t,e,n){return(e=HHe(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function HHe(t){var e=$He(t,"string");return typeof e=="symbol"?e:e+""}function $He(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var VHe=["item"],qHe=X7(X7({},fne),{},{layout:"centric",startAngle:0,endAngle:360}),GHe=w.forwardRef((t,e)=>{var n=ba(t,qHe);return w.createElement(UHe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:VHe,tooltipPayloadSearcher:Qk,categoricalChartProps:n,ref:e})}),WHe=["axis"],KHe=w.forwardRef((t,e)=>w.createElement(h4,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:WHe,tooltipPayloadSearcher:Qk,categoricalChartProps:t,ref:e}));const Y7=[{value:"6h",label:"6h",hours:6},{value:"24h",label:"24h",hours:24},{value:"48h",label:"48h",hours:48},{value:"7d",label:"7d",hours:168}];function XHe({isOpen:t,onClose:e,printerId:n,printerName:r,amsId:a,amsLabel:s,initialMode:o="humidity",thresholds:l}){const{t:c}=Ot(),{mode:u}=tp(),[d,h]=w.useState("24h"),[f,p]=w.useState(o),x=u==="dark",{data:v}=Je({queryKey:["settings"],queryFn:ne.getSettings}),g=v?.time_format||"system";w.useEffect(()=>{if(!t)return;const Z=ve=>{ve.key==="Escape"&&e()};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[t,e]);const y=Y7.find(Z=>Z.value===d)?.hours||24,{data:_,isLoading:N,error:k}=Je({queryKey:["ams-history",n,a,y],queryFn:()=>ne.getAMSHistory(n,a,y),enabled:t,refetchInterval:6e4});if(!t)return null;const A=_?.data.map(Z=>{const ve=hi(Z.recorded_at)||new Date,ce={hour:"2-digit",minute:"2-digit",...y>24?{day:"numeric",month:"short"}:{}};return{time:ve.getTime(),humidity:Z.humidity,temperature:Z.temperature,timeLabel:ve.toLocaleTimeString([],Vy(ce,g))}})||[],M=l?.humidityGood||40,C=l?.humidityFair||60,j=l?.tempGood||30,P=l?.tempFair||35,E=A[A.length-1],U=E?.humidity,L=E?.temperature,B=Z=>{const ve=Z.filter(_e=>_e!=null);if(ve.length<4)return"stable";const ce=ve.slice(0,Math.floor(ve.length/4)),ee=ve.slice(-Math.floor(ve.length/4)),je=ce.reduce((_e,ie)=>_e+ie,0)/ce.length,oe=ee.reduce((_e,ie)=>_e+ie,0)/ee.length-je;return Math.abs(oe)<2?"stable":oe>0?"up":"down"},D=B(A.map(Z=>Z.humidity)),$=B(A.map(Z=>Z.temperature)),G=({trend:Z})=>Z==="up"?i.jsx(c3,{className:"w-4 h-4 text-red-400"}):Z==="down"?i.jsx(MF,{className:"w-4 h-4 text-green-400"}):i.jsx(_1,{className:"w-4 h-4 text-gray-400 dark:text-bambu-gray"}),z=Z=>Z==null?"#9ca3af":Z<=M?"#22a352":Z<=C?"#d4a017":"#c62828",W=Z=>Z==null?"#9ca3af":Z<=j?"#22a352":Z<=P?"#d4a017":"#c62828",X=x?"#2d2d2d":"#ffffff",ae=x?"#1d1d1d":"#f3f4f6",H=x?"#3d3d3d":"#e5e7eb",K=x?"#ffffff":"#111827",te=x?"#9ca3af":"#4b5563";return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsxs("div",{className:"rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl",style:{backgroundColor:X},onClick:Z=>Z.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",style:{borderColor:H},children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold",style:{color:K},children:[s," ",c("common.history","History")]}),i.jsx("p",{className:"text-sm",style:{color:te},children:r})]}),i.jsx("button",{onClick:e,className:"p-2 rounded-lg transition-colors",style:{color:te},children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]",children:[i.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3",children:[i.jsxs("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:ae},children:[i.jsxs("button",{onClick:()=>p("humidity"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${f==="humidity"?"bg-blue-600 text-white":""}`,style:f!=="humidity"?{color:te}:void 0,children:[i.jsx(CF,{className:"w-4 h-4"}),c("common.humidity","Humidity")]}),i.jsxs("button",{onClick:()=>p("temperature"),className:`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${f==="temperature"?"bg-orange-600 text-white":""}`,style:f!=="temperature"?{color:te}:void 0,children:[i.jsx(JC,{className:"w-4 h-4"}),c("common.temperature","Temperature")]})]}),i.jsx("div",{className:"inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit",style:{backgroundColor:ae},children:Y7.map(Z=>i.jsx("button",{onClick:()=>h(Z.value),className:`px-3 py-1 text-sm rounded-md transition-colors ${d===Z.value?"bg-bambu-green text-white":""}`,style:d!==Z.value?{color:te}:void 0,children:Z.label},Z.value))})]}),i.jsx("div",{className:"grid grid-cols-4 gap-4 max-[550px]:grid-cols-2",children:f==="humidity"?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:z(U)},children:U!=null?`${U}%`:"—"}),i.jsx(G,{trend:D})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:K},children:_?.avg_humidity!=null?`${_.avg_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-green-500",children:_?.min_humidity!=null?`${_.min_humidity}%`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_humidity!=null?`${_.max_humidity}%`:"—"})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-2",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.current","Current")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-2xl font-bold",style:{color:W(L)},children:L!=null?`${L}°C`:"—"}),i.jsx(G,{trend:$})]})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-4",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.average","Average")}),i.jsx("p",{className:"text-2xl font-bold",style:{color:K},children:_?.avg_temperature!=null?`${_.avg_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-1",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.min","Min")}),i.jsx("p",{className:"text-2xl font-bold text-blue-500",children:_?.min_temperature!=null?`${_.min_temperature}°C`:"—"})]}),i.jsxs("div",{className:"rounded-lg p-4 max-[550px]:order-3",style:{backgroundColor:ae},children:[i.jsx("p",{className:"text-xs",style:{color:te},children:c("common.max","Max")}),i.jsx("p",{className:"text-2xl font-bold text-red-500",children:_?.max_temperature!=null?`${_.max_temperature}°C`:"—"})]})]})}),i.jsx("div",{className:"rounded-lg p-4",style:{backgroundColor:ae},children:N?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:te},children:c("common.loading","Loading...")}):k?i.jsx("div",{className:"h-[300px] flex items-center justify-center text-red-500",children:c("common.error","Error loading data")}):A.length===0?i.jsx("div",{className:"h-[300px] flex items-center justify-center",style:{color:te},children:c("common.noData","No data available for this time range")}):i.jsx(n1,{width:"100%",height:300,children:i.jsxs(jHe,{data:A,children:[i.jsx(RN,{strokeDasharray:"3 3",stroke:x?"#3d3d3d":"#e5e7eb"}),i.jsx(IN,{dataKey:"time",type:"number",domain:["dataMin","dataMax"],tickFormatter:Z=>{const ve=new Date(Z);return y>24?ve.toLocaleDateString([],{day:"numeric",month:"short"}):ve.toLocaleTimeString([],Vy({hour:"2-digit",minute:"2-digit"},g))},stroke:x?"#9ca3af":"#6b7280",tick:{fontSize:12}}),i.jsx(zN,{stroke:x?"#9ca3af":"#6b7280",tick:{fontSize:12},domain:f==="humidity"?[0,100]:["auto","auto"],tickFormatter:Z=>f==="humidity"?`${Z}%`:`${Z}°C`}),i.jsx(a1,{contentStyle:{backgroundColor:x?"#2d2d2d":"#ffffff",border:`1px solid ${x?"#3d3d3d":"#e5e7eb"}`,borderRadius:"8px",color:x?"#fff":"#000"},labelFormatter:Z=>new Date(Z).toLocaleString(void 0,Vy({year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"},g)),formatter:Z=>[f==="humidity"?`${Z??0}%`:`${Z??0}°C`,f==="humidity"?"Humidity":"Temperature"]}),i.jsx(OL,{}),f==="humidity"?i.jsxs(i.Fragment,{children:[i.jsx(Dy,{y:M,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Dy,{y:C,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}):i.jsxs(i.Fragment,{children:[i.jsx(Dy,{y:j,stroke:"#22a352",strokeDasharray:"5 5",label:{value:"Good",fill:"#22a352",fontSize:10}}),i.jsx(Dy,{y:P,stroke:"#d4a017",strokeDasharray:"5 5",label:{value:"Fair",fill:"#d4a017",fontSize:10}})]}),i.jsx(Ite,{type:"monotone",dataKey:f,name:f==="humidity"?"Humidity":"Temperature",stroke:f==="humidity"?"#3b82f6":"#f97316",strokeWidth:2,dot:!1,activeDot:{r:4}})]})})}),i.jsx("div",{className:"text-xs text-center",style:{color:te},children:c("amsHistory.recordingInfo","Data is recorded every 5 minutes while the printer is connected")})]})]})})}function Uj({data:t,children:e,disabled:n,className:r="",spoolman:a,inventory:s,configureSlot:o}){const{t:l}=Ot(),[c,u]=w.useState(!1),[d,h]=w.useState("top"),[f,p]=w.useState(!1),x=w.useRef(null),v=w.useRef(null),g=w.useRef(null),y=()=>{const P=t.trayUuid;P&&(navigator.clipboard&&window.isSecureContext?navigator.clipboard.writeText(P).then(()=>{p(!0),setTimeout(()=>p(!1),2e3)}).catch(()=>{_(P)}):_(P))},_=P=>{const E=document.createElement("textarea");E.value=P,E.style.position="fixed",E.style.opacity="0",document.body.appendChild(E),E.select();try{document.execCommand("copy"),p(!0),setTimeout(()=>p(!1),2e3)}catch{console.error("Failed to copy to clipboard")}document.body.removeChild(E)};w.useEffect(()=>{if(c&&x.current&&v.current){const P=x.current.getBoundingClientRect(),E=v.current.offsetHeight,L=P.top-56,B=window.innerHeight-P.bottom;L<E+12&&B>L?h("bottom"):h("top")}},[c]);const N=()=>{n||(g.current&&clearTimeout(g.current),g.current=setTimeout(()=>u(!0),80))},k=()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>u(!1),100)};w.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const A=P=>P<=15?"#ef4444":P<=30?"#f97316":P<=50?"#eab308":"#22c55e",M=P=>{if(!P)return!1;const E=P.replace("#",""),U=parseInt(E.slice(0,2),16),L=parseInt(E.slice(2,4),16),B=parseInt(E.slice(4,6),16);return(.299*U+.587*L+.114*B)/255>.6},C=t.colorHex?`#${t.colorHex.replace("#","")}`:null,j=s?.assignedSpool?.remainingWeightGrams??null;return i.jsxs("div",{ref:x,className:`relative ${r}`,onMouseEnter:N,onMouseLeave:k,children:[e,c&&i.jsxs("div",{ref:v,className:`
  8103. absolute left-1/2 -translate-x-1/2 z-50
  8104. ${d==="top"?"bottom-full mb-2":"top-full mt-2"}
  8105. animate-in fade-in-0 zoom-in-95 duration-150
  8106. `,style:{maxWidth:"calc(100vw - 24px)"},children:[i.jsxs("div",{className:`
  8107. w-52 bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8108. rounded-lg shadow-xl overflow-hidden
  8109. backdrop-blur-sm
  8110. `,children:[i.jsxs("div",{className:"h-12 relative overflow-hidden",style:{backgroundColor:C||"#3d3d3d"},children:[i.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-white/10 to-transparent"}),i.jsx("div",{className:`
  8111. absolute inset-0 flex items-center justify-center
  8112. font-semibold text-sm tracking-wide
  8113. ${M(C)?"text-black/80":"text-white/90"}
  8114. `,children:t.colorName}),i.jsx("div",{className:`
  8115. absolute top-1.5 right-1.5 px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wider
  8116. ${t.vendor==="Bambu Lab"?"bg-black/60 text-white":"bg-black/50 text-white/90"}
  8117. `,children:t.vendor==="Bambu Lab"?"BBL":"GEN"})]}),i.jsxs("div",{className:"p-3 space-y-2.5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.profile")}),i.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[120px]",children:t.profile})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("ams.kFactor")}),i.jsx("span",{className:"text-xs text-bambu-green font-mono font-bold",children:t.kFactor})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium flex items-center gap-1",children:[i.jsx(CF,{className:"w-3 h-3"}),l("ams.fill")]}),i.jsxs("span",{className:"text-xs text-white font-semibold flex items-center gap-1",children:[i.jsx("span",{children:t.fillLevel!==null?`${t.fillLevel}%`:"—"}),j!==null&&t.fillLevel!==null&&i.jsxs("span",{className:"text-[9px] text-bambu-gray font-normal",children:["• ",j,"g"]}),t.fillSource==="spoolman"&&t.fillLevel!==null&&i.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("spoolman.fillSourceLabel")}),t.fillSource==="inventory"&&t.fillLevel!==null&&i.jsx("span",{className:"text-[9px] text-bambu-gray font-normal",children:l("inventory.fillSourceLabel")})]})]}),i.jsx("div",{className:"h-1.5 bg-black/40 rounded-full overflow-hidden",children:t.fillLevel!==null?i.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${t.fillLevel}%`,backgroundColor:A(t.fillLevel)}}):i.jsx("div",{className:"h-full w-full bg-bambu-gray/30 rounded-full"})})]}),a?.enabled&&t.trayUuid&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("spoolman.spoolId")}),i.jsxs("button",{onClick:P=>{P.stopPropagation(),y()},className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-white transition-colors",title:"Copy spool UUID",children:[i.jsxs("span",{className:"font-mono text-[10px] truncate max-w-[80px]",children:[t.trayUuid.slice(0,8),"..."]}),f?i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}):i.jsx(Yl,{className:"w-3 h-3"})]})]}),a.linkedSpoolId&&a.spoolmanUrl&&i.jsxs("a",{href:`${a.spoolmanUrl.replace(/\/$/,"")}/spool/show/${a.linkedSpoolId}`,target:"_blank",rel:"noopener noreferrer",onClick:P=>P.stopPropagation(),className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green",title:l("spoolman.openInSpoolman"),children:[i.jsx(Xr,{className:"w-3.5 h-3.5"}),l("spoolman.openInSpoolman")]}),!a.linkedSpoolId&&a.onLinkSpool&&i.jsxs("button",{onClick:P=>{P.stopPropagation(),a.hasUnlinkedSpools!==!1&&a.onLinkSpool?.(t.trayUuid)},disabled:a.hasUnlinkedSpools===!1,className:`w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors ${a.hasUnlinkedSpools===!1?"bg-bambu-gray/10 text-bambu-gray cursor-not-allowed":"bg-bambu-green/20 hover:bg-bambu-green/30 text-bambu-green"}`,title:a.hasUnlinkedSpools===!1?l("spoolman.noUnlinkedSpools"):l("spoolman.linkToSpoolman"),children:[i.jsx(jh,{className:"w-3.5 h-3.5"}),l("spoolman.linkToSpoolman")]})]}),s&&t.vendor!=="Bambu Lab"&&i.jsx("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary space-y-2",children:s.assignedSpool?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(ni,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:l("inventory.assigned")})]}),i.jsxs("p",{className:"text-xs text-white truncate",children:[s.assignedSpool.brand?`${s.assignedSpool.brand} `:"",s.assignedSpool.material,s.assignedSpool.color_name?` - ${s.assignedSpool.color_name}`:""]}),s.onUnassignSpool&&i.jsxs("button",{onClick:P=>{P.stopPropagation(),s.onUnassignSpool?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-red-500/20 hover:bg-red-500/30 text-red-400",children:[i.jsx(ek,{className:"w-3.5 h-3.5"}),l("inventory.unassignSpool")]})]}):s.onAssignSpool?i.jsxs("button",{onClick:P=>{P.stopPropagation(),s.onAssignSpool?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",children:[i.jsx(ni,{className:"w-3.5 h-3.5"}),l("inventory.assignSpool")]}):null}),o?.enabled&&i.jsx("div",{className:`${a?.enabled&&t.trayUuid?"":"pt-2 mt-2 border-t border-bambu-dark-tertiary"}`,children:i.jsxs("button",{onClick:P=>{P.stopPropagation(),o.onConfigure?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",title:l("ams.configureSlot"),children:[i.jsx(ed,{className:"w-3.5 h-3.5"}),l("ams.configure")]})})]})]}),i.jsx("div",{className:`
  8118. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8119. border-l-[6px] border-l-transparent
  8120. border-r-[6px] border-r-transparent
  8121. ${d==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8122. `})]})]})}function Bj({children:t,className:e="",configureSlot:n}){const{t:r}=Ot(),[a,s]=w.useState(!1),o=w.useRef(null),l=()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>s(!0),80)},c=()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>s(!1),100)};return w.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),i.jsxs("div",{className:`relative ${e}`,onMouseEnter:l,onMouseLeave:c,children:[t,a&&i.jsxs("div",{className:`
  8123. absolute left-1/2 -translate-x-1/2 bottom-full mb-2 z-50
  8124. animate-in fade-in-0 zoom-in-95 duration-150
  8125. `,children:[i.jsxs("div",{className:`
  8126. bg-bambu-dark-secondary border border-bambu-dark-tertiary
  8127. rounded-md shadow-lg overflow-hidden
  8128. `,children:[i.jsx("div",{className:"px-3 py-1.5 text-xs text-bambu-gray whitespace-nowrap",children:r("ams.emptySlot")}),n?.enabled&&i.jsx("div",{className:"px-2 pb-2",children:i.jsxs("button",{onClick:u=>{u.stopPropagation(),n.onConfigure?.()},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs font-medium rounded transition-colors bg-bambu-blue/20 hover:bg-bambu-blue/30 text-bambu-blue",title:r("ams.configureSlot"),children:[i.jsx(ed,{className:"w-3.5 h-3.5"}),r("ams.configure")]})})]}),i.jsx("div",{className:`
  8129. absolute left-1/2 -translate-x-1/2 top-full w-0 h-0
  8130. border-l-[5px] border-l-transparent
  8131. border-r-[5px] border-r-transparent
  8132. border-t-[5px] border-t-bambu-dark-tertiary
  8133. `})]})]})}function YHe({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:a,amsId:s,trayId:o}){const{t:l}=Ot(),c=en(),{showToast:u}=an(),[d,h]=w.useState(""),{data:f,isLoading:p}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!1),enabled:t}),x=w.useMemo(()=>f?f.filter(g=>{if(g.tag_uid||g.tray_uuid)return!1;if(!d)return!0;const y=d.toLowerCase();return g.material.toLowerCase().includes(y)||g.brand&&g.brand.toLowerCase().includes(y)||g.color_name&&g.color_name.toLowerCase().includes(y)}):[],[f,d]),v=st({mutationFn:g=>ne.linkTagToSpool(g,{tag_uid:n||void 0,tray_uuid:r||void 0,tag_type:r?"bambulab":"generic",data_origin:"nfc_link"}),onSuccess:()=>{c.invalidateQueries({queryKey:["inventory-spools"]}),c.invalidateQueries({queryKey:["inventory-assignments"]}),u(l("inventory.tagLinked"),"success"),e()},onError:g=>{u(g.message||l("inventory.tagLinkFailed"),"error")}});return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(qb,{className:"w-5 h-5 text-bambu-green"}),l("inventory.linkToSpool")]}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",a]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-white/10",children:[i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:d,onChange:g=>h(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(n||r)&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:n||r,children:["Tag: ",n||r]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:p?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):x.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):x.map(g=>i.jsxs("button",{onClick:()=>v.mutate(g.id),disabled:v.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[i.jsx("span",{className:"w-6 h-6 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:g.rgba?`#${g.rgba.substring(0,6)}`:"#808080"}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"text-sm text-white font-medium truncate",children:[g.brand?`${g.brand} `:"",g.material,g.subtype?` ${g.subtype}`:""]}),i.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.color_name||"No color"," · #",g.id]})]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(g.label_weight-g.weight_used),"g"]})]},g.id))}),i.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:i.jsx(Ce,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function QHe({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:a,trayInfo:s}){const{t:o}=Ot(),l=en(),{showToast:c}=an(),[u,d]=w.useState(null),[h,f]=w.useState(""),{data:p,isLoading:x}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(),enabled:t}),{data:v}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:t}),g=st({mutationFn:M=>ne.assignSpool({spool_id:M,printer_id:n,ams_id:r,tray_id:a}),onSuccess:M=>{l.setQueryData(["spool-assignments"],C=>{const j=(C||[]).filter(P=>!(P.printer_id===n&&P.ams_id===r&&P.tray_id===a));return j.push(M),j}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),e()},onError:M=>{c(`${o("inventory.assignFailed")}: ${M.message}`,"error")}});if(!t)return null;const y=new Set((v||[]).filter(M=>!(M.printer_id===n&&M.ams_id===r&&M.tray_id===a)).map(M=>M.spool_id)),_=r===254||r===255,N=p?.filter(M=>!y.has(M.id)&&(_||!M.tag_uid&&!M.tray_uuid)),k=N?.filter(M=>{if(!h)return!0;const C=h.toLowerCase();return M.material.toLowerCase().includes(C)||(M.brand?.toLowerCase().includes(C)??!1)||(M.color_name?.toLowerCase().includes(C)??!1)||(M.subtype?.toLowerCase().includes(C)??!1)}),A=()=>{u&&g.mutate(u)};return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ni,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[s&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${s.color}`}}),i.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),i.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:h,onChange:M=>f(M.target.value),placeholder:o("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsx("div",{children:x?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):k&&k.length>0?i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:k.map(M=>i.jsx("button",{onClick:()=>d(M.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${u===M.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[M.rgba&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${M.rgba.substring(0,6)}`}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("p",{className:"text-white font-medium truncate",children:[M.brand?`${M.brand} `:"",M.material,M.subtype?` ${M.subtype}`:""]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[M.color_name||"",M.label_weight?` - ${M.label_weight}g`:"",M.label_weight?` (${Math.max(0,Math.round(M.label_weight-M.weight_used))}g ${o("ams.remainingUnit")})`:""]})]}),u===M.id&&i.jsx(aa,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},M.id))}):N&&N.length===0?i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noManualSpools")})}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:o("common.cancel")}),i.jsx(Ce,{onClick:A,disabled:!u||g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):i.jsxs(i.Fragment,{children:[i.jsx(ni,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]}),g.isError&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:g.error.message})]})]})}function ZHe(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const a=String.fromCharCode(65+n);return r?`HT-${a}`:`AMS-${a}`}function S_(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const JHe=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function Q7(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const a of JHe){const s=new RegExp(`\\b${a}\\b`,"i");if(s.test(n)){const o=e.split(s),l=o[0]?.trim()||"",c=o[1]?.trim()||"";return{material:a,brand:l,variant:c}}}const r=e.split(/\s+/);return r.length>=2?{material:r[1],brand:r[0],variant:r.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function e$e(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const t$e={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},n$e=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],r$e=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function a$e(t){const e=t.toLowerCase().trim();return t$e[e]||null}function i$e(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function s$e({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o}){const{t:l}=Ot(),[c,u]=w.useState(""),[d,h]=w.useState(null),[f,p]=w.useState(""),[x,v]=w.useState(""),[g,y]=w.useState(""),[_,N]=w.useState(!1),[k,A]=w.useState(!1),{data:M,isLoading:C,isError:j}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:t,retry:!1}),{data:P,isLoading:E}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets(),enabled:t}),{data:U,isLoading:L}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:B,isLoading:D}=Je({queryKey:["kprofiles",n,a],queryFn:()=>ne.getKProfiles(n,a),enabled:t&&!!n}),{data:$}=Je({queryKey:["colorCatalog"],queryFn:()=>ne.getColorCatalog(),enabled:t,staleTime:1/0}),G=st({mutationFn:async()=>{if(!c)throw new Error("No filament preset selected");const ee=c.startsWith("local_"),je=c.startsWith("builtin_"),he=ee?parseInt(c.replace("local_",""),10):null,oe=je?c.replace("builtin_",""):null,_e=ee?P?.filament.find(le=>le.id===he):null,ie=je?U?.find(le=>le.filament_id===oe):null,ze=!ee&&!je?M?.filament.find(le=>le.setting_id===c):null;if(!ee&&!je&&!ze)throw new Error("Selected preset not found");if(ee&&!_e)throw new Error("Selected local preset not found");if(je&&!ie)throw new Error("Selected builtin preset not found");const V=ee?_e.name:je?ie.name:ze.name,Y=Q7(V),me=d?.slot_id??-1,Q=f||r.trayColor?.slice(0,6)||"FFFFFF",se=V.replace(/@.+$/,"").trim();let de,Le;if(ee){const le=(_e?.filament_type||Y.material||"").toUpperCase(),Be={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};de=Be[le]||Be[le.replace(/[-\s]?CF$/,"")]||Be[le.replace(/\+$/,"")]||Be[le.split(/[-\s]/)[0]]||"",Le=""}else if(je)de=oe,Le="";else if(de=S_(c),Le=c,!c.startsWith("GFS"))try{const le=await ne.getCloudSettingDetail(c);le.filament_id?de=le.filament_id:le.base_id&&(de=S_(le.base_id),console.log(`Derived tray_info_idx from base_id: ${le.base_id} -> ${de}`))}catch(le){console.warn("Failed to fetch preset detail for filament_id:",le)}let Ne=ee&&_e?.nozzle_temp_min?_e.nozzle_temp_min:190,be=ee&&_e?.nozzle_temp_max?_e.nozzle_temp_max:230;if(!ee||je||!_e?.nozzle_temp_min&&!_e?.nozzle_temp_max){const le=(ee&&_e?.filament_type||Y.material).toUpperCase();le.includes("PLA")?(Ne=190,be=230):le.includes("PETG")?(Ne=220,be=260):le.includes("ABS")||le.includes("ASA")?(Ne=240,be=280):le.includes("TPU")?(Ne=200,be=240):le==="PCTG"?(Ne=220,be=260):le.includes("PC")?(Ne=260,be=300):(le.includes("PA")||le.includes("NYLON"))&&(Ne=250,be=290)}const O=d?.k_value?parseFloat(d.k_value):0,R=ee?_e?.filament_type||Y.material||"PLA":Y.material||"PLA",q=await ne.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:de,tray_type:R,tray_sub_brands:se,tray_color:Q+"FF",nozzle_temp_min:Ne,nozzle_temp_max:be,cali_idx:me,nozzle_diameter:a,setting_id:Le,kprofile_filament_id:d?.filament_id,kprofile_setting_id:d?.setting_id||void 0,k_value:O}),J=ee?`local_${he}`:je?`builtin_${oe}`:c,fe=ee?"local":je?"builtin":"cloud";try{await ne.saveSlotPreset(n,r.amsId,r.trayId,J,se,fe)}catch(le){console.warn("Failed to save slot preset mapping:",le)}return q},onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),z=st({mutationFn:async()=>ne.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),W=w.useMemo(()=>{const ee=g.toLowerCase(),je=[],he=new Set,oe=r.savedPresetId,_e=r.trayInfoIdx;if(M?.filament)for(const ie of M.filament){he.add(ie.setting_id);const ze=oe===ie.setting_id||_e&&(ie.setting_id===_e||S_(ie.setting_id)===_e);if(!(!ze&&ee&&!ie.name.toLowerCase().includes(ee))){if(!ze&&s){const V=i$e(ie.name);if(V&&V.toUpperCase()!==s.toUpperCase())continue}je.push({id:ie.setting_id,name:ie.name,source:"cloud",isUser:e$e(ie.setting_id)})}}if(P?.filament)for(const ie of P.filament){const ze=`local_${ie.id}`,V=oe===ze;if(!(!V&&ee&&!ie.name.toLowerCase().includes(ee))){if(!V&&s&&ie.compatible_printers){const Y=ie.compatible_printers.split(";").map(me=>{const Q=me.trim(),se=Q.match(/^BBL\s+(.+)/i);return se?se[1].trim().toUpperCase():Q.toUpperCase()}).filter(Boolean);if(Y.length>0&&!Y.includes(s.toUpperCase()))continue}je.push({id:ze,name:ie.name,source:"local",isUser:!1})}}if(U)for(const ie of U){if(he.has(ie.filament_id))continue;const ze=ie.filament_id.startsWith("GF")?"GFS"+ie.filament_id.slice(2):ie.filament_id;he.has(ze)||(!ee||ie.name.toLowerCase().includes(ee))&&je.push({id:`builtin_${ie.filament_id}`,name:ie.name,source:"builtin",isUser:!1})}return je.sort((ie,ze)=>{const V={cloud:0,local:1,builtin:2};return ie.source!==ze.source?V[ie.source]-V[ze.source]:ie.isUser&&!ze.isUser?-1:!ie.isUser&&ze.isUser?1:ie.name.localeCompare(ze.name)})},[M?.filament,P?.filament,U,g,s,r.savedPresetId,r.trayInfoIdx]),X=w.useMemo(()=>{if(!c)return null;let ee=null;if(c.startsWith("local_")){const oe=parseInt(c.replace("local_",""),10);ee=P?.filament.find(ie=>ie.id===oe)?.name||null}else if(c.startsWith("builtin_")){const oe=c.replace("builtin_","");ee=U?.find(ie=>ie.filament_id===oe)?.name||null}else M?.filament&&(ee=M.filament.find(_e=>_e.setting_id===c)?.name||null);if(!ee)return null;let je=ee.replace(/@.+$/,"").trim();je.startsWith("# ")&&(je=je.slice(2).trim());const he=Q7(je);return{fullName:je,material:he.material,brand:he.brand}},[c,M?.filament,P?.filament,U]),ae=X?.fullName||"",H=w.useMemo(()=>{if(!$||!X)return[];const{fullName:ee,brand:je}=X,he=ee.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return $.filter(oe=>{const _e=(oe.material||"").toUpperCase(),ie=oe.manufacturer.toUpperCase();if(!(_e===he.toUpperCase()||_e.includes(he.toUpperCase())||he.toUpperCase().includes(_e)))return!1;if(je){const V=je.toUpperCase();if(!ie.includes(V)&&!V.includes(ie))return!1}return!0})},[$,X]),K=w.useMemo(()=>{if(!B?.profiles||!X)return[];const{fullName:ee,material:je,brand:he}=X,oe=ee.toUpperCase(),_e=je.toUpperCase(),ie=he.toUpperCase();if(!_e||_e.length<2)return[];const ze=B.profiles.filter(Y=>{const me=Y.name.toUpperCase();if(ie)return!(!me.includes(ie)||!me.includes(_e));if(me.includes(oe)||me.includes(_e))return!0;const se={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[_e]||[];for(const de of se)if(me.includes(de))return!0;return!1}),V=new Map;for(const Y of ze){const me=`${Y.name}|${Y.k_value}`,Q=V.get(me);Q?r.extruderId!==void 0&&Y.extruder_id===r.extruderId&&Q.extruder_id!==r.extruderId&&V.set(me,Y):V.set(me,Y)}return Array.from(V.values())},[B?.profiles,X,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&M?.filament){let ee=M.filament.find(je=>je.setting_id===r.trayInfoIdx);ee||(ee=M.filament.find(je=>S_(je.setting_id)===r.trayInfoIdx)),ee&&u(ee.setting_id)}if(r.trayColor){const ee=r.trayColor.slice(0,6);ee&&p(ee)}}else u(""),h(null),p(""),v(""),y(""),N(!1)},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,M?.filament]),w.useEffect(()=>{if(K.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const ee=K.find(je=>je.slot_id===r.caliIdx);if(ee){h(ee);return}}h(K[0])}else h(null)},[c,K,r.caliIdx]);const te=w.useCallback(ee=>{ee.key==="Escape"&&e()},[e]);if(w.useEffect(()=>{if(t)return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[t,te]),!t)return null;const Z=C&&!j||E||L||D,ve=c&&!G.isPending,ce=f||r.trayColor?.slice(0,6)||"FFFFFF";return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-5 h-5 text-bambu-blue"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.title")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4 max-h-[60vh] overflow-y-auto",children:[_&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx(ub,{className:"w-16 h-16 text-bambu-green mx-auto"}),i.jsx("p",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.slotConfigured")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:l("configureAmsSlot.settingsSentToPrinter")})]})}),i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:l("configureAmsSlot.configuringSlot")}),i.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:l("configureAmsSlot.slotLabel",{ams:ZHe(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),Z?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.searchPresets"),value:g,onChange:ee=>y(ee.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:W.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:M?.filament?.length===0&&!P?.filament?.length?l("configureAmsSlot.noPresetsAvailable"):l("configureAmsSlot.noMatchingPresets")}):W.map(ee=>i.jsx("button",{ref:c===ee.id?je=>{je?.scrollIntoView({block:"nearest"})}:void 0,onClick:()=>u(ee.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${c===ee.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:ee.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ee.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:l("profiles.localProfiles.badge")}),ee.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:l("configureAmsSlot.builtin")}),ee.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:l("configureAmsSlot.custom")})]})]})},ee.id))})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.kProfileLabel"),ae&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:l("configureAmsSlot.filteringFor",{material:ae})})]}),K.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:d?.name||"",onChange:ee=>{const je=K.find(he=>he.name===ee.target.value);h(je||null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none pr-10",children:[i.jsx("option",{value:"",children:l("configureAmsSlot.noKProfile")}),K.map(ee=>i.jsxs("option",{value:ee.name,children:[ee.name," (K=",ee.k_value,")"]},`${ee.name}-${ee.extruder_id}`))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):c?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:l("configureAmsSlot.noMatchingKProfiles")}):i.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:l("configureAmsSlot.selectFilamentFirst")}),d&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:l("configureAmsSlot.kFromCalibration",{value:d.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:l("configureAmsSlot.customColorLabel")}),H.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:l("configureAmsSlot.presetColors",{name:X?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:H.map(ee=>i.jsxs("button",{onClick:()=>{const je=ee.hex_color.replace("#","").toUpperCase();p(je),v(ee.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===ee.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:ee.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/30 flex-shrink-0",style:{backgroundColor:ee.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:ee.color_name})]},ee.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[n$e.map(ee=>i.jsx("button",{onClick:()=>{p(ee.hex),v(ee.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===ee.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${ee.hex}`},title:ee.name},ee.hex)),i.jsx("button",{onClick:()=>A(!k),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:l(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:r$e.map(ee=>i.jsx("button",{onClick:()=>{p(ee.hex),v(ee.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===ee.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${ee.hex}`},title:ee.name},ee.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${ce}`}}),i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.colorPlaceholder"),value:x,onChange:ee=>{const je=ee.target.value;v(je);const he=a$e(je);if(he)p(he);else{const oe=je.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();oe.length===6?p(oe):oe.length===3&&p(oe.split("").map(_e=>_e+_e).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&i.jsx("button",{onClick:()=>{p(""),v("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:l("configureAmsSlot.clearCustomColor"),children:l("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:l("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),i.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>z.mutate(),disabled:z.isPending||G.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:z.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(so,{className:"w-4 h-4"}),l("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:l("configureAmsSlot.cancel")}),i.jsx(Ce,{onClick:()=>G.mutate(),disabled:!ve,children:G.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(ed,{className:"w-4 h-4"}),l("configureAmsSlot.configureSlot")]})})]})]}),(G.isError||z.isError)&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:G.error?.message||z.error?.message})]})]})}function Z7(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function ja(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Fc(t,e,n=40){const r=ja(t),a=ja(e);if(!r||!a||r.length<6||a.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(a.substring(0,2),16),u=parseInt(a.substring(2,4),16),d=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function m4(t,e,n,r){if(r)return"External";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`AMS-${a} Slot ${e+1}`}function f4(t,e,n){return n?254+e:t>=128?t:t*4+e}function J7(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}const e9={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},o$e={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function Hj(t){if(!t)return null;if(e9[t])return e9[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return o$e[n]||null}function $j(t){if(!t||t.length<6)return"Unknown";const e=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16),a=Math.max(e,n,r)/255,s=Math.min(e,n,r)/255,o=(a+s)/2;let l=0,c=0;if(a!==s){const u=a-s;c=o>.5?u/(2-a-s):u/(a+s);const d=e/255,h=n/255,f=r/255;a===d?l=((h-f)/u+(h<f?6:0))/6:a===h?l=((f-d)/u+2)/6:l=((d-h)/u+4)/6}return l=l*360,o<.15?"Black":o>.85?"White":c<.15?o<.4?"Dark Gray":o>.6?"Light Gray":"Gray":l>=15&&l<45&&o<.45||l>=45&&l<70&&o<.4?"Brown":l<15||l>=345?"Red":l<45?"Orange":l<70?"Yellow":l<150?"Green":l<200?"Cyan":l<260?"Blue":l<290?"Purple":"Pink"}function Vj(t){return(t??.02).toFixed(3)}function t9({side:t}){const{mode:e}=tp(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function p4(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),a=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return a===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${a})`}function l$e(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*r)/255>.6}function pne(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function gne(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function bne({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Ot(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),h=w.useRef(null),f=w.useRef(null),p=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&d.current&&h.current){const k=d.current.getBoundingClientRect(),A=h.current.offsetHeight,C=k.top-56,j=window.innerHeight-k.bottom;C<A+12&&j>C?u("bottom"):u("top")}},[o]);const v=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!0),80)},g=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const y=p4(t.filament_color),_=pne(t.nozzle_type,s),N=gne(t.nozzle_type,s);return i.jsxs("div",{ref:d,className:"relative",onMouseEnter:v,onMouseLeave:g,children:[a,o&&i.jsxs("div",{ref:h,className:`
  8134. absolute left-1/2 -translate-x-1/2 z-50
  8135. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8136. animate-in fade-in-0 zoom-in-95 duration-150
  8137. `,style:{maxWidth:"calc(100vw - 24px)"},children:[i.jsx("div",{className:"w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:p?i.jsxs("div",{className:"px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap",children:["Slot ",e+1," — Empty"]}):i.jsxs("div",{className:"p-2.5 space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleDiameter")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.nozzle_diameter," mm"]})]}),_&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleType")}),i.jsx("span",{className:"text-xs text-white font-semibold truncate max-w-[100px]",children:_})]}),N&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFlow")}),i.jsx("span",{className:"text-xs text-white font-semibold",children:N})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleStatus")}),i.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${n||x?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(n?"printers.nozzleActive":x?"printers.nozzleMounted":"printers.nozzleDocked")})]}),t.wear!=null&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleWear")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.wear,"%"]})]}),t.max_temp>0&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleMaxTemp")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[t.max_temp,"°C"]})]}),t.serial_number&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleSerial")}),i.jsx("span",{className:"text-[10px] text-white font-mono truncate max-w-[80px]",children:t.serial_number})]}),(y||t.filament_type)&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:s("printers.nozzleFilament")}),i.jsxs("div",{className:"flex items-center gap-1",children:[y&&i.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:y}}),i.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:r||t.filament_type||t.filament_id||""})]})]})]})}),i.jsx("div",{className:`
  8138. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8139. border-l-[6px] border-l-transparent
  8140. border-r-[6px] border-r-transparent
  8141. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8142. `})]})]})}function c$e({leftSlot:t,rightSlot:e,activeNozzle:n,filamentInfo:r,children:a}){const{t:s}=Ot(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),h=w.useRef(null),f=w.useRef(null);w.useEffect(()=>{if(o&&d.current&&h.current){const g=d.current.getBoundingClientRect(),y=h.current.offsetHeight,N=g.top-56,k=window.innerHeight-g.bottom;N<y+12&&k>N?u("bottom"):u("top")}},[o]);const p=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!0),80)},x=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),100)};if(w.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]),!t&&!e)return i.jsx(i.Fragment,{children:a});const v=(g,y)=>{const _=n===y,N=pne(g.nozzle_type,s),k=gne(g.nozzle_type,s),A=p4(g.filament_color),M=g.filament_id?r?.[g.filament_id]?.name:void 0;return i.jsxs("div",{className:"flex-1 space-y-1.5",children:[i.jsx("div",{className:`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${_?"text-amber-400":"text-bambu-gray"}`,children:s(y==="L"?"common.left":"common.right")}),g.nozzle_diameter&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleDiameter")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.nozzle_diameter," mm"]})]}),N&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleType")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:N})]}),k&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFlow")}),i.jsx("span",{className:"text-[10px] text-white font-semibold",children:k})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleStatus")}),i.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${_?"bg-green-900/50 text-green-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:s(_?"printers.nozzleActive":"printers.nozzleIdle")})]}),g.wear!=null&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleWear")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.wear,"%"]})]}),y==="R"&&g.max_temp>0&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleMaxTemp")}),i.jsxs("span",{className:"text-xs text-white font-semibold",children:[g.max_temp,"°C"]})]}),y==="R"&&g.serial_number&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleSerial")}),i.jsx("span",{className:"text-[10px] text-white font-mono",children:g.serial_number})]}),(A||g.filament_type||g.filament_id)&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-[10px] text-bambu-gray",children:s("printers.nozzleFilament")}),i.jsxs("div",{className:"flex items-center gap-1",children:[A&&i.jsx("div",{className:"w-3 h-3 rounded-sm border border-white/20",style:{backgroundColor:A}}),i.jsx("span",{className:"text-[10px] text-white font-semibold truncate max-w-[100px]",children:M||g.filament_type||g.filament_id||""})]})]})]})};return i.jsxs("div",{ref:d,className:"relative flex-1",onMouseEnter:p,onMouseLeave:x,children:[a,o&&i.jsxs("div",{ref:h,className:`
  8143. absolute left-1/2 -translate-x-1/2 z-50
  8144. ${c==="top"?"bottom-full mb-2":"top-full mt-2"}
  8145. animate-in fade-in-0 zoom-in-95 duration-150
  8146. `,style:{maxWidth:"calc(100vw - 24px)"},children:[i.jsx("div",{className:"w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm",children:i.jsxs("div",{className:"p-2.5 flex gap-3",children:[t&&v(t,"L"),t&&e&&i.jsx("div",{className:"w-px bg-bambu-dark-tertiary/50"}),e&&v(e,"R")]})}),i.jsx("div",{className:`
  8147. absolute left-1/2 -translate-x-1/2 w-0 h-0
  8148. border-l-[6px] border-l-transparent
  8149. border-r-[6px] border-r-transparent
  8150. ${c==="top"?"top-full border-t-[6px] border-t-bambu-dark-tertiary":"bottom-full border-b-[6px] border-b-bambu-dark-tertiary"}
  8151. `})]})]})}function u$e({slots:t,filamentInfo:e}){const{t:n}=Ot(),r=t.filter(l=>l.id>=2),a=6,s=r.length>0?Math.min(...r.map(l=>l.id)):16,o=Array.from({length:a},(l,c)=>r.find(u=>u.id===s+c)??{id:-(c+1),nozzle_type:"",nozzle_diameter:"",wear:null,stat:null,max_temp:0,serial_number:"",filament_color:"",filament_id:"",filament_type:""});return i.jsxs("div",{className:"text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center",children:[i.jsx("p",{className:"text-[9px] text-bambu-gray mb-1",children:n("printers.nozzleRack")}),i.jsx("div",{className:"flex gap-[3px] justify-center",children:o.map((l,c)=>{const u=!l.nozzle_diameter&&!l.nozzle_type,d=u?null:p4(l.filament_color),h=d?l$e(l.filament_color):!1;return i.jsx(bne,{slot:l,index:c,filamentName:l.filament_id?e?.[l.filament_id]?.name:void 0,children:i.jsx("div",{className:`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${u?"bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20":"bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40"}`,style:d?{backgroundColor:d}:void 0,children:i.jsx("span",{className:`text-[10px] font-semibold ${u?"text-bambu-gray/30":h?"text-black/80":"text-white"}`,style:d&&!h?{textShadow:"0 1px 3px rgba(0,0,0,0.9)"}:void 0,children:u?"—":l.nozzle_diameter||"?"})})},l.id>=0?l.id:`empty-${c}`)})})]})}function n9({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function d$e({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function h$e({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function m$e({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function f$e({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function p$e({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function qj({className:t,color:e,isHeating:n}){const a={"text-orange-400":"#fb923c","text-blue-400":"#60a5fa","text-green-400":"#4ade80"}[e]||"#888",s=n?{filter:`drop-shadow(0 0 4px ${a}) drop-shadow(0 0 8px ${a})`}:{};return n?i.jsxs("svg",{className:t,style:s,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:a,rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:a}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"})]}):i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:a,strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:a,strokeWidth:"1",fill:"none"})]})}function r9({humidity:t,goodThreshold:e=40,fairThreshold:n=60,onClick:r,compact:a}){const s=typeof t=="string"?parseInt(t,10):t,o=typeof e=="number"?e:40,l=typeof n=="number"?n:60;let c,u;isNaN(s)?(c="#C3C2C1",u="Unknown"):s<=o?(c="#22a352",u="Good"):s<=l?(c="#d4a017",u="Fair"):(c="#c62828",u="Bad");let d;return isNaN(s)||s<=o?d=n9:s<=l?d=d$e:d=h$e,i.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Humidity: ${s}% - ${u}${r?" (click for history)":""}`,children:[i.jsx(d,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`font-medium tabular-nums ${a?"text-[10px]":"text-xs"}`,style:{color:c},children:[s,"%"]})]})}function a9({temp:t,goodThreshold:e=28,fairThreshold:n=35,onClick:r,compact:a}){const s=typeof e=="number"?e:28,o=typeof n=="number"?n:35;let l,c,u;return t<=s?(l="#22a352",c="Good",u=m$e):t<=o?(l="#d4a017",c="Fair",u=f$e):(l="#c62828",c="Bad",u=p$e),i.jsxs("button",{type:"button",onClick:r,className:`flex items-center gap-1 ${r?"cursor-pointer hover:opacity-80 transition-opacity":""}`,title:`Temperature: ${t}°C - ${c}${r?" (click for history)":""}`,children:[i.jsx(u,{className:a?"w-2.5 h-3":"w-3 h-4"}),i.jsxs("span",{className:`tabular-nums text-right ${a?"text-[10px] w-8":"w-12"}`,style:{color:l},children:[t,"°C"]})]})}function th(t,e){const n=typeof t=="string"?parseInt(t,10):t,r=isNaN(n)?0:n,a=e===1,s=r>=128?r-128:r,o=String.fromCharCode(65+s);return a?`HT-${o}`:`AMS-${o}`}function Gj(t){return t>50?"#00ae42":t>=15?"#f59e0b":"#ef4444"}function Wj(t){return!t?.remaining_weight||!t?.filament_weight||t.filament_weight<=0?null:Math.min(100,Math.round(t.remaining_weight/t.filament_weight*100))}function g$e(t){if(!t)return"/img/printers/default.png";const e=t.toLowerCase().replace(/\s+/g,"");return e.includes("x1e")?"/img/printers/x1e.png":e.includes("x1c")||e.includes("x1carbon")||e.includes("x1")?"/img/printers/x1c.png":e.includes("h2dpro")||e.includes("h2d-pro")?"/img/printers/h2dpro.png":e.includes("h2d")?"/img/printers/h2d.png":e.includes("h2c")?"/img/printers/h2c.png":e.includes("h2s")?"/img/printers/h2d.png":e.includes("p2s")||e.includes("p1s")?"/img/printers/p1s.png":e.includes("p1p")?"/img/printers/p1p.png":e.includes("a1mini")?"/img/printers/a1mini.png":e.includes("a1")?"/img/printers/a1.png":"/img/printers/default.png"}function b$e(t){return t>=-50?{labelKey:"printers.wifiSignal.excellent",color:"text-bambu-green",bars:4}:t>=-60?{labelKey:"printers.wifiSignal.good",color:"text-bambu-green",bars:3}:t>=-70?{labelKey:"printers.wifiSignal.fair",color:"text-yellow-400",bars:2}:t>=-80?{labelKey:"printers.wifiSignal.weak",color:"text-orange-400",bars:1}:{labelKey:"printers.wifiSignal.veryWeak",color:"text-red-400",bars:1}}function Kj(t){return t?!!(t.tray_uuid&&t.tray_uuid!=="00000000000000000000000000000000"||t.tag_uid&&t.tag_uid!=="0000000000000000"):!1}function x$e({url:t,printName:e}){const{t:n}=Ot(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(!1),u=w.useMemo(()=>{if(!t)return null;const d=t.includes("?")?"&":"?";return`${t}${d}v=${encodeURIComponent(e||Date.now().toString())}`},[t,e]);return w.useEffect(()=>{a(!1),o(!1)},[u]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${u&&r?"cursor-pointer":""}`,onClick:()=>u&&r&&c(!0),children:u&&!s?i.jsxs(i.Fragment,{children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:`w-full h-full object-cover ${r?"block":"hidden"}`,onLoad:()=>a(!0),onError:()=>o(!0)}),!r&&i.jsx(Ja,{className:"w-8 h-8 text-bambu-gray"})]}):i.jsx(Ja,{className:"w-8 h-8 text-bambu-gray"})}),l&&u&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8",onClick:()=>c(!1),children:i.jsxs("div",{className:"relative max-w-2xl max-h-full",children:[i.jsx("img",{src:u,alt:n("printers.printPreview"),className:"max-w-full max-h-[80vh] rounded-lg shadow-2xl"}),e&&i.jsx("p",{className:"text-white text-center mt-4 text-lg",children:e})]})})]})}function y$e({printers:t}){const{t:e}=Ot(),n=en(),[r,a]=w.useState(0);w.useEffect(()=>{let l=!1;const c=n.getQueryCache().subscribe(()=>{l||(l=!0,requestAnimationFrame(()=>{a(u=>u+1),l=!1}))});return()=>c()},[n]);const{counts:s,nextFinish:o}=w.useMemo(()=>{let l=0,c=0,u=0,d=0,h=null,f=null,p=0;return t?.forEach(x=>{const v=n.getQueryData(["printerStatus",x.id]);v===void 0?d++:v.connected?v.state==="RUNNING"?(l++,v.remaining_time!=null&&v.remaining_time>0&&(f===null||v.remaining_time<f)&&(f=v.remaining_time,h=x.name,p=v.progress||0)):c++:u++}),{counts:{printing:l,idle:c,offline:u,loading:d,total:t?.length||0},nextFinish:h&&f?{name:h,remainingMin:f,progress:p}:null}},[t,n,r]);return t?.length?i.jsxs("div",{className:"flex flex-wrap items-center gap-4 gap-y-2 text-sm",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${s.idle>0?"bg-bambu-green":"bg-gray-500"}`}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.idle})," ",e("printers.status.available").toLowerCase()]})]}),s.printing>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.printing})," ",e("printers.status.printing").toLowerCase()]})]}),s.offline>0&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-gray-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white font-medium",children:s.offline})," ",e("printers.status.offline").toLowerCase()]})]}),o&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-4 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-bambu-green font-medium",children:[e("printers.nextAvailable"),":"]}),i.jsx("span",{className:"text-white font-medium",children:o.name})]}),i.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto",children:[i.jsx("div",{className:"w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5",children:i.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${o.progress}%`}})}),i.jsxs("span",{className:"text-white font-medium",children:[Math.round(o.progress),"%"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",Qs(o.remainingMin*60),")"]})]})]})]})]}):null}function i9(t,e){if(e)return e;switch(t){case"RUNNING":return"Printing";case"PAUSE":return"Paused";case"FINISH":return"Finished";case"FAILED":return"Failed";case"IDLE":return"Idle";default:return t?t.charAt(0)+t.slice(1).toLowerCase():"Idle"}}function xR(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function s9({printer:t,hideIfDisconnected:e,maintenanceInfo:n,viewMode:r="expanded",cardSize:a=2,amsThresholds:s,spoolmanEnabled:o=!1,hasUnlinkedSpools:l=!1,linkedSpools:c,spoolmanUrl:u,onGetAssignment:d,onUnassignSpool:h,timeFormat:f="system",cameraViewMode:p="window",onOpenEmbeddedCamera:x,checkPrinterFirmware:v=!0}){const{t:g}=Ot(),y=en(),_=rc(),{showToast:N}=an(),{hasPermission:k}=Ir(),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(!0),[U,L]=w.useState(!1),[B,D]=w.useState(!1),[$,G]=w.useState(!1),[z,W]=w.useState(!1),[X,ae]=w.useState(!1),[H,K]=w.useState(!1),[te,Z]=w.useState(!1),[ve,ce]=w.useState(!1),[ee,je]=w.useState(!1),[he,oe]=w.useState(!1),[_e,ie]=w.useState(null),[ze,V]=w.useState(null),[Y,me]=w.useState(null),[Q,se]=w.useState(null),[de,Le]=w.useState(!1),[Ne,be]=w.useState(null),[O,R]=w.useState(!1),[q,J]=w.useState(!1),[fe,le]=w.useState(null),[Be,Ie]=w.useState(!1),[Ke,Oe]=w.useState(!1),{data:pe}=Je({queryKey:["printerStatus",t.id],queryFn:()=>ne.getPrinterStatus(t.id),refetchInterval:3e4}),{data:xe}=Je({queryKey:["firmwareUpdate",t.id],queryFn:()=>$_.checkPrinterUpdate(t.id),staleTime:300*1e3,refetchInterval:300*1e3,enabled:v&&k("firmware:read")}),ke=w.useMemo(()=>{const xt=new Set;if(pe?.ams)for(const Ft of pe.ams)for(const bn of Ft.tray||[])bn.tray_info_idx&&xt.add(bn.tray_info_idx);for(const Ft of pe?.vt_tray??[])Ft.tray_info_idx&&xt.add(Ft.tray_info_idx);if(pe?.nozzle_rack)for(const Ft of pe.nozzle_rack)Ft.filament_id&&xt.add(Ft.filament_id);return Array.from(xt)},[pe?.ams,pe?.vt_tray,pe?.nozzle_rack]),{data:ge}=Je({queryKey:["filamentInfo",ke],queryFn:()=>ne.getFilamentInfo(ke),enabled:ke.length>0,staleTime:300*1e3}),{data:we}=Je({queryKey:["slotPresets",t.id],queryFn:()=>ne.getSlotPresets(t.id),staleTime:120*1e3}),[qe,Ee]=w.useState(null);w.useEffect(()=>{pe?.wifi_signal!=null&&Ee(pe.wifi_signal)},[pe?.wifi_signal]);const tt=pe?.wifi_signal??qe,De=w.useRef(void 0);w.useEffect(()=>{pe?.connected!==void 0&&(De.current=pe.connected)},[pe?.connected]);const We=pe?.connected??De.current,Ae=w.useRef({});w.useEffect(()=>{pe?.ams_extruder_map&&Object.keys(pe.ams_extruder_map).length>0&&(Ae.current=pe.ams_extruder_map)},[pe?.ams_extruder_map]);const Re=pe?.ams_extruder_map&&Object.keys(pe.ams_extruder_map).length>0?pe.ams_extruder_map:Ae.current,$e=w.useRef([]);w.useEffect(()=>{pe?.ams&&pe.ams.length>0&&($e.current=pe.ams)},[pe?.ams]);const ht=pe?.ams&&pe.ams.length>0?pe.ams:$e.current,At=w.useRef(void 0),Dt=pe?.tray_now;Dt!==void 0&&Dt!==255?At.current=Dt:Dt===255&&(At.current=void 0);const It=Dt!==void 0&&Dt!==255?Dt:At.current,{data:kt}=Je({queryKey:["smartPlugByPrinter",t.id],queryFn:()=>ne.getSmartPlugByPrinter(t.id)}),{data:Ue}=Je({queryKey:["scriptPlugsByPrinter",t.id],queryFn:()=>ne.getScriptPlugsByPrinter(t.id)}),{data:bt}=Je({queryKey:["smartPlugStatus",kt?.id],queryFn:()=>kt?ne.getSmartPlugStatus(kt.id):null,enabled:!!kt,refetchInterval:1e4}),{data:yt}=Je({queryKey:["queue",t.id,"pending"],queryFn:()=>ne.getQueue(t.id,"pending")}),Gt=yt?.length||0,{data:Cn}=Je({queryKey:["queue",t.id,"printing"],queryFn:()=>ne.getQueue(t.id,"printing"),enabled:pe?.state==="RUNNING"}),{data:vr}=Je({queryKey:["currentPrintUser",t.id],queryFn:()=>ne.getCurrentPrintUser(t.id),enabled:pe?.state==="RUNNING"}),Qn=Cn?.[0]?.created_by_username||vr?.username,{data:tr}=Je({queryKey:["archives",t.id,"last"],queryFn:()=>ne.getArchives(t.id,1,0),enabled:pe?.connected&&pe?.state!=="RUNNING"}),En=tr?.[0],dr=e&&We===!1,Tr=st({mutationFn:xt=>ne.deletePrinter(t.id,xt.deleteArchives),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),y.invalidateQueries({queryKey:["archives"]}),y.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:xt=>N(xt.message||g("printers.toast.failedToDelete"),"error")}),si=st({mutationFn:()=>ne.connectPrinter(t.id),onSuccess:()=>{y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),Fe=st({mutationFn:xt=>kt?ne.controlSmartPlug(kt.id,xt):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugStatus",kt?.id]})}}),Se=st({mutationFn:xt=>kt?ne.updateSmartPlug(kt.id,{auto_off:xt}):Promise.reject("No plug"),onSuccess:()=>{y.invalidateQueries({queryKey:["smartPlugByPrinter",t.id]}),y.invalidateQueries({queryKey:["smart-plugs"]})}}),nt=st({mutationFn:xt=>ne.controlSmartPlug(xt,"on"),onSuccess:()=>{N(g("printers.toast.scriptTriggered"))},onError:xt=>N(xt.message||g("printers.toast.failedToRunScript"),"error")}),ot=st({mutationFn:()=>ne.stopPrint(t.id),onSuccess:()=>{N(g("printers.toast.printStopped")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:xt=>N(xt.message||g("printers.toast.failedToStopPrint"),"error")}),Ge=st({mutationFn:()=>ne.pausePrint(t.id),onSuccess:()=>{N(g("printers.toast.printPaused")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:xt=>N(xt.message||g("printers.toast.failedToPausePrint"),"error")}),zt=st({mutationFn:()=>ne.resumePrint(t.id),onSuccess:()=>{N(g("printers.toast.printResumed")),y.invalidateQueries({queryKey:["printerStatus",t.id]})},onError:xt=>N(xt.message||g("printers.toast.failedToResumePrint"),"error")}),ye=st({mutationFn:xt=>ne.setChamberLight(t.id,xt),onMutate:async xt=>{await y.cancelQueries({queryKey:["printerStatus",t.id]});const Ft=y.getQueryData(["printerStatus",t.id]);return y.setQueryData(["printerStatus",t.id],bn=>({...bn,chamber_light:xt})),{previousStatus:Ft}},onSuccess:(xt,Ft)=>{N(`Chamber light ${Ft?"on":"off"}`)},onError:(xt,Ft,bn)=>{bn?.previousStatus&&y.setQueryData(["printerStatus",t.id],bn.previousStatus),N(xt.message||g("printers.toast.failedToControlChamberLight"),"error")}}),He=st({mutationFn:xt=>ne.updatePrinter(t.id,{plate_detection_enabled:xt}),onSuccess:()=>{y.invalidateQueries({queryKey:["printers"]}),N(He.variables?g("printers.toast.plateCheckEnabled"):g("printers.toast.plateCheckDisabled"))},onError:xt=>N(xt.message||g("printers.toast.failedToUpdateSetting"),"error")}),Ye=(pe?.state==="RUNNING"||pe?.state==="PAUSE")&&(pe?.printable_objects_count??0)>=2,{data:Xe}=Je({queryKey:["printableObjects",t.id],queryFn:()=>ne.getPrintableObjects(t.id),enabled:he||Ye,refetchInterval:he?5e3:Ye?3e4:!1}),[Te,lt]=w.useState(null),pt=w.useRef(!1),at=w.useRef(null),Tt=w.useRef(!1),$t=st({mutationFn:({amsId:xt,slotId:Ft})=>ne.refreshAmsSlot(t.id,xt,Ft),onMutate:({amsId:xt,slotId:Ft})=>{at.current&&clearTimeout(at.current),pt.current=!1,Tt.current=!1,lt({amsId:xt,slotId:Ft}),setTimeout(()=>{Tt.current=!0},2e3),at.current=setTimeout(()=>{lt(null)},3e4)},onSuccess:xt=>{N(xt.message||g("printers.toast.rfidRereadInitiated"))},onError:xt=>{N(xt.message||g("printers.toast.failedToRereadRfid"),"error"),at.current&&clearTimeout(at.current),lt(null)}}),[Rt,Pt]=w.useState(null),[sn,Zt]=w.useState(null),un=async()=>{try{const xt=await ne.getPlateReferences(t.id);Pt(xt)}catch{}},kn=()=>{He.mutate(!t.plate_detection_enabled)},Dn=async()=>{R(!0),be(null);const xt=pe?.chamber_light===!1;Oe(xt),xt&&(await ne.setChamberLight(t.id,!0),await new Promise(Ft=>setTimeout(Ft,2500)));try{const Ft=await ne.checkPlateEmpty(t.id,{includeDebugImage:!0});be(Ft),un()}catch(Ft){N(Ft instanceof Error?Ft.message:g("printers.toast.failedToCheckPlate"),"error"),xt&&(await ne.setChamberLight(t.id,!1),Oe(!1))}finally{R(!1)}},Xt=w.useCallback(async()=>{be(null),Ke&&(await ne.setChamberLight(t.id,!1),Oe(!1))},[Ke,t.id]),mn=async xt=>{J(!0);try{const Ft=await ne.calibratePlateDetection(t.id,{label:xt});if(Ft.success){N(Ft.message||g("printers.toast.calibrationSaved"),"success"),un();const bn=await ne.checkPlateEmpty(t.id,{includeDebugImage:!0});be(bn)}else N(Ft.message||g("printers.toast.calibrationFailed"),"error")}catch(Ft){N(Ft instanceof Error?Ft.message:g("printers.toast.calibrationFailed"),"error")}finally{J(!1)}},fn=async(xt,Ft)=>{try{await ne.updatePlateReferenceLabel(t.id,xt,Ft),Zt(null),un()}catch(bn){N(bn instanceof Error?bn.message:g("printers.toast.failedToUpdateLabel"),"error")}},Gr=async xt=>{try{await ne.deletePlateReference(t.id,xt),N(g("printers.toast.referenceDeleted"),"success"),un();const Ft=await ne.checkPlateEmpty(t.id,{includeDebugImage:!0});be(Ft)}catch(Ft){N(Ft instanceof Error?Ft.message:g("printers.toast.failedToDeleteReference"),"error")}},pn=async()=>{if(fe){Ie(!0);try{await ne.updatePrinter(t.id,{plate_detection_roi:fe}),N(g("printers.toast.detectionAreaSaved"),"success"),le(null);const xt=await ne.checkPlateEmpty(t.id,{includeDebugImage:!0});be(xt)}catch(xt){N(xt instanceof Error?xt.message:g("printers.toast.failedToSaveDetectionArea"),"error")}finally{Ie(!1)}}};w.useEffect(()=>{const xt=Ft=>{Ft.key==="Escape"&&Ne&&Xt()};return window.addEventListener("keydown",xt),()=>window.removeEventListener("keydown",xt)},[Ne,Xt]);const Rn=w.useRef(null);w.useEffect(()=>{if(!Te)return;const xt=pe?.ams_status_main??0;return xt!==0&&(pt.current=!0,Rn.current&&(clearTimeout(Rn.current),Rn.current=null)),pt.current&&xt===0&&(Tt.current?(at.current&&clearTimeout(at.current),lt(null)):Rn.current||(Rn.current=setTimeout(()=>{at.current&&clearTimeout(at.current),lt(null)},2e3))),()=>{Rn.current&&clearTimeout(Rn.current)}},[pe?.ams_status_main,Te]);const[ia,Sn]=w.useState(null);if(dr)return null;const va=()=>{switch(a){case 1:return"w-10 h-10";case 2:return"w-14 h-14";case 3:return"w-16 h-16";case 4:return"w-20 h-20";default:return"w-14 h-14"}},sr=()=>{switch(a){case 1:return"text-base truncate";case 2:return"text-lg";case 3:return"text-xl";case 4:return"text-2xl";default:return"text-lg"}},ma=()=>{switch(a){case 1:return"mb-2";case 2:return"mb-4";case 3:return"mb-5";case 4:return"mb-6";default:return"mb-4"}};return i.jsxs(wt,{className:"relative",children:[i.jsxs(_t,{className:a>=3?"p-5":"",children:[i.jsxs("div",{className:ma(),children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("img",{src:g$e(t.model),alt:t.model||g("common.printer"),className:`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${va()}`}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-semibold text-white ${sr()}`,children:t.name}),r==="compact"&&i.jsx("div",{className:`w-2 h-2 rounded-full flex-shrink-0 ${pe?.connected?"bg-status-ok":"bg-status-error"}`,title:pe?.connected?g("printers.connection.connected"):g("printers.connection.offline")})]}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[t.model||"Unknown Model",r==="expanded"&&pe?.nozzles&&pe.nozzles[0]?.nozzle_diameter&&i.jsxs("span",{className:"ml-1.5 text-bambu-gray",title:pe.nozzles[0].nozzle_type||"Nozzle",children:["• ",pe.nozzles[0].nozzle_diameter,"mm"]}),r==="expanded"&&n&&n.total_print_hours>0&&i.jsxs("span",{className:"ml-2 text-bambu-gray",children:[i.jsx(Wn,{className:"w-3 h-3 inline-block mr-1"}),Math.round(n.total_print_hours),"h"]})]})]})]}),i.jsxs("div",{className:"relative flex-shrink-0",children:[i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>M(!A),children:i.jsx(Th,{className:"w-4 h-4"})}),A&&i.jsxs("div",{className:"absolute right-0 mt-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-20",children:[i.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${k("printers:update")?"hover:bg-bambu-dark-tertiary":"opacity-50 cursor-not-allowed"}`,onClick:()=>{k("printers:update")&&(L(!0),M(!1))},title:k("printers:update")?void 0:g("printers.permission.noEdit"),children:[i.jsx($a,{className:"w-4 h-4"}),g("common.edit")]}),i.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{si.mutate(),M(!1)},children:[i.jsx(Ar,{className:"w-4 h-4"}),g("printers.reconnect")]}),i.jsxs("button",{className:"w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2",onClick:()=>{G(!0),M(!1)},children:[i.jsx(NX,{className:"w-4 h-4"}),g("printers.mqttDebug")]}),i.jsxs("button",{className:`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${k("printers:delete")?"text-red-400 hover:bg-bambu-dark-tertiary":"text-red-400/50 cursor-not-allowed"}`,onClick:()=>{k("printers:delete")&&(j(!0),M(!1))},title:k("printers:delete")?void 0:g("printers.permission.noDelete"),children:[i.jsx(Jt,{className:"w-4 h-4"}),g("common.delete")]})]})]})]}),r==="expanded"&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[i.jsxs("span",{className:`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${pe?.connected?"bg-status-ok/20 text-status-ok":"bg-status-error/20 text-status-error"}`,children:[pe?.connected?i.jsx(qb,{className:"w-3 h-3"}):i.jsx(ek,{className:"w-3 h-3"}),pe?.connected?g("printers.connection.connected"):g("printers.connection.offline")]}),pe?.connected&&tt!=null&&i.jsxs("span",{className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${tt>=-50||tt>=-60?"bg-status-ok/20 text-status-ok":tt>=-70?"bg-status-warning/20 text-status-warning":tt>=-80?"bg-orange-500/20 text-orange-600":"bg-status-error/20 text-status-error"}`,title:`WiFi: ${tt} dBm - ${g(b$e(tt).labelKey)}`,children:[i.jsx(mpe,{className:"w-3 h-3"}),tt,"dBm"]}),pe?.connected&&(()=>{const xt=pe.hms_errors?FTe(pe.hms_errors):[];return i.jsxs("button",{onClick:()=>K(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${xt.length>0?xt.some(Ft=>Ft.severity<=2)?"bg-status-error/20 text-status-error":"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:g("printers.clickToViewHmsErrors"),children:[i.jsx(Tn,{className:"w-3 h-3"}),xt.length>0?xt.length:"OK"]})})(),n&&i.jsxs("button",{onClick:()=>_("/maintenance"),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${n.due_count>0?"bg-status-error/20 text-status-error":n.warning_count>0?"bg-status-warning/20 text-status-warning":"bg-status-ok/20 text-status-ok"}`,title:n.due_count>0||n.warning_count>0?`${n.due_count>0?`${n.due_count} maintenance due`:""}${n.due_count>0&&n.warning_count>0?", ":""}${n.warning_count>0?`${n.warning_count} due soon`:""} - Click to view`:g("printers.maintenanceUpToDate"),children:[i.jsx(Df,{className:"w-3 h-3"}),n.due_count>0||n.warning_count>0?n.due_count+n.warning_count:"OK"]}),Gt>0&&i.jsxs("button",{onClick:()=>_("/queue"),className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-purple-500/20 text-purple-400 hover:opacity-80 transition-opacity",title:g("printers.queue.inQueue",{count:Gt}),children:[i.jsx(fi,{className:"w-3 h-3"}),Gt]}),v&&xe?.current_version&&xe?.latest_version?i.jsxs("button",{onClick:()=>Le(!0),className:`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${xe.update_available?"bg-orange-500/20 text-orange-400":"bg-status-ok/20 text-status-ok"}`,title:xe.update_available?g("printers.firmwareUpdateAvailable",{current:xe.current_version,latest:xe.latest_version}):g("printers.firmwareUpToDate",{version:xe.current_version}),children:[xe.update_available?i.jsx(da,{className:"w-3 h-3"}):i.jsx(pr,{className:"w-3 h-3"}),xe.current_version]}):pe?.firmware_version?i.jsx("span",{className:"flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray",children:pe.firmware_version}):null]})]}),C&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(wt,{className:"w-full max-w-md mx-4",children:i.jsxs(_t,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:"p-2 rounded-full bg-red-500/20",children:i.jsx(Tn,{className:"w-5 h-5 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:g("printers.confirm.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:g("printers.confirm.deleteMessage",{name:t.name})})]})]}),i.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:i.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:P,onChange:xt=>E(xt.target.checked),className:"mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:g("printers.deleteArchives")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:g(P?"printers.confirm.deleteArchivesNote":"printers.confirm.keepArchivesNote")})]})]})}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{j(!1),E(!0)},children:g("common.cancel")}),i.jsx(Ce,{variant:"danger",onClick:()=>{Tr.mutate({deleteArchives:P}),j(!1),E(!0)},children:"Delete"})]})]})})}),pe?.connected&&i.jsxs(i.Fragment,{children:[r==="compact"?i.jsx("div",{className:"mt-2",children:pe.state==="RUNNING"?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5",children:i.jsx("div",{className:"bg-bambu-green h-1.5 rounded-full transition-all",style:{width:`${pe.progress||0}%`}})}),i.jsxs("span",{className:"text-xs text-white",children:[Math.round(pe.progress||0),"%"]})]}):i.jsx("p",{className:"text-xs text-bambu-gray",children:i9(pe.state,pe.stg_cur_name)})}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mb-4 p-3 bg-bambu-dark rounded-lg relative",children:[i.jsxs("button",{onClick:()=>oe(!0),disabled:!(pe.state==="RUNNING"||pe.state==="PAUSE")||(pe.printable_objects_count??0)<2||!k("printers:control"),className:`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${(pe.state==="RUNNING"||pe.state==="PAUSE")&&(pe.printable_objects_count??0)>=2&&k("printers:control")?"text-bambu-gray hover:text-white hover:bg-white/10":"text-bambu-gray/30 cursor-not-allowed"}`,title:k("printers:control")?pe.state==="RUNNING"||pe.state==="PAUSE"?(pe.printable_objects_count??0)>=2?g("printers.skipObjects.tooltip"):g("printers.skipObjects.requiresMultiple"):g("printers.skipObjects.onlyWhilePrinting"):g("printers.permission.noControl"),children:[i.jsx(hk,{className:"w-4 h-4"}),Xe&&Xe.skipped_count>0&&i.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full",children:Xe.skipped_count})]}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(x$e,{url:pe.state==="RUNNING"?pe.cover_url:null,printName:pe.state==="RUNNING"&&(pe.subtask_name||pe.current_print)||void 0}),i.jsx("div",{className:"flex-1 min-w-0",children:pe.current_print&&pe.state==="RUNNING"?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:pe.stg_cur_name||"Printing"}),i.jsx("p",{className:"text-white text-sm mb-2 truncate",children:pe.subtask_name||pe.current_print}),i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all",style:{width:`${pe.progress||0}%`}})}),i.jsxs("span",{className:"text-white",children:[Math.round(pe.progress||0),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-bambu-gray",children:[pe.remaining_time!=null&&pe.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),Qs(pe.remaining_time*60)]}),i.jsxs("span",{className:"text-bambu-green font-medium",title:g("printers.estimatedCompletion"),children:["ETA ",DF(pe.remaining_time,f,g)]})]}),pe.layer_num!=null&&pe.total_layers!=null&&pe.total_layers>0&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(fi,{className:"w-3 h-3"}),pe.layer_num,"/",pe.total_layers]}),Qn&&i.jsxs("span",{className:"flex items-center gap-1",title:`Started by ${Qn}`,children:[i.jsx(td,{className:"w-3 h-3"}),Qn]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-1",children:g("printers.sort.status")}),i.jsx("p",{className:"text-white text-sm mb-2",children:i9(pe.state,pe.stg_cur_name)}),i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3",children:i.jsx("div",{className:"bg-bambu-dark-tertiary h-2 rounded-full"})}),i.jsx("span",{className:"text-bambu-gray",children:"—"})]}),En?i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 truncate",title:En.print_name||En.filename,children:["Last: ",En.print_name||En.filename,En.completed_at&&i.jsxs("span",{className:"ml-1 text-bambu-gray/60",children:["• ",mb(En.completed_at,{month:"short",day:"numeric"})]})]}):i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.readyToPrint")})]})})]})]}),i.jsx(ITe,{printerId:t.id,printerModel:t.model,printerState:pe.state,plateCleared:pe.plate_cleared})]}),pe.temperatures&&r==="expanded"&&(()=>{const xt=pe.temperatures.nozzle_heating||pe.temperatures.nozzle_2_heating||!1,Ft=pe.temperatures.bed_heating||!1,bn=pe.temperatures.chamber_heating||!1,Nt=t.nozzle_count===2||pe.temperatures.nozzle_2!==void 0,Zn=pe.active_extruder===1?"L":"R",wr=pe.nozzle_rack?.find(Va=>Va.id===1),hr=pe.nozzle_rack?.find(Va=>Va.id===0),wa=hr||wr;return i.jsxs("div",{className:"flex items-stretch gap-1.5 flex-wrap",children:[i.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[i.jsx(qj,{className:"w-3.5 h-3.5 mb-0.5",color:"text-orange-400",isHeating:xt}),pe.temperatures.nozzle_2!==void 0?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-[9px] text-bambu-gray",children:"L / R"}),i.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(pe.temperatures.nozzle||0),"° / ",Math.round(pe.temperatures.nozzle_2||0),"°"]})]}):wa?i.jsx(bne,{slot:wa,index:0,activeStatus:!0,filamentName:wa.filament_id?ge?.[wa.filament_id]?.name:void 0,children:i.jsxs("div",{className:"cursor-default",children:[i.jsx("p",{className:"text-[9px] text-bambu-gray",children:g("printers.temperatures.nozzle")}),i.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(pe.temperatures.nozzle||0),"°C"]})]})}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-[9px] text-bambu-gray",children:g("printers.temperatures.nozzle")}),i.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(pe.temperatures.nozzle||0),"°C"]})]})]}),i.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[i.jsx(qj,{className:"w-3.5 h-3.5 mb-0.5",color:"text-blue-400",isHeating:Ft}),i.jsx("p",{className:"text-[9px] text-bambu-gray",children:g("printers.temperatures.bed")}),i.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(pe.temperatures.bed||0),"°C"]})]}),pe.temperatures.chamber!==void 0&&i.jsxs("div",{className:"text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center",children:[i.jsx(qj,{className:"w-3.5 h-3.5 mb-0.5",color:"text-green-400",isHeating:bn}),i.jsx("p",{className:"text-[9px] text-bambu-gray",children:g("printers.temperatures.chamber")}),i.jsxs("p",{className:"text-[11px] text-white",children:[Math.round(pe.temperatures.chamber||0),"°C"]})]}),Nt&&i.jsx(c$e,{leftSlot:wr,rightSlot:hr,activeNozzle:Zn,filamentInfo:ge,children:i.jsxs("div",{className:"text-center px-3 py-1.5 bg-bambu-dark rounded-lg h-full flex flex-col justify-center items-center cursor-default",title:g("printers.activeNozzle",{nozzle:g(Zn==="L"?"common.left":"common.right")}),children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsxs("span",{className:`text-[11px] font-bold ${Zn==="L"?"text-amber-400":"text-gray-500"}`,children:["L",wr?.nozzle_diameter?` ${wr.nozzle_diameter}`:""]}),i.jsx("span",{className:"text-[9px] text-bambu-gray/40",children:"·"}),i.jsxs("span",{className:`text-[11px] font-bold ${Zn==="R"?"text-amber-400":"text-gray-500"}`,children:["R",hr?.nozzle_diameter?` ${hr.nozzle_diameter}`:""]})]}),i.jsx("p",{className:"text-[9px] text-bambu-gray",children:g("printers.temperatures.nozzle")})]})}),pe.nozzle_rack&&pe.nozzle_rack.some(Va=>Va.id>=2)&&i.jsx(u$e,{slots:pe.nozzle_rack,filamentInfo:ge})]})})(),r==="expanded"&&(()=>{const xt=pe.state==="RUNNING",Ft=pe.state==="PAUSE",bn=xt||Ft,Nt=ot.isPending||Ge.isPending||zt.isPending,Zn=pe.cooling_fan_speed,wr=pe.big_fan1_speed,hr=pe.big_fan2_speed;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.controls")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"flex items-center justify-between gap-2 max-[550px]:items-start",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0 max-[550px]:flex-wrap max-[550px]:items-start max-[550px]:gap-1.5",children:[i.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${Zn&&Zn>0?"bg-cyan-500/10":"bg-bambu-dark"}`,title:g("printers.fans.partCooling"),children:[i.jsx(fX,{className:`w-3.5 h-3.5 ${Zn&&Zn>0?"text-cyan-400":"text-bambu-gray/50"}`}),i.jsxs("span",{className:`text-[10px] ${Zn&&Zn>0?"text-cyan-400":"text-bambu-gray/50"}`,children:[Zn??0,"%"]})]}),i.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${wr&&wr>0?"bg-blue-500/10":"bg-bambu-dark"}`,title:g("printers.fans.auxiliary"),children:[i.jsx(kX,{className:`w-3.5 h-3.5 ${wr&&wr>0?"text-blue-400":"text-bambu-gray/50"}`}),i.jsxs("span",{className:`text-[10px] ${wr&&wr>0?"text-blue-400":"text-bambu-gray/50"}`,children:[wr??0,"%"]})]}),i.jsxs("div",{className:`flex items-center gap-1 px-1.5 py-1 rounded ${hr&&hr>0?"bg-green-500/10":"bg-bambu-dark"}`,title:g("printers.fans.chamber"),children:[i.jsx(Tde,{className:`w-3.5 h-3.5 ${hr&&hr>0?"text-green-400":"text-bambu-gray/50"}`}),i.jsxs("span",{className:`text-[10px] ${hr&&hr>0?"text-green-400":"text-bambu-gray/50"}`,children:[hr??0,"%"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 max-[550px]:self-start",children:[i.jsxs("button",{onClick:()=>Z(!0),disabled:!bn||Nt||!k("printers:control"),className:`
  8152. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  8153. transition-colors
  8154. ${bn&&k("printers:control")?"bg-red-500/20 text-red-400 hover:bg-red-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}
  8155. `,title:k("printers:control")?g("printers.stop"):g("printers.permission.noControl"),children:[i.jsx(vl,{className:"w-3 h-3"}),g("printers.stop")]}),i.jsxs("button",{onClick:()=>Ft?je(!0):ce(!0),disabled:!bn||Nt||!k("printers:control"),className:`
  8156. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  8157. transition-colors
  8158. ${bn&&k("printers:control")?Ft?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}
  8159. `,title:k("printers:control")?g(Ft?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ft?i.jsx(io,{className:"w-3 h-3"}):i.jsx(YC,{className:"w-3 h-3"}),g(Ft?"printers.resume":"printers.pause")]})]})]})]})})(),(ht?.length>0||pe.vt_tray.length>0)&&r==="expanded"&&(()=>{const xt=ht.filter(Nt=>Nt.tray.length>1),Ft=ht.filter(Nt=>Nt.tray.length===1),bn=t.nozzle_count===2||pe?.temperatures?.nozzle_2!==void 0;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"space-y-3",children:[xt.length>0&&i.jsx("div",{className:"grid grid-cols-2 gap-3",children:xt.map(Nt=>{const Zn=Re[String(Nt.id)],wr=Nt.id>=128?Nt.id-128:Nt.id,hr=Zn!==void 0?Zn:wr,wa=hr===1,Va=hr===0;return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"text-[10px] text-white font-medium",children:th(Nt.id,Nt.tray.length)}),bn&&(wa||Va)&&i.jsx(t9,{side:wa?"L":"R"})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[Nt.humidity!=null&&i.jsx(r9,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ie({amsId:Nt.id,amsLabel:th(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0}),Nt.temp!=null&&i.jsx(a9,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ie({amsId:Nt.id,amsLabel:th(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(Vt=>{const xn=Nt.tray[Vt]||Nt.tray.find(Ht=>Ht.id===Vt),Ss=xn?.tray_type&&xn.remain>=0,Ci=!xn?.tray_type,ns=Nt.id*4+Vt,Tl=It===ns,rs=xn?.tray_info_idx?ge?.[xn.tray_info_idx]:null,oi=we?.[ns],Sa=xn?.tray_uuid?.toUpperCase(),Qr=Sa?c?.[Sa]:void 0,mr=Wj(Qr),ho=d?.(t.id,Nt.id,Vt),qa=(()=>{const Ht=ho?.spool;return Ht&&Ht.label_weight>0&&Ht.weight_used!=null?Math.round(Math.max(0,Ht.label_weight-Ht.weight_used)/Ht.label_weight*100):null})(),Oa=Ss&&xn.remain>0?xn.remain:mr??qa??(Ss?xn.remain:null),mo=Ss&&xn.remain===0&&(mr!==null||qa!==null)?mr!==null?"spoolman":"inventory":"ams",Ur=xn?.tray_type?{vendor:Kj(xn)?"Bambu Lab":"Generic",profile:rs?.name||oi?.preset_name||xn.tray_sub_brands||xn.tray_type,colorName:Hj(xn.tray_id_name)||$j(xn.tray_color),colorHex:xn.tray_color||null,kFactor:Vj(xn.k),fillLevel:Oa,trayUuid:xn.tray_uuid||null,tagUid:xn.tag_uid||null,fillSource:mo}:null,fa=Te?.amsId===Nt.id&&Te?.slotId===Vt,Us=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ci?"opacity-50":""} ${Tl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:xn?.tray_color?`#${xn.tray_color}`:xn?.tray_type?"#333":"transparent",borderColor:Ci?"#666":"rgba(255,255,255,0.1)",borderStyle:Ci?"dashed":"solid"}}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:xn?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Oa!==null&&Oa>=0&&xn?i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Oa}%`,backgroundColor:Gj(Oa)}}):xn?.tray_type?i.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return i.jsxs("div",{className:"relative group",children:[fa&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Ar,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&i.jsx("button",{onClick:Ht=>{Ht.stopPropagation(),Sn(ia?.amsId===Nt.id&&ia?.slotId===Vt?null:{amsId:Nt.id,slotId:Vt})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&ia?.amsId===Nt.id&&ia?.slotId===Vt&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Ht=>{Ht.stopPropagation(),k("printers:ams_rfid")&&($t.mutate({amsId:Nt.id,slotId:Vt}),Sn(null))},disabled:fa||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Ar,{className:`w-3 h-3 ${fa?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Ur?i.jsx(Uj,{data:Ur,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ur.trayUuid?c?.[Ur.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Ur.trayUuid?Ht=>{V({tagUid:Ur.tagUid||"",trayUuid:Ht,printerId:t.id,amsId:Nt.id,trayId:Vt})}:void 0},inventory:o?void 0:(()=>{const Ht=d?.(t.id,Nt.id,Vt);return{assignedSpool:Ht?.spool?{id:Ht.spool.id,material:Ht.spool.material,brand:Ht.spool.brand,color_name:Ht.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Ht.spool.label_weight-Ht.spool.weight_used))}:null,onAssignSpool:Ur.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:Nt.id,trayId:Vt,trayInfo:{type:Ur.profile,color:Ur.colorHex||"",location:`${th(Nt.id,Nt.tray.length)} Slot ${Vt+1}`}}):void 0,onUnassignSpool:Ht&&Ur.vendor!=="Bambu Lab"?()=>h?.(t.id,Nt.id,Vt):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:Nt.id,trayId:Vt,trayCount:Nt.tray.length,trayType:xn?.tray_type||void 0,trayColor:xn?.tray_color||void 0,traySubBrands:xn?.tray_sub_brands||void 0,trayInfoIdx:xn?.tray_info_idx||void 0,extruderId:Zn,caliIdx:xn?.cali_idx,savedPresetId:oi?.preset_id})},children:Us}):i.jsx(Bj,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:Nt.id,trayId:Vt,trayCount:Nt.tray.length,extruderId:Zn})},children:Us})]},Vt)})})]},Nt.id)})}),(Ft.length>0||pe.vt_tray.length>0)&&i.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ft.map(Nt=>{const Zn=Re[String(Nt.id)],wr=Nt.id>=128?Nt.id-128:Nt.id,hr=Zn!==void 0?Zn:wr,wa=hr===1,Va=hr===0,Vt=Nt.tray[0],xn=Vt?.tray_type&&Vt.remain>=0,Ss=!Vt?.tray_type,Ci=f4(Nt.id,Vt?.id??0,!1),ns=It===Ci,Tl=Vt?.tray_info_idx?ge?.[Vt.tray_info_idx]:null,rs=we?.[Ci],oi=Vt?.tray_uuid?.toUpperCase(),Sa=oi?c?.[oi]:void 0,Qr=Wj(Sa),mr=Vt?.id??0,ho=d?.(t.id,Nt.id,mr),qa=(()=>{const Vn=ho?.spool;return Vn&&Vn.label_weight>0&&Vn.weight_used!=null?Math.round(Math.max(0,Vn.label_weight-Vn.weight_used)/Vn.label_weight*100):null})(),Oa=xn&&Vt.remain>0?Vt.remain:Qr??qa??(xn?Vt.remain:null),mo=xn&&Vt.remain===0&&(Qr!==null||qa!==null)?Qr!==null?"spoolman":"inventory":"ams",Ur=Vt?.tray_type?{vendor:Kj(Vt)?"Bambu Lab":"Generic",profile:Tl?.name||rs?.preset_name||Vt.tray_sub_brands||Vt.tray_type,colorName:Hj(Vt.tray_id_name)||$j(Vt.tray_color),colorHex:Vt.tray_color||null,kFactor:Vj(Vt.k),fillLevel:Oa,trayUuid:Vt.tray_uuid||null,tagUid:Vt.tag_uid||null,fillSource:mo}:null,fa=Vt?.id??0,Us=Te?.amsId===Nt.id&&Te?.slotId===fa,Ht=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ss?"opacity-50":""} ${ns?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Vt?.tray_color?`#${Vt.tray_color}`:Vt?.tray_type?"#333":"transparent",borderColor:Ss?"#666":"rgba(255,255,255,0.1)",borderStyle:Ss?"dashed":"solid"}}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Vt?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Oa!==null&&Oa>=0?i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Oa}%`,backgroundColor:Gj(Oa)}}):Vt?.tray_type?i.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx("span",{className:"text-[10px] text-white font-medium",children:th(Nt.id,Nt.tray.length)}),bn&&(wa||Va)&&i.jsx(t9,{side:wa?"L":"R"})]}),i.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[i.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Us&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Ar,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&i.jsx("button",{onClick:Vn=>{Vn.stopPropagation(),Sn(ia?.amsId===Nt.id&&ia?.slotId===fa?null:{amsId:Nt.id,slotId:fa})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&ia?.amsId===Nt.id&&ia?.slotId===fa&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Vn=>{Vn.stopPropagation(),k("printers:ams_rfid")&&($t.mutate({amsId:Nt.id,slotId:fa}),Sn(null))},disabled:Us||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Ar,{className:`w-3 h-3 ${Us?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Ur?i.jsx(Uj,{data:Ur,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ur.trayUuid?c?.[Ur.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Ur.trayUuid?Vn=>{V({tagUid:Ur.tagUid||"",trayUuid:Vn,printerId:t.id,amsId:Nt.id,trayId:fa})}:void 0},inventory:o?void 0:(()=>{const Vn=d?.(t.id,Nt.id,fa);return{assignedSpool:Vn?.spool?{id:Vn.spool.id,material:Vn.spool.material,brand:Vn.spool.brand,color_name:Vn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Vn.spool.label_weight-Vn.spool.weight_used))}:null,onAssignSpool:Ur.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:Nt.id,trayId:fa,trayInfo:{type:Ur.profile,color:Ur.colorHex||"",location:th(Nt.id,Nt.tray.length)}}):void 0,onUnassignSpool:Vn&&Ur.vendor!=="Bambu Lab"?()=>h?.(t.id,Nt.id,fa):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:Nt.id,trayId:fa,trayCount:Nt.tray.length,trayType:Vt?.tray_type||void 0,trayColor:Vt?.tray_color||void 0,traySubBrands:Vt?.tray_sub_brands||void 0,trayInfoIdx:Vt?.tray_info_idx||void 0,extruderId:Zn,caliIdx:Vt?.cali_idx,savedPresetId:rs?.preset_id})},children:Ht}):i.jsx(Bj,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:Nt.id,trayId:fa,trayCount:Nt.tray.length,extruderId:Zn})},children:Ht})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[Nt.temp!=null&&i.jsx(a9,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>ie({amsId:Nt.id,amsLabel:th(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0}),Nt.humidity!=null&&i.jsx(r9,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>ie({amsId:Nt.id,amsLabel:th(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0})]})]})]},Nt.id)}),pe.vt_tray.length>0&&i.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${pe.vt_tray.length===1?"max-w-[50%]":""}`,children:[i.jsx("div",{className:"flex items-center gap-1 mb-2",children:i.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),i.jsx("div",{className:`grid ${pe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...pe.vt_tray].sort((Nt,Zn)=>(Nt.id??254)-(Zn.id??254)).map(Nt=>{const Zn=Nt.id??254,wr=It===Zn,hr=Zn-254,wa=bn?g(Zn===254?"printers.extL":"printers.extR"):"",Va=Nt.tray_info_idx?ge?.[Nt.tray_info_idx]:null,Vt=we?.[1020+hr],xn=Nt.tray_uuid?.toUpperCase(),Ss=xn?c?.[xn]:void 0,Ci=Wj(Ss),ns=d?.(t.id,255,hr),Tl=(()=>{const mr=ns?.spool;return mr&&mr.label_weight>0&&mr.weight_used!=null?Math.round(Math.max(0,mr.label_weight-mr.weight_used)/mr.label_weight*100):null})(),rs=Ci??Tl??null,oi={vendor:Kj(Nt)?"Bambu Lab":"Generic",profile:Va?.name||Vt?.preset_name||Nt.tray_sub_brands||Nt.tray_type||"Unknown",colorName:Hj(Nt.tray_id_name)||$j(Nt.tray_color),colorHex:Nt.tray_color||null,kFactor:Vj(Nt.k),fillLevel:rs,trayUuid:Nt.tray_uuid||null,tagUid:Nt.tag_uid||null,fillSource:Ci!==null?"spoolman":Tl!==null?"inventory":void 0},Sa=!Nt.tray_type,Qr=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Sa?"opacity-50":""} ${wr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Nt.tray_color?`#${Nt.tray_color}`:Nt.tray_type?"#333":"transparent",borderColor:Sa?"#666":"rgba(255,255,255,0.1)",borderStyle:Sa?"dashed":"solid"}}),i.jsx("div",{className:`text-[9px] font-bold truncate ${Sa?"text-white/40":"text-white"}`,children:Nt.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:rs!==null&&rs>=0&&!Sa?i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${rs}%`,backgroundColor:Gj(rs)}}):Sa?null:i.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"})}),wa&&i.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:wa})]});return i.jsx("div",{className:"relative group",children:Sa?i.jsx(Bj,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:255,trayId:hr,trayCount:1,extruderId:bn?Zn===254?1:0:void 0})},children:Qr}):i.jsx(Uj,{data:oi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:oi.trayUuid?c?.[oi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&oi.trayUuid?mr=>{V({tagUid:oi.tagUid||"",trayUuid:mr,printerId:t.id,amsId:255,trayId:hr})}:void 0},inventory:o?void 0:(()=>{const mr=d?.(t.id,255,hr);return{assignedSpool:mr?.spool?{id:mr.spool.id,material:mr.spool.material,brand:mr.spool.brand,color_name:mr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(mr.spool.label_weight-mr.spool.weight_used))}:null,onAssignSpool:()=>me({printerId:t.id,amsId:255,trayId:hr,trayInfo:{type:oi.profile,color:oi.colorHex||"",location:wa||g("printers.external")}}),onUnassignSpool:mr?()=>h?.(t.id,255,hr):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>se({amsId:255,trayId:hr,trayCount:1,trayType:Nt.tray_type||void 0,trayColor:Nt.tray_color||void 0,traySubBrands:Nt.tray_sub_brands||void 0,trayInfoIdx:Nt.tray_info_idx||void 0,extruderId:bn?Zn===254?1:0:void 0,caliIdx:Nt.cali_idx,savedPresetId:Vt?.preset_id})},children:Qr})},Zn)})})]})]})]})]})})()]}),kt&&r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(nd,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-sm text-white truncate",children:kt.name}),bt&&i.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${bt.state==="ON"?"bg-bambu-green/20 text-bambu-green":bt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[bt.state||"?",bt.state==="ON"&&bt.energy?.power!=null&&i.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",bt.energy.power,"W"]})]})]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{onClick:()=>W(!0),disabled:Fe.isPending||bt?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?bt?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(md,{className:"w-3 h-3"}),"On"]}),i.jsxs("button",{onClick:()=>ae(!0),disabled:Fe.isPending||bt?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?bt?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(QC,{className:"w-3 h-3"}),"Off"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:`text-xs hidden sm:inline ${kt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:kt.auto_off_executed?"Auto-off done":"Auto-off"}),i.jsx("button",{onClick:()=>Se.mutate(!kt.auto_off),disabled:Se.isPending||kt.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?kt.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?kt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":kt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:i.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${kt.auto_off||kt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ue&&Ue.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[i.jsx(d0,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Ue.map(xt=>i.jsxs("button",{onClick:()=>nt.mutate(xt.id),disabled:nt.isPending,title:`Run ${xt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[i.jsx(io,{className:"w-2.5 h-2.5"}),xt.name]},xt.id))})]})]}),r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[i.jsxs("div",{className:"text-xs text-bambu-gray",children:[i.jsx("p",{children:t.ip_address}),i.jsx("p",{className:"truncate",children:t.serial_number})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>ye.mutate(!pe?.chamber_light),disabled:!pe?.connected||ye.isPending||!k("printers:control"),title:k("printers:control")?pe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:pe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:i.jsx(lL,{on:pe?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const xt=localStorage.getItem("cameraWindowState"),Ft=xt?JSON.parse(xt):{width:640,height:400},bn=[`width=${Ft.width}`,`height=${Ft.height}`,Ft.left!==void 0?`left=${Ft.left}`:"",Ft.top!==void 0?`top=${Ft.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,bn)}},disabled:!pe?.connected,title:g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:i.jsx(PF,{className:"w-4 h-4"})}),i.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:kn,disabled:!pe?.connected||He.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:He.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(C1,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:Dn,disabled:!pe?.connected||O||!k("printers:update"),title:k("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:O?i.jsx(it,{className:"w-3 h-3 animate-spin"}):i.jsx(Pn,{className:"w-3 h-3"})})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!k("printers:files"),title:k("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[i.jsx(Vb,{className:"w-4 h-4"}),"Files"]})]})]})]}),B&&i.jsx(ATe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&i.jsx(DTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Ne&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Xt(),children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:xt=>xt.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[Ne.needs_calibration?i.jsx(C1,{className:"w-5 h-5 text-blue-500"}):Ne.is_empty?i.jsx(pr,{className:"w-5 h-5 text-green-500"}):i.jsx(mi,{className:"w-5 h-5 text-yellow-500"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Ne.reference_count!==void 0&&Ne.max_references&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Ne.reference_count,"/",Ne.max_references," refs"]})]}),i.jsx("button",{onClick:()=>Xt(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[Ne.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[i.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),i.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[i.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),i.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`p-3 rounded-lg ${Ne.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[i.jsx("p",{className:`font-medium ${Ne.is_empty?"text-green-400":"text-yellow-400"}`,children:Ne.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),i.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Ne.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Ne.difference_percent.toFixed(1),"%"]})]}),Ne.debug_image_url&&i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),i.jsx("img",{src:Ne.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:Ne.message})]}),Rt&&Rt.references.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:Rt.references.length,max:Rt.max_references})}),i.jsx("div",{className:"grid grid-cols-5 gap-2",children:Rt.references.map(xt=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ne.getPlateReferenceThumbnailUrl(t.id,xt.index),alt:xt.label||`Reference ${xt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),i.jsx("button",{onClick:()=>Gr(xt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:i.jsx(Lt,{className:"w-3 h-3 text-white"})}),sn?.index===xt.index?i.jsx("input",{type:"text",value:sn.label,onChange:Ft=>Zt({...sn,label:Ft.target.value}),onBlur:()=>fn(xt.index,sn.label),onKeyDown:Ft=>{Ft.key==="Enter"&&fn(xt.index,sn.label),Ft.key==="Escape"&&Zt(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Zt({index:xt.index,label:xt.label}),title:xt.label?g("printers.plateDetection.clickToEdit",{label:xt.label}):g("printers.plateDetection.clickToAddLabel"),children:xt.label||i.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),i.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:xt.timestamp?new Date(xt.timestamp).toLocaleDateString():""})]},xt.index))})]}),!Ne.needs_calibration&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),fe?i.jsxs("div",{className:"flex gap-1",children:[i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>le(null),disabled:Be,children:g("common.cancel")}),i.jsx(Ce,{size:"sm",onClick:pn,disabled:Be,children:Be?i.jsx(it,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>le(Ne.roi||{x:.15,y:.35,w:.7,h:.55}),children:[i.jsx($a,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),fe?i.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:fe.x,onChange:xt=>le({...fe,x:parseFloat(xt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(fe.x*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:fe.y,onChange:xt=>le({...fe,y:parseFloat(xt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(fe.y*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:fe.w,onChange:xt=>le({...fe,w:parseFloat(xt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(fe.w*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:fe.h,onChange:xt=>le({...fe,h:parseFloat(xt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(fe.h*100),"%"]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Ne.roi?.x||.15)*100),"%, Y=",Math.round((Ne.roi?.y||.35)*100),"%, W=",Math.round((Ne.roi?.w||.7)*100),"%, H=",Math.round((Ne.roi?.h||.55)*100),"%"]})]})]}),i.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Ne.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsx(Ce,{variant:"ghost",onClick:()=>Xt(),children:g("common.cancel")}),i.jsx(Ce,{onClick:()=>mn(),disabled:q,children:q?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ce,{variant:"ghost",onClick:()=>mn(),disabled:q,children:q?"Adding...":`Add Reference (${Rt?.references.length||0}/${Rt?.max_references||5})`}),i.jsx(Ce,{onClick:()=>Xt(),children:"Close"})]})})]})}),z&&kt&&i.jsx(gn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Fe.mutate("on"),W(!1)},onCancel:()=>W(!1)}),X&&kt&&i.jsx(gn,{title:g("printers.confirm.powerOffTitle"),message:pe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Fe.mutate("off"),ae(!1)},onCancel:()=>ae(!1)}),te&&i.jsx(gn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{ot.mutate(),Z(!1)},onCancel:()=>Z(!1)}),ve&&i.jsx(gn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Ge.mutate(),ce(!1)},onCancel:()=>ce(!1)}),ee&&i.jsx(gn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{zt.mutate(),je(!1)},onCancel:()=>je(!1)}),i.jsx(cL,{printerId:t.id,isOpen:he,onClose:()=>oe(!1)}),H&&i.jsx(OTe,{printerName:t.name,errors:pe?.hms_errors||[],onClose:()=>K(!1),printerId:t.id,hasPermission:k}),_e&&i.jsx(XHe,{isOpen:!!_e,onClose:()=>ie(null),printerId:t.id,printerName:t.name,amsId:_e.amsId,amsLabel:_e.amsLabel,initialMode:_e.mode,thresholds:s}),ze&&i.jsx(YHe,{isOpen:!!ze,onClose:()=>V(null),tagUid:ze.tagUid,trayUuid:ze.trayUuid,printerId:ze.printerId,amsId:ze.amsId,trayId:ze.trayId}),Y&&i.jsx(QHe,{isOpen:!!Y,onClose:()=>me(null),printerId:Y.printerId,amsId:Y.amsId,trayId:Y.trayId,trayInfo:Y.trayInfo}),Q&&i.jsx(s$e,{isOpen:!!Q,onClose:()=>se(null),printerId:t.id,slotInfo:Q,printerModel:xR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),U&&i.jsx(S$e,{printer:t,onClose:()=>L(!1)}),de&&xe&&i.jsx(w$e,{printer:t,firmwareInfo:xe,onClose:()=>Le(!1)}),ia&&i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Sn(null)})]})}function v$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Ot(),[a,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,u]=w.useState([]),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[k,A]=w.useState({scanned:0,total:0});w.useEffect(()=>{dc.getInfo().then(P=>{v(P.is_docker),P.subnets.length>0&&(y(P.subnets),N(P.subnets[0]))}).catch(()=>{})},[]);const M=c.filter(P=>!n.includes(P.serial)),C=async()=>{h(""),u([]),l(!0),p(!1),A({scanned:0,total:0});try{if(x){await dc.startSubnetScan(_);const P=setInterval(async()=>{try{const E=await dc.getScanStatus();A({scanned:E.scanned,total:E.total});const U=await dc.getDiscoveredPrinters();u(U),E.running||(clearInterval(P),l(!1),p(!0))}catch(E){console.error("Failed to get scan status:",E)}},500)}else{await dc.startDiscovery(10);const P=setInterval(async()=>{try{const E=await dc.getDiscoveredPrinters();u(E)}catch(E){console.error("Failed to get discovered printers:",E)}},1e3);setTimeout(async()=>{clearInterval(P);try{await dc.stopDiscovery()}catch{}l(!1),p(!0);try{const E=await dc.getDiscoveredPrinters();u(E)}catch(E){console.error("Failed to get final discovered printers:",E)}},1e4)}}catch(P){console.error("Failed to start discovery:",P),h(P instanceof Error?P.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},j=P=>{const E=P.serial.startsWith("unknown-")?"":P.serial;s({...a,name:P.name||"",serial_number:E,ip_address:P.ip_address,model:xR(P.model)}),u([])};return w.useEffect(()=>()=>{dc.stopDiscovery().catch(()=>{}),dc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const P=E=>{E.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:i.jsx(wt,{className:"w-full max-w-md",onClick:P=>P.stopPropagation(),children:i.jsxs(_t,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),i.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.length>0?i.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:P=>N(P.target.value),disabled:o,children:g.map(P=>i.jsx("option",{value:P,children:P},P))}):i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:P=>N(P.target.value),placeholder:"192.168.1.0/24",disabled:o}),i.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),i.jsx(Ce,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),x&&k.total>0?r("printers.discovery.scanProgress",{scanned:k.scanned,total:k.total}):r("printers.discovery.scanning")]}):i.jsxs(i.Fragment,{children:[i.jsx(xr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&i.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),M.length>0&&i.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:M.map(P=>i.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>j(P),children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-white text-sm truncate",children:P.name||P.serial}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[xR(P.model)||r("printers.discovery.unknown")," • ",P.ip_address,P.serial.startsWith("unknown-")&&i.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),i.jsx(Pn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},P.serial))}),o&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&M.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),i.jsxs("form",{onSubmit:P=>{P.preventDefault(),e(a)},className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),i.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.name,onChange:P=>s({...a,name:P.target.value}),placeholder:r("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.ip_address,onChange:P=>s({...a,ip_address:P.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),i.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.serial_number,onChange:P=>s({...a,serial_number:P.target.value}),placeholder:"01P00A000000000"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),i.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.access_code,onChange:P=>s({...a,access_code:P.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),i.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.model||"",onChange:P=>s({...a,model:P.target.value}),children:[i.jsx("option",{value:"",children:r("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:a.location||"",onChange:P=>s({...a,location:P.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"auto_archive",checked:a.auto_archive,onChange:P=>s({...a,auto_archive:P.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsx(Ce,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function w$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Ot(),a=en(),{showToast:s}=an(),{hasPermission:o}=Ir(),l=o("firmware:update"),[c,u]=w.useState(null),[d,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Je({queryKey:["firmwarePrepare",t.id],queryFn:()=>$_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=st({mutationFn:()=>$_.startUpload(t.id),onSuccess:()=>{h(!0);const _=setInterval(async()=>{try{const N=await $_.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),a.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{u(null),g.mutate()};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(wt,{className:"w-full max-w-md mx-4",children:i.jsxs(_t,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?i.jsx(da,{className:"w-5 h-5 text-orange-400"}):i.jsx(pr,{className:"w-5 h-5 text-status-ok"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),i.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&i.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),i.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&i.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[i.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),i.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!d&&!c?i.jsx("div",{className:"mb-4",children:x.can_proceed?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[i.jsx(Ja,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):i.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Ba,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(d||c)&&c&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),i.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&i.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),i.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),i.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Ce,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!d&&c?.status!=="complete"&&l&&i.jsx(Ce,{onClick:y,disabled:g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):i.jsxs(i.Fragment,{children:[i.jsx(da,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function S$e({printer:t,onClose:e}){const{t:n}=Ot(),r=en(),{showToast:a}=an(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=st({mutationFn:u=>ne.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>a(u.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const u=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const c=u=>{u.preventDefault();const d={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(d.access_code=s.access_code),l.mutate(d)};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsx(wt,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:i.jsxs(_t,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),i.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:u=>o({...s,name:u.target.value}),placeholder:n("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:u=>o({...s,ip_address:u.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),i.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),i.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:u=>o({...s,access_code:u.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),i.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:u=>o({...s,model:u.target.value}),children:[i.jsx("option",{value:"",children:n("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:u=>o({...s,location:u.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:u=>o({...s,auto_archive:u.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),i.jsx(Ce,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function _$e(t){const{data:e}=Je({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function N$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const a=_$e(t.id),{data:s}=Je({queryKey:["smartPlugStatus",e.id],queryFn:()=>ne.getSmartPlugStatus(e.id),refetchInterval:1e4});return a?i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),i.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[i.jsx(md,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function C$e(){const{t}=Ot(),[e,n]=w.useState(!1),[r,a]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const oe=localStorage.getItem("printerCardSize");return oe?parseInt(oe,10):2}),v=p===1?"compact":"expanded",g=en(),{showToast:y}=an(),{hasPermission:_}=Ir(),[N,k]=w.useState(()=>{const oe=localStorage.getItem("openEmbeddedCameras");if(oe)try{const _e=JSON.parse(oe);return new Map(_e.map(ie=>[ie.id,ie]))}catch{return new Map}return new Map});w.useEffect(()=>{const oe=Array.from(N.values());oe.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(oe)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:A,isLoading:M}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:C}=Je({queryKey:["settings"],queryFn:ne.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&k(new Map)},[C?.camera_view_mode,N.size]);const{data:j}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:P}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview,staleTime:60*1e3}),{data:E}=Je({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),U=E?.enabled&&E?.connected,{data:L}=Je({queryKey:["unlinked-spools"],queryFn:ne.getUnlinkedSpools,enabled:!!U,staleTime:30*1e3}),B=L&&L.length>0,{data:D}=Je({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!U,staleTime:30*1e3}),$=D?.linked,{data:G}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),staleTime:30*1e3}),z=st({mutationFn:({printerId:oe,amsId:_e,trayId:ie})=>ne.unassignSpool(oe,_e,ie),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(oe,_e,ie)=>G?.find(ze=>ze.printer_id===oe&&ze.ams_id===Number(_e)&&ze.tray_id===Number(ie)),X=P?.reduce((oe,_e)=>(oe[_e.printer_id]={due_count:_e.due_count,warning_count:_e.warning_count,total_print_hours:_e.total_print_hours},oe),{})||{},ae=j?.reduce((oe,_e)=>(_e.printer_id&&(oe[_e.printer_id]=_e),oe),{})||{},H=st({mutationFn:ne.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:oe=>y(oe.message||t("printers.toast.failedToAdd"),"error")}),K=st({mutationFn:oe=>ne.controlSmartPlug(oe,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),te=()=>{const oe=!r;a(oe),localStorage.setItem("hideDisconnectedPrinters",String(oe))},Z=oe=>{d(oe),localStorage.setItem("printerSortBy",oe)},ve=()=>{const oe=!h;f(oe),localStorage.setItem("printerSortAsc",String(oe))},ce=()=>{switch(p){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},ee=["S","M","L","XL"],je=w.useMemo(()=>{if(!A)return[];const oe=[...A];switch(u){case"name":oe.sort((_e,ie)=>_e.name.localeCompare(ie.name));break;case"model":oe.sort((_e,ie)=>(_e.model||"").localeCompare(ie.model||""));break;case"location":oe.sort((_e,ie)=>{const ze=_e.location||"",V=ie.location||"";return!ze&&V?1:ze&&!V?-1:ze.localeCompare(V)||_e.name.localeCompare(ie.name)});break;case"status":oe.sort((_e,ie)=>{const ze=g.getQueryData(["printerStatus",_e.id]),V=g.getQueryData(["printerStatus",ie.id]),Y=me=>me?.connected?me.state==="RUNNING"?0:1:2;return Y(ze)-Y(V)});break}return h||oe.reverse(),oe},[A,u,h,g]),he=w.useMemo(()=>{if(u!=="location")return null;const oe={};return je.forEach(_e=>{const ie=_e.location||"Ungrouped";oe[ie]||(oe[ie]=[]),oe[ie].push(_e)}),oe},[u,je]);return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),i.jsx(y$e,{printers:A})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("select",{value:u,onChange:oe=>Z(oe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"name",children:t("printers.sort.name")}),i.jsx("option",{value:"status",children:t("printers.sort.status")}),i.jsx("option",{value:"model",children:t("printers.sort.model")}),i.jsx("option",{value:"location",children:t("printers.sort.location")})]}),i.jsx("button",{onClick:ve,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?i.jsx(Mf,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(lb,{className:"w-4 h-4 text-bambu-gray"})})]}),i.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:ee.map((oe,_e)=>{const ie=_e+1,ze=p===ie;return i.jsx("button",{onClick:()=>{x(ie),localStorage.setItem("printerCardSize",String(ie))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${_e===0?"rounded-l-lg":""} ${_e===ee.length-1?"rounded-r-lg":""} ${ze?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(oe==="S"?"printers.cardSize.small":oe==="M"?"printers.cardSize.medium":oe==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:oe},oe)})}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:te,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(ae).length>0&&i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(md,{className:"w-4 h-4"}),t("printers.powerOn"),i.jsx(Pn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),i.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[i.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),A?.filter(oe=>ae[oe.id]).map(oe=>i.jsx(N$e,{printer:oe,plug:ae[oe.id],onPowerOn:_e=>{c(_e),K.mutate(_e)},isPowering:l===ae[oe.id]?.id},oe.id)),A?.filter(oe=>ae[oe.id]).length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),i.jsxs(Ce,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(Gn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),M?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):A?.length===0?i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),i.jsxs(Ce,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(Gn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):he?i.jsx("div",{className:"space-y-6",children:Object.entries(he).map(([oe,_e])=>i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),oe,i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",_e.length,")"]})]}),i.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${ce()}`,children:_e.map(ie=>i.jsx(s9,{printer:ie,hideIfDisconnected:r,maintenanceInfo:X[ie.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(ze,V,Y)=>z.mutate({printerId:ze,amsId:V,trayId:Y}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(ze,V)=>k(Y=>new Map(Y).set(ze,{id:ze,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},ie.id))})]},oe))}):i.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${ce()}`,children:je.map(oe=>i.jsx(s9,{printer:oe,hideIfDisconnected:r,maintenanceInfo:X[oe.id],viewMode:v,cardSize:p,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(_e,ie,ze)=>z.mutate({printerId:_e,amsId:ie,trayId:ze}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(_e,ie)=>k(ze=>new Map(ze).set(_e,{id:_e,name:ie})),checkPrinterFirmware:C?.check_printer_firmware!==!1},oe.id))}),e&&i.jsx(v$e,{onClose:()=>n(!1),onAdd:oe=>H.mutate(oe),existingSerials:A?.map(oe=>oe.serial_number)||[]}),Array.from(N.values()).map((oe,_e)=>i.jsx(jTe,{printerId:oe.id,printerName:oe.name,viewerIndex:_e,onClose:()=>k(ie=>{const ze=new Map(ie);return ze.delete(oe.id),ze})},oe.id))]})}function k$e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:k$e()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const A$e={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function rl(t){return A$e[t.toUpperCase()]||t}const T$e=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}],o9=768;function xne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth<o9:!1);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${o9-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function g4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:a}){const{t:s}=Ot(),{data:o}=Je({queryKey:["settings"],queryFn:ne.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,k]=w.useState(null),[A,M]=w.useState(0),[C,j]=w.useState(!1),[P,E]=w.useState(null),[U,L]=w.useState(!1),[B,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),z=10,W=160,X=240,ae=.35;w.useEffect(()=>{const Ne=be=>{be.key==="Escape"&&a()};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[a]),w.useEffect(()=>{if(x(!0),c){const Ne=(r||"").toLowerCase(),be=Ne==="3mf"||Ne==="stl",O=Ne==="gcode"||Ne==="3mf";f({has_model:be,has_gcode:O,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(be?"3d":O?"gcode":null),x(!1);return}if(!t){f(null),d(null),x(!1);return}ne.getArchiveCapabilities(t).then(Ne=>{f(Ne),Ne.has_model?d("3d"):Ne.has_gcode&&d("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),k(null),M(0),c){const Ne=(r||"").toLowerCase();if(!e||Ne!=="3mf"){g(null),_(!1);return}ne.getLibraryFilePlates(e).then(be=>g(be)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}ne.getArchivePlates(t).then(Ne=>g(Ne)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),K=(v?.is_multi_plate??!1)&&H.length>1,te=C&&K,Z=N==null?null:H.find(Ne=>Ne.index===N)??null,ve=Ne=>Ne.object_count??Ne.objects?.length??0,ce=H.reduce((Ne,be)=>Ne+ve(be),0),ee=Z?ve(Z):ce,je=Z?s("modelViewer.plateNumber",{number:Z.index}):s("modelViewer.allPlates"),he=H.length>0,oe=w.useRef(null),_e=w.useRef(null),[ie,ze]=w.useState(10),[V,Y]=w.useState(3),me=H.length>ie,Q=Math.max(1,Math.ceil(H.length/ie)),se=me?H.slice(A*ie,(A+1)*ie):H;w.useEffect(()=>{if(!te){ze(10),Y(3);return}const Ne=oe.current,be=_e.current;if(!Ne||!be)return;let O=0;const R=()=>{const fe=be.clientWidth,Be=Math.floor(fe/210),Ie=Math.max(3,Math.min(5,Be||3));Y(Ee=>Ee===Ie?Ee:Ie);const Ke=window.getComputedStyle(Ne),Oe=Number.parseFloat(Ke.rowGap||"0"),xe=Ne.querySelector("button")?.getBoundingClientRect().height??44,ke=be.clientHeight,we=Math.max(1,Math.floor((ke+Oe)/(xe+Oe)))*Ie,qe=Math.max(1,we-1);ze(Ee=>Ee===qe?Ee:qe)},q=()=>{O&&cancelAnimationFrame(O),O=requestAnimationFrame(R)};q();const J=new ResizeObserver(q);return J.observe(be),J.observe(Ne),()=>{O&&cancelAnimationFrame(O),J.disconnect()}},[te,H.length]),w.useEffect(()=>{if(!me){M(0);return}M(Ne=>Math.min(Ne,Q-1))},[H.length,me,Q]),w.useEffect(()=>{if(!me||N==null)return;const Ne=H.findIndex(O=>O.index===N);if(Ne<0)return;const be=Math.floor(Ne/ie);M(O=>O===be?O:be)},[H,ie,N,me]),w.useEffect(()=>{if(!te){E(null),D(!1);return}if(B)return;const Ne=$.current,be=G.current;if(!Ne||!be)return;const O=Ne.clientHeight;if(!O)return;const R=Math.max(X,O*ae),q=Math.max(W,O-z-R),J=Math.min(be.scrollHeight,q);E(Math.max(W,J))},[te,B,H.length,A,z,W,X,ae]),w.useEffect(()=>{if(!U)return;const Ne=O=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),J=q.height;if(!J)return;const fe=Math.max(X,J*ae),le=Math.max(W,J-z-fe),Be=Math.min(le,Math.max(W,O.clientY-q.top));E(Be)},be=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",Ne),document.addEventListener("mouseup",be),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Ne),document.removeEventListener("mouseup",be),document.body.style.cursor="",document.body.style.userSelect=""}},[U,z,W,X,ae]);const de=c?(r||"").toLowerCase()==="3mf":!0,Le=async()=>{if(!de)return;const Ne=n||"model";try{if(c){const{token:be}=await ne.createLibrarySlicerToken(e),O=ne.getLibrarySlicerDownloadUrl(e,be,Ne);of(`${window.location.origin}${O}`,l)}else{const{token:be}=await ne.createArchiveSlicerToken(t),O=ne.getArchiveSlicerDownloadUrl(t,be,Ne);of(`${window.location.origin}${O}`,l)}}catch{if(c){const be=`${window.location.origin}${ne.getLibraryFileDownloadUrl(e)}`;of(be,l)}else{const be=`${window.location.origin}${ne.getArchiveForSlicer(t,Ne)}`;of(be,l)}}};return i.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:a,children:i.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:Ne=>Ne.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),he&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[je,": ",s("modelViewer.objectCount",{count:ee})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,disabled:!de,children:[i.jsx(Xr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>j(Ne=>!Ne),title:C?"Exit fullscreen":"Enter fullscreen",children:C?i.jsx(kF,{className:"w-4 h-4"}):i.jsx(KC,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:a,children:i.jsx(Lt,{className:"w-5 h-5"})})]})]}),h&&i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>h.has_model&&d("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(Ja,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),i.jsxs("button",{onClick:()=>h.has_gcode&&d("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(jhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&h?i.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${te?"gap-0 min-h-0":"gap-3"}`,children:[K&&i.jsxs("div",{ref:G,style:te&&P!=null?{height:P}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${te?"flex flex-col shrink-0":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(fi,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&i.jsx(it,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:te?"flex flex-col min-h-0 flex-1":void 0,children:[i.jsx("div",{ref:_e,className:te?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:i.jsxs("div",{ref:oe,className:te?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:te?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[i.jsxs("button",{type:"button",onClick:()=>k(null),className:`flex items-center rounded-lg border text-left transition-colors ${te?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${te?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(fi,{className:`${te?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${te?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),i.jsx("p",{className:`${te?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&i.jsx(aa,{className:`${te?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),se.map(Ne=>i.jsxs("button",{type:"button",onClick:()=>k(Ne.index),className:`flex items-center rounded-lg border text-left transition-colors ${te?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Ne.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Ne.has_thumbnail&&Ne.thumbnail_url?i.jsx("img",{src:Ne.thumbnail_url,alt:`Plate ${Ne.index}`,className:`${te?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${te?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(fi,{className:`${te?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${te?"text-xs":"text-sm"} text-white font-medium truncate`,children:Ne.name||s("modelViewer.plateNumber",{number:Ne.index})}),i.jsx("p",{className:`${te?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Ne.object_count??Ne.objects?.length??0})})]}),N===Ne.index&&i.jsx(aa,{className:`${te?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Ne.index))]})}),(Z||me)&&i.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[Z&&i.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[i.jsx("span",{children:s("modelViewer.plateNumber",{number:Z.index})}),Z.print_time_seconds!=null&&i.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(Z.print_time_seconds/60)})}),Z.filament_used_grams!=null&&i.jsxs("span",{children:[Z.filament_used_grams.toFixed(1)," g"]}),Z.filaments.length>0&&i.jsx("span",{children:s("modelViewer.filamentCount",{count:Z.filaments.length})})]}),me&&i.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${Z?"ml-auto":""}`,children:[i.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:A+1,total:Q})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>M(Ne=>Math.max(Ne-1,0)),disabled:A===0,className:`px-2 py-1 rounded border text-xs ${A===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let be=Math.max(0,A-Math.floor(2.5));const O=Math.min(Q,be+5);O-be<5&&(be=Math.max(0,O-5));const R=Array.from({length:O-be},(q,J)=>be+J);return i.jsxs(i.Fragment,{children:[be>0&&i.jsx("button",{type:"button",onClick:()=>M(0),className:`px-2 py-1 rounded border text-xs ${A===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),be>1&&i.jsx("span",{className:"px-1",children:"…"}),R.map(q=>i.jsx("button",{type:"button",onClick:()=>M(q),className:`px-2 py-1 rounded border text-xs ${A===q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q+1},q)),O<Q-1&&i.jsx("span",{className:"px-1",children:"…"}),O<Q&&i.jsx("button",{type:"button",onClick:()=>M(Q-1),className:`px-2 py-1 rounded border text-xs ${A===Q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q})]})})(),i.jsx("button",{type:"button",onClick:()=>M(Ne=>Math.min(Ne+1,Q-1)),disabled:A>=Q-1,className:`px-2 py-1 rounded border text-xs ${A>=Q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),te&&i.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Ne=>{Ne.preventDefault(),L(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${U?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),i.jsx("div",{className:`flex-1 ${te?"min-h-0":""}`,children:i.jsx(xY,{url:c?ne.getLibraryFileDownloadUrl(e):h.has_source?ne.getSource3mfDownloadUrl(t):ne.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&h?i.jsx(eQ,{gcodeUrl:c?ne.getLibraryFileGcodeUrl(e):ne.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const HN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function M$e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),a=parseInt(e.substring(4,6),16),s=Math.max(n,r,a)/255,o=Math.min(n,r,a)/255,l=(s+o)/2;let c=0,u=0;if(s!==o){const d=s-o;u=l>.5?d/(2-s-o):d/(s+o);const h=n/255,f=r/255,p=a/255;s===h?c=((f-p)/d+(f<p?6:0))/6:s===f?c=((p-h)/d+2)/6:c=((h-f)/d+4)/6}return c=c*360,l<.15?"Black":l>.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function vf(t){const e=t.replace("#","").toLowerCase().substring(0,6);return HN[e]?HN[e]:M$e(t)}function b4(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(HN[n])return HN[n]}return null}function oA(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(a=>{const s=a.tray.length===1;a.tray.forEach(o=>{if(o.tray_type){const l=Z7(o.tray_color);e.push({type:o.tray_type,color:l,colorName:vf(l),amsId:a.id,trayId:o.id,isHt:s,isExternal:!1,label:m4(a.id,o.id,s,!1),globalTrayId:f4(a.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(a.id)]})}})});for(const a of t?.vt_tray??[])if(a.tray_type){const s=Z7(a.tray_color),o=a.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:a.tray_type,color:s,colorName:vf(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:a.tray_info_idx||"",extruderId:r?255-o:void 0})}return e}function l9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=oA(e);if(n.length===0)return;const r=new Set,a=t.filaments.map(l=>{const c=l.tray_info_idx||"";let u=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(u=u.filter(v=>v.extruderId===l.nozzle_id));let d,h,f,p;if(c){const v=u.filter(g=>g.trayInfoIdx===c);v.length===1?d=v[0]:v.length>1&&(h=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&ja(g.color)===ja(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Fc(g.color,l.color))),!h&&!f&&(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!h&&!f&&!p&&(h=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&ja(v.color)===ja(l.color)),h||(f=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Fc(v.color,l.color))),!h&&!f&&(p=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=d||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...a.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return a.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function P$e(t){return w.useMemo(()=>oA(t),[t])}function yne(t,e,n){const r=P$e(e),a=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const M=n[d],C=r.find(j=>j.globalTrayId===M);if(C){const j=C.type?.toUpperCase()===u.type?.toUpperCase(),P=ja(C.color)===ja(u.color)||Fc(C.color,u.color);let E;return j&&P?E="match":j?E="type_only":E="mismatch",{...u,loaded:C,hasFilament:!0,typeMatch:j,colorMatch:P,status:E,isManual:!0}}}const h=u.tray_info_idx||"";let f=r.filter(M=>!c.has(M.globalTrayId));u.nozzle_id!=null&&(f=f.filter(M=>M.extruderId===u.nozzle_id));let p,x,v,g;if(h){const M=f.filter(C=>C.trayInfoIdx===h);M.length===1?p=M[0]:M.length>1&&(x=M.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&ja(C.color)===ja(u.color)),x||(v=M.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&Fc(C.color,u.color))),!x&&!v&&(g=M.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(M=>M.type?.toUpperCase()===u.type?.toUpperCase()&&ja(M.color)===ja(u.color)),x||(v=f.find(M=>M.type?.toUpperCase()===u.type?.toUpperCase()&&Fc(M.color,u.color))),!x&&!v&&(g=f.find(M=>M.type?.toUpperCase()===u.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,k=!!p||!!x||!!v;let A;return p||x||v?A="match":g?A="type_only":A="mismatch",{...u,loaded:y,hasFilament:_,typeMatch:N,colorMatch:k,status:A,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(a.length===0)return;const c=Math.max(...a.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return a.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[a]),o=a.some(c=>c.status==="mismatch"),l=a.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:a,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function E$e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,a=0,s=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const g=n[d],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===u.type?.toUpperCase(),N=ja(y.color)===ja(u.color)||Fc(y.color,u.color);_&&N?r++:_?a++:s++;continue}}let h=e.filter(g=>!o.has(g.globalTrayId));if(u.nozzle_id!=null){const g=h.filter(y=>y.extruderId===u.nozzle_id);g.length>0&&(h=g)}const f=h.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()&&ja(g.color)===ja(u.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()&&Fc(g.color,u.color)),x=f||p?void 0:h.find(g=>g.type?.toUpperCase()===u.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?a++:s++}const l=t.length;let c="full";return s>0?c="missing":a>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:a,missingTypes:s,totalSlots:l,status:c}}function j$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=oA(e);if(r.length===0)return;const a=new Set(Object.values(n)),s=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){s.push({slot_id:u,globalTrayId:n[u]});continue}let d=r.filter(v=>!a.has(v.globalTrayId));if(c.nozzle_id!=null){const v=d.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(d=v)}const h=d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&ja(v.color)===ja(c.color)),f=h?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Fc(v.color,c.color)),p=h||f?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&a.add(x.globalTrayId),s.push({slot_id:u,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const c9={useDefault:!0,manualMappings:{},autoConfigured:!1};function D$e(t,e,n,r,a,s){const o=SF({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>ne.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(E=>E.id===x)?.name||`Printer ${x}`,k=oA(y),A=a[x]||c9,M=l9(n,y),C=A.useDefault?r:A.manualMappings,j=j$e(n,y,C),P=E$e(n?.filaments,k,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:k,autoMapping:M,finalMapping:j,matchStatus:P.status,exactMatches:P.exactMatches,typeOnlyMatches:P.typeOnlyMatches,missingTypes:P.missingTypes,totalSlots:P.totalSlots,config:A}}),[t,o,e,n,a,r]),c=o.some(x=>x.isLoading),u=(x,v)=>{s(g=>({...g,[x]:{...g[x]||c9,...v}}))},d=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=l9(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),u(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)d(x)},f=x=>l.find(g=>g.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:a,updatePrinterConfig:u,autoConfigureAll:h,autoConfigurePrinter:d,getFinalMapping:f,allPrintersReady:p}}function R$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:a,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Ot(),c=en(),[u,d]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Je({queryKey:["printer-status",t],queryFn:()=>ne.getPrinterStatus(t),enabled:!!t}),{data:x}=Je({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=yne(e,p,n),N=w.useMemo(()=>{const U=new Map;for(const L of x||[]){const B=L.ams_id===255,D=f4(L.ams_id,L.tray_id,B);U.set(D,L.spool?.cost_per_kg??null)}return U},[x]),k=w.useMemo(()=>{let U=0;for(const L of g){const B=L.loaded?.globalTrayId;if(B==null)continue;const $=N.get(B)??null??s;$>0&&(U+=L.used_grams/1e3*$)}return U},[g,N,s]),A=w.useMemo(()=>Array.from(N.values()).some(U=>U!=null&&U>0),[N]),M=e?.filaments&&e.filaments.length>0,C=e?.filaments?.some(U=>U.nozzle_id!=null)??!1;if(!M||!p)return null;const j=y?"#f97316":_?"#facc15":"#00ae42",P=(U,L)=>{if(U>0)if(L===""){const B={...n};delete B[U],r(B)}else r({...n,[U]:parseInt(L,10)})},E=async()=>{d(!0);try{await ne.refreshPrinterStatus(t),await new Promise(U=>setTimeout(U,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{d(!1)}};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>f(!h),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(v1,{className:"w-4 h-4",fill:j,stroke:"none"}),i.jsx("span",{children:l("printModal.filamentMapping")}),y?i.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?i.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):i.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),h?i.jsx(yl,{className:"w-4 h-4 ml-auto"}):i.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),h&&i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),i.jsxs("button",{type:"button",onClick:E,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:u,children:[i.jsx(Ar,{className:`w-3 h-3 ${u?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),g.map((U,L)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${U.type} - ${vf(U.color)}`,children:i.jsx(v1,{className:"w-3 h-3",fill:U.color,stroke:U.color})}),i.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[C&&U.nozzle_id!=null&&i.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:U.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:U.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),U.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",U.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:U.loaded?.globalTrayId??"",onChange:B=>P(U.slot_id||0,B.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${U.status==="match"?"border-bambu-green/50 text-bambu-green":U.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${U.isManual?"ring-1 ring-blue-400/50":""}`,title:U.isManual?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(B=>U.nozzle_id==null||B.extruderId===U.nozzle_id).map(B=>i.jsxs("option",{value:B.globalTrayId,className:"bg-bambu-dark text-white",children:[B.label,": ",B.type," (",B.colorName,")"]},B.globalTrayId))]}),U.status==="match"?i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}):U.status==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(Tn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(Tn,{className:"w-3 h-3 text-orange-400"})})]},L)),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",i.jsx("span",{className:"text-white",children:k>0||A?`${a}${k.toFixed(2)}`:"N/A"})]}),y&&i.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function F$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:a}=Ot(),s=w.useMemo(()=>{const c={};for(const u of e){const d=u.type.toUpperCase();c[d]||(c[d]=[]),c[d].push(u)}return c},[e]),o=t?.filaments;if(!o||o.length===0||e.length===0)return null;const l=(c,u)=>{if(u===""){const d={...n};delete d[c],r(d)}else{const[d,h]=u.split("|");r({...n,[c]:{type:d,color:h}})}};return i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:i.jsx("span",{children:a("printModal.filamentOverride")})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("printModal.filamentOverrideHint")}),i.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:o.map(c=>{const u=n[c.slot_id],d=!!u,h=s[c.type.toUpperCase()]||[],f=c.nozzle_id!=null?h.filter(p=>p.extruder_id==null||p.extruder_id===c.nozzle_id):h;return i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[i.jsx("span",{title:`${a("printModal.originalFilament")}: ${c.type} - ${vf(c.color)}`,children:i.jsx(v1,{className:"w-3 h-3",fill:c.color,stroke:c.color})}),i.jsxs("span",{className:"text-white truncate",children:[c.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",c.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:d?`${u.type}|${u.color}`:"",onChange:p=>l(c.slot_id,p.target.value),disabled:f.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${d?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[i.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[a("printModal.originalFilament"),": ",c.type," (",vf(c.color),")"]}),f.map((p,x)=>i.jsxs("option",{value:`${p.type}|${p.color}`,className:"bg-bambu-dark text-white",children:[p.type," (",vf(p.color),")"]},`${p.type}-${p.color}-${x}`))]}),d?i.jsx("button",{type:"button",onClick:()=>l(c.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:a("printModal.resetToOriginal"),children:i.jsx(so,{className:"w-3 h-3"})}):i.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function L$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&i.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[i.jsx(Tn,{className:"w-3 h-3"}),"Selection required"]})]}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(a=>i.jsxs("button",{type:"button",onClick:()=>r(a.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===a.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[a.has_thumbnail&&a.thumbnail_url!=null?i.jsx("img",{src:a.thumbnail_url,alt:`Plate ${a.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx(fi,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white font-medium truncate",children:a.name||`Plate ${a.index}`}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[a.objects.length>0?a.objects.slice(0,3).join(", ")+(a.objects.length>3?"...":""):`${a.filaments.length} filament${a.filaments.length!==1?"s":""}`,a.print_time_seconds!=null?` • ${Qs(a.print_time_seconds)}`:""]})]}),n===a.index&&i.jsx(aa,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},a.index))})]})}function O$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=en(),[a,s]=w.useState(!1),o=(u,d)=>{if(u<=0)return;const h={...t.config.manualMappings};d===""?delete h[u]:h[u]=parseInt(d,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await ne.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(u=>{const d=u.slot_id||0,h=t.config.manualMappings[d];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),g=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&ja(N.color)===ja(u.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&Fc(N.color,u.color)),_=g||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase());f=g??y??_}let x="mismatch";if(f){const v=f.type?.toUpperCase()===u.type?.toUpperCase(),g=ja(f.color)===ja(u.color)||Fc(f.color,u.color);v&&g?x="match":v&&(x="type_only")}return{req:u,loaded:f,status:x,isManual:p}});return i.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),i.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:a,children:[i.jsx(Ar,{className:`w-3 h-3 ${a?"animate-spin":""}`}),i.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:h,isManual:f},p)=>i.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[i.jsx("span",{title:`Required: ${u.type} - ${vf(u.color)}`,children:i.jsx(v1,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),i.jsxs("span",{className:"text-white truncate",children:[u.type," ",i.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),i.jsx("span",{className:"text-bambu-gray",children:"→"}),i.jsxs("select",{value:d?.globalTrayId??"",onChange:x=>o(u.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[i.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>i.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?i.jsx("span",{title:"Same type, different color",children:i.jsx(Tn,{className:"w-3 h-3 text-yellow-400"})}):i.jsx("span",{title:"Filament type not loaded",children:i.jsx(Tn,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function I$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:a=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u,assignmentMode:d="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:g}){const[y,_]=w.useState(!1),N=s?t:t.filter(z=>z.is_active),k=w.useMemo(()=>{if(d!=="printer"||!g||y)return N;const z=N.filter(W=>W.model===g);return z.length>0?z:N},[N,d,g,y]),A=N.length-k.length,M=w.useMemo(()=>{const z=N.map(W=>W.model).filter(W=>!!W);return[...new Set(z)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const z=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(z)].sort()},[N,f]),j=h&&p&&M.length>0,P=a&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(k.length===0)return i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[i.jsx(Ba,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const E=z=>{a?e.includes(z)?n(e.filter(W=>W!==z)):n([...e,z]):n([z])},U=()=>{n(k.map(z=>z.id))},L=()=>{n([])},B=(z,W,X)=>{X.stopPropagation(),!(!c||!u)&&(W?c(z):u(z,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=z=>e.includes(z),$=e.length,G=z=>o?.find(W=>W.printerId===z);return i.jsxs("div",{className:"space-y-2 mb-6",children:[j&&i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[i.jsx(gr,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),i.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const z=g&&M.includes(g)?g:M[0];p(z)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[i.jsx(mh,{className:"w-4 h-4"}),i.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),d==="model"&&j&&i.jsxs("div",{className:"space-y-3 mb-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),i.jsxs("select",{value:f||"",onChange:z=>{p(z.target.value||null),v&&v(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[i.jsx("option",{value:"",children:"Select a model..."}),M.map(z=>i.jsx("option",{value:z,children:z},z))]})]}),f&&C.length>0&&v&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),i.jsxs("select",{value:x||"",onChange:z=>v(z.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[i.jsx("option",{value:"",children:"Any location"}),C.map(z=>i.jsx("option",{value:z,children:z},z))]})]}),f&&i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),d==="printer"&&a&&k.length>1&&i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[i.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),i.jsxs("div",{className:"flex gap-2",children:[$<k.length&&i.jsx("button",{type:"button",onClick:U,className:"text-bambu-green hover:text-bambu-green/80 transition-colors",children:"Select all"}),$>0&&i.jsx("button",{type:"button",onClick:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d==="printer"&&k.map(z=>{const W=D(z.id),X=G(z.id),ae=X&&!X.config.useDefault;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>E(z.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${W?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${z.is_active?"":"opacity-60"}`,children:[i.jsx("div",{className:`p-2 rounded-lg ${W?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:i.jsx(gr,{className:`w-5 h-5 ${W?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{className:"text-left flex-1",children:[i.jsxs("p",{className:"text-white font-medium",children:[z.name,!z.is_active&&i.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[z.model||"Unknown model"," • ",z.ip_address]})]}),a&&i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${W?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:W&&i.jsx(aa,{className:"w-3 h-3 text-white"})})]}),W&&P&&X&&i.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:H=>H.stopPropagation(),children:[i.jsx("input",{type:"checkbox",checked:ae,onChange:H=>B(z.id,H.target.checked,H),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),i.jsxs("span",{className:`text-xs ml-2 ${X.matchStatus==="full"?"text-bambu-green":X.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",X.exactMatches,"/",X.totalSlots," matched)"]}),X.isLoading&&i.jsx(Ar,{className:"w-3 h-3 text-bambu-gray animate-spin"}),ae&&i.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(z.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[i.jsx(rge,{className:"w-3 h-3"}),"Auto"]})]}),ae&&i.jsx(O$e,{printerResult:X,filamentReqs:l.filaments,onUpdateConfig:H=>u(z.id,H)})]})]},z.id)}),d==="printer"&&A>0&&!y&&i.jsxs("button",{type:"button",onClick:()=>_(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[i.jsx(Tn,{className:"w-3 h-3 text-yellow-400"}),A," other printer",A>1?"s":""," hidden (different model) —",i.jsx("span",{className:"underline",children:"show all"})]}),d==="printer"&&y&&g&&i.jsx("button",{type:"button",onClick:()=>_(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:i.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),d==="printer"&&$===0&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),"Select at least one printer"]}),d==="model"&&!f&&i.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const z$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function U$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,a]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return i.jsxs("div",{className:"mb-4",children:[i.jsxs("button",{type:"button",onClick:()=>a(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[i.jsx(f0,{className:"w-4 h-4"}),i.jsx("span",{children:"Print Options"}),r?i.jsx(yl,{className:"w-4 h-4 ml-auto"}):i.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),r&&i.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:z$e.map(({key:o,label:l,desc:c})=>i.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:l}),i.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),i.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:i.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function B$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system"}){const[a,s]=w.useState(""),[o,l]=w.useState(""),[c,u]=w.useState(!0),[d,h]=w.useState(!0),f=w.useRef(null),p=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){p.current=!1;return}if(!p.current){p.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:d3(k)})),s(u3(k,n)),l($B(k,r)),u(!0),h(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const x=k=>{e({...t,scheduleType:k})},v=(k,A)=>{const M=Mge(k,n),C=Pge(A);u(!!M),h(!!C),M&&C&&(M.setHours(C.hours,C.minutes,0,0),M>new Date&&e({...t,scheduledTime:d3(M)}))},g=k=>{s(k),v(k,o)},y=k=>{l(k),v(a,k)},_=k=>{const A=k.target.value;if(A){const M=new Date(A);isNaN(M.getTime())||(s(u3(M,n)),l($B(M,r)),u(!0),h(!0),e({...t,scheduledTime:A}))}},N=()=>{f.current?.showPicker()};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("asap"),children:[i.jsx(Wn,{className:"w-4 h-4"}),"ASAP"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("scheduled"),children:[i.jsx(ra,{className:"w-4 h-4"}),"Scheduled"]}),i.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("manual"),children:[i.jsx(gX,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"flex-1 relative",children:[i.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${c?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:a,onChange:k=>g(k.target.value),placeholder:Age(n)}),i.jsx("button",{type:"button",onClick:N,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:i.jsx(ra,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"w-32",children:i.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:o,onChange:k=>y(k.target.value),placeholder:Tge(r)})})]}),i.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:_,tabIndex:-1}),(!c||!d)&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[i.jsx(md,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Cg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},H$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Xu({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:a,onClose:s,onSuccess:o}){const{t:l}=Ot(),c=en(),{showToast:u}=an(),d=!!n&&!e,[h,f]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[p,x]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[v,g]=w.useState(()=>t==="edit-queue-item"&&a?{bed_levelling:a.bed_levelling??Cg.bed_levelling,flow_cali:a.flow_cali??Cg.flow_cali,vibration_cali:a.vibration_cali??Cg.vibration_cali,layer_inspect:a.layer_inspect??Cg.layer_inspect,timelapse:a.timelapse??Cg.timelapse}:Cg),[y,_]=w.useState(()=>{if(t==="edit-queue-item"&&a){let Ae="asap";a.manual_start?Ae="manual":a.scheduled_time&&!J7(a.scheduled_time)&&(Ae="scheduled");let Re="";if(a.scheduled_time&&!J7(a.scheduled_time)){const $e=new Date(a.scheduled_time);Re=d3($e)}return{scheduleType:Ae,scheduledTime:Re,requirePreviousSuccess:a.require_previous_success,autoOffAfter:a.auto_off_after}}return H$e}),[N,k]=w.useState(()=>{if(t==="edit-queue-item"&&a?.ams_mapping&&Array.isArray(a.ams_mapping)){const Ae={};return a.ams_mapping.forEach((Re,$e)=>{Re!==-1&&(Ae[$e+1]=Re)}),Ae}return{}}),[A,M]=w.useState({}),[C,j]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?"model":"printer"),[P,E]=w.useState(()=>t==="edit-queue-item"&&a?.target_model?a.target_model:null),[U,L]=w.useState(()=>t==="edit-queue-item"&&a?.target_location?a.target_location:null),[B,D]=w.useState(()=>{if(t==="edit-queue-item"&&a?.filament_overrides){const Ae={};for(const Re of a.filament_overrides)Ae[Re.slot_id]={type:Re.type,color:Re.color};return Ae}return{}}),[$]=w.useState(()=>t==="edit-queue-item"&&a?.printer_id?[a.printer_id]:[]),[G]=w.useState(()=>t==="edit-queue-item"&&a?a.plate_id:null),[z,W]=w.useState(!1),[X,ae]=w.useState({current:0,total:0}),[H,K]=w.useState(new Set),te=h.length,Z=h.length>0?h[0]:null,{data:ve}=Je({queryKey:["settings"],queryFn:ne.getSettings}),ce=rl(ve?.currency||"USD"),ee=ve?.default_filament_cost??0,{data:je,isLoading:he}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:oe}=Je({queryKey:["archive",e],queryFn:()=>ne.getArchive(e),enabled:!!e&&!d}),{data:_e}=Je({queryKey:["library-file",n],queryFn:()=>ne.getLibraryFile(n),enabled:d&&!!n}),ie=oe?.sliced_for_model||_e?.sliced_for_model||null,{data:ze,isError:V}=Je({queryKey:["archive-plates",e],queryFn:()=>ne.getArchivePlates(e),enabled:!!e&&!d,retry:!1}),{data:Y}=Je({queryKey:["library-file-plates",n],queryFn:()=>ne.getLibraryFilePlates(n),enabled:d&&!!n}),me=d?Y:ze,{data:Q,isError:se}=Je({queryKey:["archive-filaments",e,p],queryFn:()=>ne.getArchiveFilamentRequirements(e,p??void 0),enabled:!!e&&!d&&(p!==null||!me?.is_multi_plate),retry:!1}),{data:de}=Je({queryKey:["library-file-filaments",n,p],queryFn:()=>ne.getLibraryFileFilamentRequirements(n,p??void 0),enabled:d&&!!n&&(p!==null||!me?.is_multi_plate)}),Le=!d&&(V||se),Ne=d?de:Q,be=w.useMemo(()=>{if(!(p===null||!me?.plates?.length))return me.plates.find(Ae=>Ae.index===p)?.name||void 0},[me,p]),{data:O}=Je({queryKey:["available-filaments",P,U],queryFn:()=>ne.getAvailableFilaments(P,U??void 0),enabled:C==="model"&&!!P}),{data:R}=Je({queryKey:["printer-status",Z],queryFn:()=>ne.getPrinterStatus(Z),enabled:!!Z}),{amsMapping:q}=yne(Ne,R,N),J=D$e(h,je,Ne,N,A,M);w.useEffect(()=>{me?.plates&&me.plates.length>=1&&!p&&x(me.plates[0].index)},[me,p]),w.useEffect(()=>{if(t==="edit-queue-item")return;const Ae=je?.filter(Re=>Re.is_active)||[];Ae.length===1&&h.length===0&&f([Ae[0].id])},[t,je,h.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(h.sort())!==JSON.stringify($.sort())||p!==G)&&(k({}),M({}),K(new Set)):(k({}),M({}),K(new Set))},[t,h,p,$,G]);const[fe,le]=w.useState(P),[Be,Ie]=w.useState(p);w.useEffect(()=>{(P!==fe||p!==Be)&&(le(P),Ie(p),(t!=="edit-queue-item"||fe!==null)&&D({}))},[P,p,fe,Be,t]),w.useEffect(()=>{if(!ve?.per_printer_mapping_expanded||h.length<=1)return;const Ae=h.filter(Re=>{if(H.has(Re))return!1;const $e=J.printerResults.find(ht=>ht.printerId===Re);return $e&&$e.status&&!$e.isLoading});Ae.length>0&&(K(Re=>{const $e=new Set(Re);return Ae.forEach(ht=>$e.add(ht)),$e}),Ae.forEach(Re=>{J.autoConfigurePrinter(Re)}))},[ve?.per_printer_mapping_expanded,h,H,J]),w.useEffect(()=>{const Ae=Re=>{Re.key==="Escape"&&!z&&s()};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[s,z]);const Ke=me?.is_multi_plate??!1,Oe=me?.plates??[],pe=st({mutationFn:Ae=>ne.addToQueue(Ae)}),xe=st({mutationFn:Ae=>ne.updateQueueItem(a.id,Ae),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),o?.(),s()},onError:Ae=>{u(Ae.message||"Failed to update queue item","error")}}),ke=async Ae=>{if(Ae?.preventDefault(),C==="printer"&&h.length===0){u("Please select at least one printer","error");return}if(C==="model"&&!P){u("Please select a target printer model","error");return}W(!0);const Re=C==="model"?1:h.length;ae({current:0,total:Re});const $e={success:0,failed:0,errors:[]},ht=It=>{if(h.length>1){const kt=A[It];if(kt&&!kt.useDefault)return J.getFinalMapping(It)}return q},At=Object.keys(B).length>0?Object.entries(B).map(([It,{type:kt,color:Ue}])=>({slot_id:parseInt(It,10),type:kt,color:Ue})):void 0,Dt=It=>({printer_id:C==="printer"?It:null,target_model:C==="model"?P:null,target_location:C==="model"?U:null,filament_overrides:C==="model"?At:void 0,archive_id:d?void 0:e,library_file_id:d?n:void 0,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:It?ht(It):void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():void 0,...v});if(C==="model"){ae({current:1,total:1});try{if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),W(!1);return}else if(t==="edit-queue-item"){const It={printer_id:null,target_model:P,target_location:U,filament_overrides:At||null,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():null,...v};await xe.mutateAsync(It)}else await pe.mutateAsync(Dt(null));$e.success++}catch(It){$e.failed++,$e.errors.push(It.message)}}else for(let It=0;It<h.length;It++){const kt=h[It];ae({current:It+1,total:h.length});try{if(t==="reprint"){const Ue=ht(kt);d?await ne.printLibraryFile(n,kt,{plate_id:p??void 0,plate_name:be,ams_mapping:Ue,...v}):await ne.reprintArchive(e,kt,{plate_id:p??void 0,plate_name:be,ams_mapping:Ue,...v})}else if(t==="edit-queue-item"&&It===0){const Ue=ht(kt),bt={printer_id:kt,target_model:null,target_location:null,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:Ue,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():null,...v};await xe.mutateAsync(bt)}else await pe.mutateAsync(Dt(kt));$e.success++}catch(Ue){$e.failed++;const bt=je?.find(yt=>yt.id===kt)?.name||`Printer ${kt}`;$e.errors.push(`${bt}: ${Ue.message}`)}}W(!1),$e.failed===0?(t!=="reprint"&&(C==="model"?u(t==="edit-queue-item"?"Queue item updated":`Queued for any ${P}`):t==="edit-queue-item"?u("Queue item updated"):$e.success===1?u("Print queued for printer"):u(`Print queued for ${$e.success} printers`)),c.invalidateQueries({queryKey:["queue"]}),o?.(),s()):$e.success===0?u(`Failed: ${$e.errors[0]}`,"error"):(u(`${$e.success} succeeded, ${$e.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},ge=z||xe.isPending,we=w.useMemo(()=>!(ge||C==="printer"&&h.length===0||C==="model"&&!P||C==="model"&&t==="reprint"||Ke&&!p),[h.length,C,P,t,Ke,p,ge]),Ee=(()=>{const Ae=h.length;return t==="reprint"?{title:l(d?"queue.print":"queue.reprint"),icon:gr,submitText:Ae>1?l("queue.printToPrinters",{count:Ae}):l("queue.print"),submitIcon:gr,loadingText:X.total>1?l("queue.sendingProgress",{current:X.current,total:X.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:ra,submitText:Ae>1?l("queue.queueToPrinters",{count:Ae}):l("queue.addToQueue"),submitIcon:ra,loadingText:X.total>1?l("queue.addingProgress",{current:X.current,total:X.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:$a,submitText:l("common.save"),submitIcon:$a,loadingText:X.total>1?l("queue.savingProgress",{current:X.current,total:X.total}):l("common.saving")}})(),tt=Ee.icon,De=Ee.submitIcon,We=Z&&(d||(Ke?p!==null:!0));return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:z?void 0:s,children:i.jsx(wt,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:Ae=>Ae.stopPropagation(),children:i.jsxs(_t,{className:t==="reprint"?"":"p-0",children:[i.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(tt,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:Ee.title})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:s,disabled:z,children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:ke,className:t==="reprint"?"":"p-4 space-y-4",children:[i.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?i.jsxs(i.Fragment,{children:["Send ",i.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),i.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),i.jsx(L$e,{plates:Oe,isMultiPlate:Ke,selectedPlate:p,onSelect:x}),i.jsx(I$e,{printers:je||[],selectedPrinterIds:h,onMultiSelect:f,isLoading:he,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:J.printerResults,filamentReqs:Ne,onAutoConfigurePrinter:J.autoConfigurePrinter,onUpdatePrinterConfig:J.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":C,onAssignmentModeChange:t!=="reprint"?j:void 0,targetModel:P,onTargetModelChange:t!=="reprint"?E:void 0,targetLocation:U,onTargetLocationChange:t!=="reprint"?L:void 0,slicedForModel:ie}),C==="model"&&P&&Ne&&O&&O.length>0&&i.jsx(F$e,{filamentReqs:Ne,availableFilaments:O,overrides:B,onChange:D}),ie&&C==="printer"&&h.length===1&&(()=>{const Ae=je?.find(Re=>Re.id===h[0]);return Ae&&Ae.model&&ie!==Ae.model?i.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",ie,", but printing on ",Ae.model]})]}):null})(),Le&&i.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[i.jsx(Ba,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),We&&!Le&&h.length===1&&i.jsx(R$e,{printerId:Z,filamentReqs:Ne,manualMappings:N,onManualMappingChange:k,defaultExpanded:ve?.per_printer_mapping_expanded??!1,currencySymbol:ce,defaultCostPerKg:ee}),(t==="reprint"||te>0||C==="model"&&P)&&i.jsx(U$e,{options:v,onChange:g}),t!=="reprint"&&i.jsx(B$e,{options:y,onChange:_,dateFormat:ve?.date_format||"system",timeFormat:ve?.time_format||"system"}),xe.isError&&i.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:xe.error?.message||"Failed to complete operation"}),i.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:z,children:"Cancel"}),i.jsx(Ce,{type:"submit",disabled:!we,className:"flex-1",children:ge?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),Ee.loadingText]}):i.jsxs(i.Fragment,{children:[i.jsx(De,{className:"w-4 h-4"}),Ee.submitText]})})]})]})]})})})}function $$e({onClose:t,initialFiles:e}){const{t:n}=Ot(),r=en(),{showToast:a}=an(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(A=>A.name.endsWith(".3mf")).map(A=>({file:A,status:"pending"}))||[]),[c,u]=w.useState(!1),[d,h]=w.useState(null);w.useEffect(()=>{const A=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t]);const f=st({mutationFn:A=>ne.uploadArchivesBulk(A),onSuccess:A=>{h(A),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(M=>M.map(C=>{const j=A.results.find(E=>E.filename===C.file.name),P=A.errors.find(E=>E.filename===C.file.name);return j?{...C,status:"success",archiveId:j.id}:P?{...C,status:"error",error:P.error}:C})),A.failed===0?a(`${A.uploaded} file${A.uploaded!==1?"s":""} uploaded`):A.uploaded===0?a(`Failed to upload ${A.failed} file${A.failed!==1?"s":""}`,"error"):a(`${A.uploaded} uploaded, ${A.failed} failed`,"warning")},onError:()=>{l(A=>A.map(M=>({...M,status:"error",error:"Upload failed"}))),a("Upload failed","error")}}),p=w.useCallback(A=>{A.preventDefault(),u(!0)},[]),x=w.useCallback(A=>{A.preventDefault(),u(!1)},[]),v=w.useCallback(A=>{A.preventDefault(),u(!1);const M=Array.from(A.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))])},[]),g=w.useCallback(A=>{const M=Array.from(A.target.files||[]).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(A=>{l(M=>M.filter((C,j)=>j!==A))},[]),_=()=>{if(o.length===0)return;const A=o.filter(M=>M.status==="pending");A.length!==0&&(l(M=>M.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(A.map(M=>M.file)))},N=o.filter(A=>A.status==="pending").length,k=f.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4",children:i.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:p,onDragLeave:x,onDrop:v,children:[i.jsx(Ra,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),i.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),i.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),i.jsx(Ce,{variant:"secondary",onClick:()=>s.current?.click(),disabled:k,children:n("uploadModal.browseFiles")}),i.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),i.jsx("div",{className:"px-4 pb-4",children:i.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&i.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:i.jsx("div",{className:"space-y-2",children:o.map((A,M)=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(VC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"flex-1 text-white text-sm truncate",children:A.file.name}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[(A.file.size/(1024*1024)).toFixed(1)," MB"]}),A.status==="pending"&&i.jsx("button",{onClick:()=>y(M),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:k,children:i.jsx(Lt,{className:"w-4 h-4"})}),A.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),A.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-bambu-green"}),A.status==="error"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-red-400",children:A.error}),i.jsx(Ba,{className:"w-4 h-4 text-red-400"})]})]},`${A.file.name}-${M}`))})}),d&&i.jsx("div",{className:"px-4 pb-4",children:i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&i.jsxs(i.Fragment,{children:[", ",i.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&i.jsx(Ce,{onClick:_,disabled:N===0||k,className:"flex-1",children:k?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const V$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],q$e=["completed","failed","aborted","printing"];function vne({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Ot();w.useEffect(()=>{const he=oe=>{oe.key==="Escape"&&e()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e]);const a=en(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[u,d]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,k]=w.useState(t.quantity??1),[A,M]=w.useState(t.photos||[]),[C,j]=w.useState(t.external_url||""),[P,E]=w.useState(!1),[U,L]=w.useState(!1),B=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:z}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:W}=Je({queryKey:["tags"],queryFn:ne.getTags,enabled:n.length===0}),X=n.length>0?n:W?.map(he=>he.name)||[],ae=p.split(",").map(he=>he.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),K=X.filter(he=>!ae.includes(he)&&(H===""||he.toLowerCase().includes(H))),te=he=>{let oe;if(H&&!X.includes(H)?oe=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(_e=>_e.trim()).filter(Boolean):[]:oe=ae,!oe.includes(he)){const _e=[...oe,he].join(", ");x(_e)}$.current!==null&&clearTimeout($.current),B.current?.focus()},Z=he=>{const oe=ae.filter(_e=>_e!==he).join(", ");x(oe)},ve=st({mutationFn:he=>ne.updateArchive(t.id,he),onSuccess:()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),e()}}),ce=async he=>{const oe=he.target.files?.[0];if(oe){E(!0);try{const _e=await ne.uploadArchivePhoto(t.id,oe);M(_e.photos),a.invalidateQueries({queryKey:["archives"]})}catch(_e){console.error("Failed to upload photo:",_e)}finally{E(!1),D.current&&(D.current.value="")}}},ee=async he=>{try{const oe=await ne.deleteArchivePhoto(t.id,he);M(oe.photos||[]),a.invalidateQueries({queryKey:["archives"]})}catch(oe){console.error("Failed to delete photo:",oe)}},je=he=>{he.preventDefault();const oe={print_name:s||void 0,printer_id:l,project_id:u,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(oe.status=y),y==="failed"||y==="aborted"?oe.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(oe.failure_reason=null),ve.mutate(oe)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:he=>he.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:je,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),i.jsx("input",{type:"text",value:s,onChange:he=>o(he.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),i.jsxs("select",{value:l??"",onChange:he=>c(he.target.value?Number(he.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(he=>i.jsx("option",{value:he.id,children:he.name},he.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(gs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),i.jsxs("select",{value:u??"",onChange:he=>d(he.target.value?Number(he.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noProject")}),z?.map(he=>i.jsx("option",{value:he.id,children:he.name},he.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(zme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),i.jsx("input",{type:"number",min:1,value:N,onChange:he=>k(Math.max(1,parseInt(he.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),i.jsx("textarea",{value:h,onChange:he=>f(he.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(qb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),i.jsx("input",{type:"url",value:C,onChange:he=>j(he.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),ae.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ae.map(he=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[i.jsx(Vh,{className:"w-3 h-3"}),he,i.jsx("button",{type:"button",onClick:()=>Z(he),className:"ml-0.5 text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-3 h-3"})})]},he))}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:B,type:"text",value:p,onChange:he=>x(he.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),L(!0)},onBlur:()=>{$.current=window.setTimeout(()=>L(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:ae.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),U&&K.length>0&&i.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[i.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[H?r("editArchive.matchingTags",{query:H}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),i.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:K.map(he=>i.jsx("button",{type:"button",onClick:()=>te(he),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:he},he))})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),i.jsx("select",{value:y,onChange:he=>{_(he.target.value),he.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:q$e.map(he=>i.jsx("option",{value:he,children:r(`editArchive.statuses.${he}`)},he))})]}),(y==="failed"||y==="aborted")&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),i.jsxs("select",{value:v,onChange:he=>g(he.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.selectReason")}),V$e.map(he=>i.jsx("option",{value:r(`editArchive.failureReasons.${he}`),children:r(`editArchive.failureReasons.${he}`)},he))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(cb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[A.map(he=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:ne.getArchivePhotoUrl(t.id,he),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:()=>ee(he),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(Jt,{className:"w-3 h-3 text-white"})})]},he)),i.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[i.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:ce,className:"hidden",disabled:P}),P?i.jsx(it,{className:"w-6 h-6 text-bambu-gray animate-spin"}):i.jsx(Gn,{className:"w-6 h-6 text-bambu-gray"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ce,{type:"submit",disabled:ve.isPending,className:"flex-1",children:[i.jsx(ps,{className:"w-4 h-4"}),ve.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function wne({x:t,y:e,items:n,onClose:r}){const a=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,u]=w.useState({x:t,y:e,visible:!1}),[d,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const g=N=>{a.current&&!a.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(a.current){a.current.style.visibility="hidden",a.current.style.display="block";const g=a.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let k=t,A=e;t+g.width>y-N&&(k=Math.max(N,y-g.width-N)),k<N&&(k=N),e+g.height>_-N&&(A=Math.max(N,_-g.height-N)),A<N&&(A=N);const M=180,C=y-k-g.width,j=k;h(C<M&&j>M),u({x:k,y:A,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,k=300,C=N-_.top-8<k&&_.top>k;p(j=>({...j,[g]:C?"bottom":"top"})),o(g)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return i.jsx("div",{ref:a,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((g,y)=>{if(g.divider)return i.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return i.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[i.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),i.jsx("span",{className:"flex-1",children:g.label}),_&&i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&i.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${d?"right-full mr-1":"left-full ml-1"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,k)=>i.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},k))})]},y)})})}function G$e({selectedIds:t,existingTags:e,onClose:n}){const r=en(),{showToast:a}=an(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[u,d]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=st({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await ne.getArchive(y),N=_.tags?_.tags.split(",").map(A=>A.trim()).filter(Boolean):[];let k;u==="add"?k=[...new Set([...N,...v])]:k=N.filter(A=>!l.has(A)),await ne.updateArchive(y,{tags:k.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:u,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),a(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{a(v.message||"Failed to update tags","error")}}),f=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-md",children:i.jsxs(_t,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),i.jsx(Ce,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:i.jsx(Gn,{className:"w-4 h-4"})})]}),e.length>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>i.jsx("button",{onClick:()=>f(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&i.jsxs("div",{children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>i.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,i.jsx("button",{onClick:()=>f(v),className:"hover:opacity-70",children:i.jsx(Lt,{className:"w-3 h-3"})})]},v))})]})]}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),i.jsx(Ce,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Vh,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function W$e({selectedIds:t,onClose:e}){const n=en(),{showToast:r}=an(),{data:a,isLoading:s}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()});w.useEffect(()=>{const d=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=st({mutationFn:async d=>(await ne.addArchivesToProject(d,t),d),onSuccess:d=>{const h=a?.find(f=>f.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=st({mutationFn:async()=>{for(const d of t)await ne.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(gs,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("button",{onClick:()=>c.mutate(),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:i.jsx(mi,{className:"w-4 h-4 text-red-400"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&i.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),a&&a.length>0&&i.jsxs("div",{className:"flex items-center gap-2 py-2",children:[i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a?.map(d=>i.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:i.jsx(gs,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium truncate",children:d.name}),i.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&i.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!a||a.length===0)&&i.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:i.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function K$e(t,e){return new Date(t,e+1,0).getDate()}function X$e(t,e){return new Date(t,e,1).getDay()}const Y$e=["January","February","March","April","May","June","July","August","September","October","November","December"],Q$e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Z$e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[a,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,u]=w.useState(null),[d,h]=w.useState(null),f=w.useMemo(()=>{const A=new Map;return t.forEach(M=>{const C=hi(M.completed_at||M.created_at)||new Date,j=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,P=A.get(j)||[];P.push(M),A.set(j,P)}),A},[t]),p=K$e(o,a),x=X$e(o,a),v=()=>{a===0?(s(11),l(o-1)):s(a-1)},g=()=>{a===11?(s(0),l(o+1)):s(a+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let A=0;A<x;A++)_.push(null);for(let A=1;A<=p;A++)_.push(A);const N=c?f.get(c)||[]:[],k=A=>{A!==c&&h(null),u(A)};return i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Xl,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Y$e[a]," ",o]}),i.jsx("button",{onClick:y,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),i.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(pi,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Q$e.map(A=>i.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:A},A))}),i.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((A,M)=>{if(A===null)return i.jsx("div",{className:"aspect-square"},`empty-${M}`);const C=`${o}-${String(a+1).padStart(2,"0")}-${String(A).padStart(2,"0")}`,j=f.get(C)||[],P=j.length>0,E=A===r.getDate()&&a===r.getMonth()&&o===r.getFullYear(),U=C===c,L=j.filter(D=>D.status==="completed").length,B=j.filter(D=>D.status==="failed").length;return i.jsxs("button",{onClick:()=>k(U?null:C),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${U?"bg-bambu-green text-white":E?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":P?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[i.jsx("span",{className:`text-sm font-medium ${E&&!U?"text-bambu-green":""}`,children:A}),P&&i.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${B>0&&L===0?"bg-red-400":B>0?"bg-yellow-400":"bg-green-400"}`}),i.jsx("span",{className:"text-xs font-medium",children:j.length})]})]},A)})}),i.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(A=>{const M=new Date(A.completed_at||A.created_at);return M.getMonth()===a&&M.getFullYear()===o}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(A=>{const M=new Date(A.completed_at||A.created_at);return M.getMonth()===a&&M.getFullYear()===o&&A.status==="completed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(A=>{const M=new Date(A.completed_at||A.created_at);return M.getMonth()===a&&M.getFullYear()===o&&A.status==="failed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),i.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?i.jsxs(i.Fragment,{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),N.length>0?i.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(A=>{const M=A.id===d||A.id===n;return i.jsxs("button",{onClick:()=>{h(A.id),e?.(A)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${M?"":"hover:bg-bambu-dark-tertiary"}`,style:M?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[A.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(A.id),alt:"",className:"w-12 h-12 rounded object-cover"}):i.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:A.print_name||A.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:A.status==="failed"?"text-red-400":"text-green-400",children:A.status==="failed"?"Failed":"Completed"}),A.filament_color&&i.jsx("div",{className:"flex gap-0.5",children:A.filament_color.split(",").map((C,j)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},j))})]})]})]},A.id)})}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Sne({archiveId:t,archiveName:e,onClose:n}){const r=ne.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const a=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 flex flex-col items-center",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),i.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:i.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),i.jsxs(Ce,{onClick:a,className:"w-full",children:[i.jsx(da,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function _ne({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:a}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const p=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const u=n[s],d=ne.getArchivePhotoUrl(t,u),h=()=>{const p=document.createElement("a");p.href=d,p.download=`${e}_photo_${s+1}.jpg`,p.click()},f=()=>{a&&c(!0)};return i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[i.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:p=>p.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:h,children:[i.jsx(da,{className:"w-4 h-4"}),"Download"]}),a&&i.jsx(Ce,{variant:"secondary",size:"sm",onClick:f,className:"text-red-400 hover:text-red-300",children:i.jsx(Jt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-6 h-6"})})]})]}),i.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&i.jsx("button",{onClick:()=>o(p=>p-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(Xl,{className:"w-8 h-8 text-white"})}),i.jsx("img",{src:d,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),s<n.length-1&&i.jsx("button",{onClick:()=>o(p=>p+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(pi,{className:"w-8 h-8 text-white"})})]}),n.length>1&&i.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((p,x)=>i.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:i.jsx("img",{src:ne.getArchivePhotoUrl(t,p),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},p))})]}),l&&i.jsx(gn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{a?.(u),c(!1)},onCancel:()=>c(!1)})]})}function Wi(t){this.content=t}Wi.prototype={constructor:Wi,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return e==-1?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,a=r.find(t),s=r.content.slice();return a==-1?s.push(n||t,e):(s[a+1]=e,n&&(s[a]=n)),new Wi(s)},remove:function(t){var e=this.find(t);if(e==-1)return this;var n=this.content.slice();return n.splice(e,2),new Wi(n)},addToStart:function(t,e){return new Wi([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Wi(n)},addBefore:function(t,e,n){var r=this.remove(e),a=r.content.slice(),s=r.find(t);return a.splice(s==-1?a.length:s,0,e,n),new Wi(a)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){return t=Wi.from(t),t.size?new Wi(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=Wi.from(t),t.size?new Wi(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Wi.from(t);for(var n=0;n<t.content.length;n+=2)e=e.remove(t.content[n]);return e},toObject:function(){var t={};return this.forEach(function(e,n){t[e]=n}),t},get size(){return this.content.length>>1}};Wi.from=function(t){if(t instanceof Wi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Wi(e)};function Nne(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let a=t.child(r),s=e.child(r);if(a==s){n+=a.nodeSize;continue}if(!a.sameMarkup(s))return n;if(a.isText&&a.text!=s.text){for(let o=0;a.text[o]==s.text[o];o++)n++;return n}if(a.content.size||s.content.size){let o=Nne(a.content,s.content,n+1);if(o!=null)return o}n+=a.nodeSize}}function Cne(t,e,n,r){for(let a=t.childCount,s=e.childCount;;){if(a==0||s==0)return a==s?null:{a:n,b:r};let o=t.child(--a),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let u=0,d=Math.min(o.text.length,l.text.length);for(;u<d&&o.text[o.text.length-u-1]==l.text[l.text.length-u-1];)u++,n--,r--;return{a:n,b:r}}if(o.content.size||l.content.size){let u=Cne(o.content,l.content,n-1,r-1);if(u)return u}n-=c,r-=c}}class Mt{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,n,r,a=0,s){for(let o=0,l=0;l<n;o++){let c=this.content[o],u=l+c.nodeSize;if(u>e&&r(c,a+l,s||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,a+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,a){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?a?typeof a=="function"?a(l):a:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=u},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,a=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)a.push(e.content[s]);return new Mt(a,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let r=[],a=0;if(n>e)for(let s=0,o=0;o<n;s++){let l=this.content[s],c=o+l.nodeSize;c>e&&((o<e||c>n)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),a+=l.nodeSize),o=c}return new Mt(r,a)}cutByIndex(e,n){return e==n?Mt.empty:e==0&&n==this.content.length?this:new Mt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let a=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return a[e]=n,new Mt(a,s)}addToStart(e){return new Mt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Mt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(e.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let n=this.content[e];if(!n)throw new RangeError("Index "+e+" out of range for "+this);return n}maybeChild(e){return this.content[e]||null}forEach(e){for(let n=0,r=0;n<this.content.length;n++){let a=this.content[n];e(a,r,n),r+=a.nodeSize}}findDiffStart(e,n=0){return Nne(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Cne(this,e,n,r)}findIndex(e){if(e==0)return __(0,e);if(e==this.size)return __(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),s=r+a.nodeSize;if(s>=e)return s==e?__(n+1,s):__(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return Mt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Mt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Mt.empty;let n,r=0;for(let a=0;a<e.length;a++){let s=e[a];r+=s.nodeSize,a&&s.isText&&e[a-1].sameMarkup(s)?(n||(n=e.slice(0,a)),n[n.length-1]=s.withText(n[n.length-1].text+s.text)):n&&n.push(s)}return new Mt(n||e,r)}static from(e){if(!e)return Mt.empty;if(e instanceof Mt)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Mt([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}Mt.empty=new Mt([],0);const Xj={index:0,offset:0};function __(t,e){return Xj.index=t,Xj.offset=e,Xj}function $N(t,e){if(t===e)return!0;if(!(t&&typeof t=="object")||!(e&&typeof e=="object"))return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!$N(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!$N(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let $r=class yR{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,r=!1;for(let a=0;a<e.length;a++){let s=e[a];if(this.eq(s))return e;if(this.type.excludes(s.type))n||(n=e.slice(0,a));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,a)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return e.slice(0,n).concat(e.slice(n+1));return e}isInSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return!0;return!1}eq(e){return this==e||this.type==e.type&&$N(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);let a=r.create(n.attrs);return r.checkAttrs(a.attrs),a}static sameSet(e,n){if(e==n)return!0;if(e.length!=n.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(n[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return yR.none;if(e instanceof yR)return[e];let n=e.slice();return n.sort((r,a)=>r.type.rank-a.type.rank),n}};$r.none=[];class VN extends Error{}class Wt{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Ane(this.content,e+this.openStart,n);return r&&new Wt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Wt(kne(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return Wt.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Wt(Mt.fromJSON(e,n.content),r,a)}static maxOpen(e,n=!0){let r=0,a=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)a++;return new Wt(e,r,a)}}Wt.empty=new Wt(Mt.empty,0,0);function kne(t,e,n){let{index:r,offset:a}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(a==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(kne(s.content,e-a-1,n-a-1)))}function Ane(t,e,n,r){let{index:a,offset:s}=t.findIndex(e),o=t.maybeChild(a);if(s==e||o.isText)return r&&!r.canReplace(a,a,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=Ane(o.content,e-s-1,n,o);return l&&t.replaceChild(a,o.copy(l))}function J$e(t,e,n){if(n.openStart>t.depth)throw new VN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new VN("Inconsistent open depths");return Tne(t,e,n,0)}function Tne(t,e,n,r){let a=t.index(r),s=t.node(r);if(a==e.index(r)&&r<t.depth-n.openStart){let o=Tne(t,e,n,r+1);return s.copy(s.content.replaceChild(a,o))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&t.depth==r&&e.depth==r){let o=t.parent,l=o.content;return Sf(o,l.cut(0,t.parentOffset).append(n.content).append(l.cut(e.parentOffset)))}else{let{start:o,end:l}=eVe(n,t);return Sf(s,Pne(t,o,l,e,r))}else return Sf(s,qN(t,e,r))}function Mne(t,e){if(!e.type.compatibleContent(t.type))throw new VN("Cannot join "+e.type.name+" onto "+t.type.name)}function vR(t,e,n){let r=t.node(n);return Mne(r,e.node(n)),r}function wf(t,e){let n=e.length-1;n>=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Qy(t,e,n,r){let a=(e||t).node(n),s=0,o=e?e.index(n):a.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(wf(t.nodeAfter,r),s++));for(let l=s;l<o;l++)wf(a.child(l),r);e&&e.depth==n&&e.textOffset&&wf(e.nodeBefore,r)}function Sf(t,e){return t.type.checkContent(e),t.copy(e)}function Pne(t,e,n,r,a){let s=t.depth>a&&vR(t,e,a+1),o=r.depth>a&&vR(n,r,a+1),l=[];return Qy(null,t,a,l),s&&o&&e.index(a)==n.index(a)?(Mne(s,o),wf(Sf(s,Pne(t,e,n,r,a+1)),l)):(s&&wf(Sf(s,qN(t,e,a+1)),l),Qy(e,n,a,l),o&&wf(Sf(o,qN(n,r,a+1)),l)),Qy(r,null,a,l),new Mt(l)}function qN(t,e,n){let r=[];if(Qy(null,t,n,r),t.depth>n){let a=vR(t,e,n+1);wf(Sf(a,qN(t,e,n+1)),r)}return Qy(e,null,n,r),new Mt(r)}function eVe(t,e){let n=e.depth-t.openStart,a=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)a=e.node(s).copy(Mt.from(a));return{start:a.resolveNoCache(t.openStart+n),end:a.resolveNoCache(a.content.size-t.openEnd-n)}}class Gv{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=e.child(n);return r?e.child(n).cut(r):a}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)a+=r.child(s).nodeSize;return a}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return $r.none;if(this.textOffset)return e.child(n).marks;let r=e.maybeChild(n-1),a=e.maybeChild(n);if(!r){let l=r;r=a,a=l}let s=r.marks;for(var o=0;o<s.length;o++)s[o].type.spec.inclusive===!1&&(!a||!s[o].isInSet(a.marks))&&(s=s[o--].removeFromSet(s));return s}marksAcross(e){let n=this.parent.maybeChild(this.index());if(!n||!n.isInline)return null;let r=n.marks,a=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!a||!r[s].isInSet(a.marks))&&(r=r[s--].removeFromSet(r));return r}sharedDepth(e){for(let n=this.depth;n>0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new GN(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let n=1;n<=this.depth;n++)e+=(e?"/":"")+this.node(n).type.name+"_"+this.index(n-1);return e+":"+this.parentOffset}static resolve(e,n){if(!(n>=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,a+c),!u||(o=o.child(l),o.isText))break;s=u-1,a+=c+1}return new Gv(n,r,s)}static resolveCached(e,n){let r=u9.get(e);if(r)for(let s=0;s<r.elts.length;s++){let o=r.elts[s];if(o.pos==n)return o}else u9.set(e,r=new tVe);let a=r.elts[r.i]=Gv.resolve(e,n);return r.i=(r.i+1)%nVe,a}}class tVe{constructor(){this.elts=[],this.i=0}}const nVe=12,u9=new WeakMap;class GN{constructor(e,n,r){this.$from=e,this.$to=n,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const rVe=Object.create(null);let Uh=class wR{constructor(e,n,r,a=$r.none){this.type=e,this.attrs=n,this.marks=a,this.content=r||Mt.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,n,r,a=0){this.content.nodesBetween(e,n,r,a,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,n,r,a){return this.content.textBetween(e,n,r,a)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,n,r){return this.type==e&&$N(this.attrs,n||e.defaultAttrs||rVe)&&$r.sameSet(this.marks,r||$r.none)}copy(e=null){return e==this.content?this:new wR(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new wR(this.type,this.attrs,this.content,e)}cut(e,n=this.content.size){return e==0&&n==this.content.size?this:this.copy(this.content.cut(e,n))}slice(e,n=this.content.size,r=!1){if(e==n)return Wt.empty;let a=this.resolve(e),s=this.resolve(n),o=r?0:a.sharedDepth(n),l=a.start(o),u=a.node(o).content.cut(a.pos-l,s.pos-l);return new Wt(u,a.depth-o,s.depth-o)}replace(e,n,r){return J$e(this.resolve(e),this.resolve(n),r)}nodeAt(e){for(let n=this;;){let{index:r,offset:a}=n.content.findIndex(e);if(n=n.maybeChild(r),!n)return null;if(a==e||n.isText)return n;e-=a+1}}childAfter(e){let{index:n,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(n),index:n,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:n,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(n),index:n,offset:r};let a=this.content.child(n-1);return{node:a,index:n-1,offset:r-a.nodeSize}}resolve(e){return Gv.resolveCached(this,e)}resolveNoCache(e){return Gv.resolve(this,e)}rangeHasMark(e,n,r){let a=!1;return n>e&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Ene(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=Mt.empty,a=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,a,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=a;c<s;c++)if(!this.type.allowsMarks(r.child(c).marks))return!1;return!0}canReplaceWith(e,n,r,a){if(a&&!this.type.allowsMarks(a))return!1;let s=this.contentMatchAt(e).matchType(r),o=s&&s.matchFragment(this.content,n);return o?o.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=$r.none;for(let n=0;n<this.marks.length;n++){let r=this.marks[n];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!$r.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(n=>n.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let a=Mt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,a,r);return s.type.checkAttrs(s.attrs),s}};Uh.prototype.text=void 0;class WN extends Uh{constructor(e,n,r,a){if(super(e,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Ene(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new WN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new WN(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Ene(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Xf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new aVe(e,n);if(r.next==null)return Xf.empty;let a=jne(r);r.next&&r.err("Unexpected trailing text");let s=dVe(uVe(a));return hVe(s,r),s}matchType(e){for(let n=0;n<this.next.length;n++)if(this.next[n].type==e)return this.next[n].next;return null}matchFragment(e,n=0,r=e.childCount){let a=this;for(let s=n;a&&s<r;s++)a=a.matchType(e.child(s).type);return a}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:n}=this.next[e];if(!(n.isText||n.hasRequiredAttrs()))return n}return null}compatible(e){for(let n=0;n<this.next.length;n++)for(let r=0;r<e.next.length;r++)if(this.next[n].type==e.next[r].type)return!0;return!1}fillBefore(e,n=!1,r=0){let a=[this];function s(o,l){let c=o.matchFragment(e,r);if(c&&(!n||c.validEnd))return Mt.from(l.map(u=>u.createAndFill()));for(let u=0;u<o.next.length;u++){let{type:d,next:h}=o.next[u];if(!(d.isText||d.hasRequiredAttrs())&&a.indexOf(h)==-1){a.push(h);let f=s(h,l.concat(d));if(f)return f}}return null}return s(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let n=this.computeWrapping(e);return this.wrapCache.push(e,n),n}computeWrapping(e){let n=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let a=r.shift(),s=a.match;if(s.matchType(e)){let o=[];for(let l=a;l.type;l=l.via)o.push(l.type);return o.reverse()}for(let o=0;o<s.next.length;o++){let{type:l,next:c}=s.next[o];!l.isLeaf&&!l.hasRequiredAttrs()&&!(l.name in n)&&(!a.type||c.validEnd)&&(r.push({match:l.contentMatch,type:l,via:a}),n[l.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let a=0;a<r.next.length;a++)e.indexOf(r.next[a].next)==-1&&n(r.next[a].next)}return n(this),e.map((r,a)=>{let s=a+(r.validEnd?"*":" ")+" ";for(let o=0;o<r.next.length;o++)s+=(o?", ":"")+r.next[o].type.name+"->"+e.indexOf(r.next[o].next);return s}).join(`
  8160. `)}}Xf.empty=new Xf(!0);class aVe{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function jne(t){let e=[];do e.push(iVe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function iVe(t){let e=[];do e.push(sVe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function sVe(t){let e=cVe(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=oVe(t,e);else break;return e}function d9(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function oVe(t,e){let n=d9(t),r=n;return t.eat(",")&&(t.next!="}"?r=d9(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function lVe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let a=[];for(let s in n){let o=n[s];o.isInGroup(e)&&a.push(o)}return a.length==0&&t.err("No node type or group '"+e+"' found"),a}function cVe(t){if(t.eat("(")){let e=jne(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=lVe(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function uVe(t){let e=[[]];return a(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let u={term:c,to:l};return e[o].push(u),u}function a(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,u)=>c.concat(s(u,l)),[]);if(o.type=="seq")for(let c=0;;c++){let u=s(o.exprs[c],l);if(c==o.exprs.length-1)return u;a(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),a(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return a(s(o.expr,l),c),a(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let u=0;u<o.min;u++){let d=n();a(s(o.expr,c),d),c=d}if(o.max==-1)a(s(o.expr,c),c);else for(let u=o.min;u<o.max;u++){let d=n();r(c,d),a(s(o.expr,c),d),c=d}return[r(c)]}else{if(o.type=="name")return[r(l,void 0,o.value)];throw new Error("Unknown expr type")}}}}function Dne(t,e){return e-t}function h9(t,e){let n=[];return r(e),n.sort(Dne);function r(a){let s=t[a];if(s.length==1&&!s[0].term)return r(s[0].to);n.push(a);for(let o=0;o<s.length;o++){let{term:l,to:c}=s[o];!l&&n.indexOf(c)==-1&&r(c)}}}function dVe(t){let e=Object.create(null);return n(h9(t,0));function n(r){let a=[];r.forEach(o=>{t[o].forEach(({term:l,to:c})=>{if(!l)return;let u;for(let d=0;d<a.length;d++)a[d][0]==l&&(u=a[d][1]);h9(t,c).forEach(d=>{u||a.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let s=e[r.join(",")]=new Xf(r.indexOf(t.length-1)>-1);for(let o=0;o<a.length;o++){let l=a[o][1].sort(Dne);s.next.push({type:a[o][0],next:e[l.join(",")]||n(l)})}return s}}function hVe(t,e){for(let n=0,r=[t];n<r.length;n++){let a=r[n],s=!a.validEnd,o=[];for(let l=0;l<a.next.length;l++){let{type:c,next:u}=a.next[l];o.push(c.name),s&&!(c.isText||c.hasRequiredAttrs())&&(s=!1),r.indexOf(u)==-1&&r.push(u)}s&&e.err("Only non-generatable nodes ("+o.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function Rne(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function Fne(t,e){let n=Object.create(null);for(let r in t){let a=e&&e[r];if(a===void 0){let s=t[r];if(s.hasDefault)a=s.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=a}return n}function Lne(t,e,n,r){for(let a in e)if(!(a in t))throw new RangeError(`Unsupported attribute ${a} for ${n} of type ${a}`);for(let a in t){let s=t[a];s.validate&&s.validate(e[a])}}function One(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new fVe(t,r,e[r]);return n}let m9=class Ine{constructor(e,n,r){this.name=e,this.schema=n,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=One(e,r.attrs),this.defaultAttrs=Rne(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Xf.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Fne(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Uh(this,this.computeAttrs(e),Mt.from(n),$r.setFrom(r))}createChecked(e=null,n,r){return n=Mt.from(n),this.checkContent(n),new Uh(this,this.computeAttrs(e),n,$r.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Mt.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let a=this.contentMatch.matchFragment(n),s=a&&a.fillBefore(Mt.empty,!0);return s?new Uh(this,e,n.append(s),$r.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){Lne(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;n<e.length;n++)if(!this.allowsMarkType(e[n].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let n;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?n&&n.push(e[r]):n||(n=e.slice(0,r));return n?n.length?n:$r.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,o)=>r[s]=new Ine(s,n,o));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function mVe(t,e,n){let r=n.split("|");return a=>{let s=a===null?"null":typeof a;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class fVe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?mVe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class lA{constructor(e,n,r,a){this.name=e,this.rank=n,this.schema=r,this.spec=a,this.attrs=One(e,a.attrs),this.excluded=null;let s=Rne(this.attrs);this.instance=s?new $r(this,s):null}create(e=null){return!e&&this.instance?this.instance:new $r(this,Fne(this.attrs,e))}static compile(e,n){let r=Object.create(null),a=0;return e.forEach((s,o)=>r[s]=new lA(s,a++,n,o)),r}removeFromSet(e){for(var n=0;n<e.length;n++)e[n].type==this&&(e=e.slice(0,n).concat(e.slice(n+1)),n--);return e}isInSet(e){for(let n=0;n<e.length;n++)if(e[n].type==this)return e[n]}checkAttrs(e){Lne(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class zne{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in e)n[a]=e[a];n.nodes=Wi.from(e.nodes),n.marks=Wi.from(e.marks||{}),this.nodes=m9.compile(this.spec.nodes,this),this.marks=lA.compile(this.spec.marks,this);let r=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let s=this.nodes[a],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Xf.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?f9(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let a in this.marks){let s=this.marks[a],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:f9(this,o.split(" "))}this.nodeFromJSON=a=>Uh.fromJSON(this,a),this.markFromJSON=a=>$r.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,a){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof m9){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,a)}text(e,n){let r=this.nodes.text;return new WN(r,r.defaultAttrs,e,$r.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function f9(t,e){let n=[];for(let r=0;r<e.length;r++){let a=e[r],s=t.marks[a],o=s;if(s)n.push(s);else for(let l in t.marks){let c=t.marks[l];(a=="_"||c.spec.group&&c.spec.group.split(" ").indexOf(a)>-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function pVe(t){return t.tag!=null}function gVe(t){return t.style!=null}let Zy=class SR{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(pVe(a))this.tags.push(a);else if(gVe(a)){let s=/[^=]*/.exec(a.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let s=e.nodes[a.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new g9(this,n,!1);return r.addAll(e,$r.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new g9(this,n,!0);return r.addAll(e,$r.none,n.from,n.to),Wt.maxOpen(r.finish())}matchTag(e,n,r){for(let a=r?this.tags.indexOf(r)+1:0;a<this.tags.length;a++){let s=this.tags[a];if(yVe(e,s.tag)&&(s.namespace===void 0||e.namespaceURI==s.namespace)&&(!s.context||n.matchesContext(s.context))){if(s.getAttrs){let o=s.getAttrs(e);if(o===!1)continue;s.attrs=o||void 0}return s}}}matchStyle(e,n,r,a){for(let s=a?this.styles.indexOf(a)+1:0;s<this.styles.length;s++){let o=this.styles[s],l=o.style;if(!(l.indexOf(e)!=0||o.context&&!r.matchesContext(o.context)||l.length>e.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(a){let s=a.priority==null?50:a.priority,o=0;for(;o<n.length;o++){let l=n[o];if((l.priority==null?50:l.priority)<s)break}n.splice(o,0,a)}for(let a in e.marks){let s=e.marks[a].spec.parseDOM;s&&s.forEach(o=>{r(o=b9(o)),o.mark||o.ignore||o.clearMark||(o.mark=a)})}for(let a in e.nodes){let s=e.nodes[a].spec.parseDOM;s&&s.forEach(o=>{r(o=b9(o)),o.node||o.ignore||o.mark||(o.node=a)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new SR(e,SR.schemaRules(e)))}};const Une={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},bVe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Bne={ol:!0,ul:!0},Wv=1,_R=2,Jy=4;function p9(t,e,n){return e!=null?(e?Wv:0)|(e==="full"?_R:0):t&&t.whitespace=="pre"?Wv|_R:n&~Jy}class N_{constructor(e,n,r,a,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=a,this.options=o,this.content=[],this.activeMarks=$r.none,this.match=s||(o&Jy?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Mt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(e.type))?(this.match=r,a):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Wv)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-a[0].length))}}let n=Mt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Mt.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Une.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class g9{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,s,o=p9(null,n.preserveWhitespace,0)|(r?Jy:0);a?s=new N_(a.type,a.attrs,$r.none,!0,n.topMatch||a.type.contentMatch,o):r?s=new N_(null,null,$r.none,!0,null,o):s=new N_(e.schema.topNodeType,null,$r.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,a=this.top,s=a.options&_R?"full":this.localPreserveWS||(a.options&Wv)>0,{schema:o}=this.parser;if(s==="full"||a.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
  8161. `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c<l.length;c++)c&&this.insertNode(o.linebreakReplacement.create(),n,!0),l[c]&&this.insertNode(o.text(l[c]),n,!/\S/.test(l[c]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let l=a.content[a.content.length-1],c=e.previousSibling;(!l||c&&c.nodeName=="BR"||l.isText&&/[ \t\r\n\u000c]$/.test(l.text))&&(r=r.slice(1))}r&&this.insertNode(o.text(r),n,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,n,r){let a=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let o=e.nodeName.toLowerCase(),l;Bne.hasOwnProperty(o)&&this.parser.normalizeLists&&xVe(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(l=this.parser.matchTag(e,this,r));e:if(c?c.ignore:bVe.hasOwnProperty(o))this.findInside(e),this.ignoreFallback(e,n);else if(!c||c.skip||c.closeParent){c&&c.closeParent?this.open=Math.max(0,this.open-1):c&&c.skip.nodeType&&(e=c.skip);let u,d=this.needsBlock;if(Une.hasOwnProperty(o))s.content.length&&s.content[0].isInline&&this.open&&(this.open--,s=this.top),u=!0,s.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,n);break e}let h=c&&c.skip?n:this.readStyles(e,n);h&&this.addAll(e,h),u&&this.sync(s),this.needsBlock=d}else{let u=this.readStyles(e,n);u&&this.addElementByRule(e,c,u,c.consuming===!1?l:void 0)}this.localPreserveWS=a}leafFallback(e,n){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
  8162. `),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let a=0;a<this.parser.matchedStyles.length;a++){let s=this.parser.matchedStyles[a],o=r.getPropertyValue(s);if(o)for(let l=void 0;;){let c=this.parser.matchStyle(s,o,this,l);if(!c)break;if(c.ignore)return null;if(c.clearMark?n=n.filter(u=>!c.clearMark(u)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,a){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(a)this.addElement(e,r,a);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,a){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=a==null?null:e.childNodes[a];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let a,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!a||a.length>u.length+l)&&(a=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!a)return null;this.sync(s);for(let o=0;o<a.length;o++)n=this.enterInner(a[o],null,n,!1);return n}insertNode(e,n,r){if(e.isInline&&this.needsBlock&&!this.top.type){let s=this.textblockFromContext();s&&(n=this.enterInner(s,null,n))}let a=this.findPlace(e,n,r);if(a){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let o=$r.none;for(let l of a.concat(e.marks))(s.type?s.type.allowsMarkType(l.type):x9(l.type,e.type))&&(o=l.addToSet(o));return s.content.push(e.mark(o)),!0}return!1}enter(e,n,r,a){let s=this.findPlace(e.create(n),r,!1);return s&&(s=this.enterInner(e,n,r,!0,a)),s}enterInner(e,n,r,a=!1,s){this.closeExtra();let o=this.top;o.match=o.match&&o.match.matchType(e);let l=p9(e,s,o.options);o.options&Jy&&o.content.length==0&&(l|=Jy);let c=$r.none;return r=r.filter(u=>(o.type?o.type.allowsMarkType(u.type):x9(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new N_(e,n,c,a,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Wv)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)e+=r[a].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&e.nodeType==1&&e.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(e,n,r){if(e!=n&&this.find)for(let a=0;a<this.find.length;a++)this.find[a].pos==null&&e.nodeType==1&&e.contains(this.find[a].node)&&n.compareDocumentPosition(this.find[a].node)&(r?2:4)&&(this.find[a].pos=this.currentPos)}findInText(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&(this.find[n].pos=this.currentPos-(e.nodeValue.length-this.find[n].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(a?0:1),o=(l,c)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let d=c>0||c==0&&a?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!d||d.name!=u&&!d.isInGroup(u))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function xVe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Bne.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function yVe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function b9(t){let e={};for(let n in t)e[n]=t[n];return e}function x9(t,e){let n=e.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c<l.edgeCount;c++){let{type:u,next:d}=l.edge(c);if(u==e||s.indexOf(d)<0&&o(d))return!0}};if(o(a.contentMatch))return!0}}class sp{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=Yj(n).createDocumentFragment());let a=r,s=[];return e.forEach(o=>{if(s.length||o.marks.length){let l=0,c=0;for(;l<s.length&&c<o.marks.length;){let u=o.marks[c];if(!this.marks[u.type.name]){c++;continue}if(!u.eq(s[l][0])||u.type.spec.spanning===!1)break;l++,c++}for(;l<s.length;)a=s.pop()[1];for(;c<o.marks.length;){let u=o.marks[c++],d=this.serializeMark(u,o.isInline,n);d&&(s.push([u,a]),a.appendChild(d.dom),a=d.contentDOM||d.dom)}}a.appendChild(this.serializeNodeInner(o,n))}),r}serializeNodeInner(e,n){let{dom:r,contentDOM:a}=o1(Yj(n),this.nodes[e.type.name](e),null,e.attrs);if(a){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,a)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let a=e.marks.length-1;a>=0;a--){let s=this.serializeMark(e.marks[a],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let a=this.marks[e.type.name];return a&&o1(Yj(r),a(e,n),null,e.attrs)}static renderSpec(e,n,r=null,a){return o1(e,n,r,a)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new sp(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=y9(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return y9(e.marks)}}function y9(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function Yj(t){return t.document||window.document}const v9=new WeakMap;function vVe(t){let e=v9.get(t);return e===void 0&&v9.set(t,e=wVe(t)),e}function wVe(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let a=0;a<r.length;a++)n(r[a]);else for(let a in r)n(r[a])}return n(t),e}function o1(t,e,n,r){if(typeof e=="string")return{dom:t.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let a=e[0],s;if(typeof a!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(s=vVe(r))&&s.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=a.indexOf(" ");o>0&&(n=a.slice(0,o),a=a.slice(o+1));let l,c=n?t.createElementNS(n,a):t.createElement(a),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let h in u)if(u[h]!=null){let f=h.indexOf(" ");f>0?c.setAttributeNS(h.slice(0,f),h.slice(f+1),u[h]):h=="style"&&c.style?c.style.cssText=u[h]:c.setAttribute(h,u[h])}}for(let h=d;h<e.length;h++){let f=e[h];if(f===0){if(h<e.length-1||h>d)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:x}=o1(t,f,n,r);if(c.appendChild(p),x){if(l)throw new RangeError("Multiple content holes");l=x}}}return{dom:c,contentDOM:l}}const Hne=65535,$ne=Math.pow(2,16);function SVe(t,e){return t+e*$ne}function w9(t){return t&Hne}function _Ve(t){return(t-(t&Hne))/$ne}const Vne=1,qne=2,l1=4,Gne=8;class NR{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Gne)>0}get deletedBefore(){return(this.delInfo&(Vne|l1))>0}get deletedAfter(){return(this.delInfo&(qne|l1))>0}get deletedAcross(){return(this.delInfo&l1)>0}}class Mo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Mo.empty)return Mo.empty}recover(e){let n=0,r=w9(e);if(!this.inverted)for(let a=0;a<r;a++)n+=this.ranges[a*3+2]-this.ranges[a*3+1];return this.ranges[r*3]+n+_Ve(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,r){let a=0,s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?a:0);if(c>e)break;let u=this.ranges[l+s],d=this.ranges[l+o],h=c+u;if(e<=h){let f=u?e==c?-1:e==h?1:n:n,p=c+a+(f<0?0:d);if(r)return p;let x=e==(n<0?c:h)?null:SVe(l/3,e-c),v=e==c?qne:e==h?Vne:l1;return(n<0?e!=c:e!=h)&&(v|=Gne),new NR(p,v,x)}a+=d-u}return r?e+a:new NR(e+a,0,null)}touches(e,n){let r=0,a=w9(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;l<this.ranges.length;l+=3){let c=this.ranges[l]-(this.inverted?r:0);if(c>e)break;let u=this.ranges[l+s],d=c+u;if(e<=d&&l==a*3)return!0;r+=this.ranges[l+o]-u}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,s=0;a<this.ranges.length;a+=3){let o=this.ranges[a],l=o-(this.inverted?s:0),c=o+(this.inverted?0:s),u=this.ranges[a+n],d=this.ranges[a+r];e(l,l+u,c,c+d),s+=d-u}}invert(){return new Mo(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?Mo.empty:new Mo(e<0?[0,-e,0]:[0,0,e])}}Mo.empty=new Mo([]);class Kv{constructor(e,n,r=0,a=e?e.length:0){this.mirror=n,this.from=r,this.to=a,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new Kv(this._maps,this.mirror,e,n)}appendMap(e,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(e){for(let n=0,r=this._maps.length;n<e._maps.length;n++){let a=e.getMirror(n);this.appendMap(e._maps[n],a!=null&&a<n?r+a:void 0)}}getMirror(e){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==e)return this.mirror[n+(n%2?-1:1)]}}setMirror(e,n){this.mirror||(this.mirror=[]),this.mirror.push(e,n)}appendMappingInverted(e){for(let n=e.maps.length-1,r=this._maps.length+e._maps.length;n>=0;n--){let a=e.getMirror(n);this.appendMap(e._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let e=new Kv;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,r){let a=0;for(let s=this.from;s<this.to;s++){let o=this._maps[s],l=o.mapResult(e,n);if(l.recover!=null){let c=this.getMirror(s);if(c!=null&&c>s&&c<this.to){s=c,e=this._maps[c].recover(l.recover);continue}}a|=l.delInfo,e=l.pos}return r?e:new NR(e,a,null)}}const Qj=Object.create(null);class ws{getMap(){return Mo.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Qj[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in Qj)throw new RangeError("Duplicate use of step JSON ID "+e);return Qj[e]=n,n.prototype.jsonID=e,n}}class ti{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new ti(e,null)}static fail(e){return new ti(null,e)}static fromReplace(e,n,r,a){try{return ti.ok(e.replace(n,r,a))}catch(s){if(s instanceof VN)return ti.fail(s.message);throw s}}}function x4(t,e,n){let r=[];for(let a=0;a<t.childCount;a++){let s=t.child(a);s.content.size&&(s=s.copy(x4(s.content,e,s))),s.isInline&&(s=e(s,n,a)),r.push(s)}return Mt.fromArray(r)}class Nh extends ws{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=e.resolve(this.from),a=r.node(r.sharedDepth(this.to)),s=new Wt(x4(n.content,(o,l)=>!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),a),n.openStart,n.openEnd);return ti.fromReplace(e,this.from,this.to,s)}invert(){return new Wl(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Nh(n.pos,r.pos,this.mark)}merge(e){return e instanceof Nh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Nh(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Nh(n.from,n.to,e.markFromJSON(n.mark))}}ws.jsonID("addMark",Nh);class Wl extends ws{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new Wt(x4(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),e),n.openStart,n.openEnd);return ti.fromReplace(e,this.from,this.to,r)}invert(){return new Nh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Wl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Wl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Wl(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Wl(n.from,n.to,e.markFromJSON(n.mark))}}ws.jsonID("removeMark",Wl);class Ch extends ws{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ti.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return ti.fromReplace(e,this.pos,this.pos+1,new Wt(Mt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;a<n.marks.length;a++)if(!n.marks[a].isInSet(r))return new Ch(this.pos,n.marks[a]);return new Ch(this.pos,this.mark)}}return new Yf(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Ch(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Ch(n.pos,e.markFromJSON(n.mark))}}ws.jsonID("addNodeMark",Ch);class Yf extends ws{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ti.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return ti.fromReplace(e,this.pos,this.pos+1,new Wt(Mt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Ch(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Yf(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Yf(n.pos,e.markFromJSON(n.mark))}}ws.jsonID("removeNodeMark",Yf);class Di extends ws{constructor(e,n,r,a=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=a}apply(e){return this.structure&&CR(e,this.from,this.to)?ti.fail("Structure replace would overwrite content"):ti.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Mo([this.from,this.to-this.from,this.slice.size])}invert(e){return new Di(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new Di(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Di)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let n=this.slice.size+e.slice.size==0?Wt.empty:new Wt(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Di(this.from,this.to+(e.to-e.from),n,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let n=this.slice.size+e.slice.size==0?Wt.empty:new Wt(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Di(e.from,this.to,n,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new Di(n.from,n.to,Wt.fromJSON(e,n.slice),!!n.structure)}}ws.jsonID("replace",Di);class Fi extends ws{constructor(e,n,r,a,s,o,l=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=a,this.slice=s,this.insert=o,this.structure=l}apply(e){if(this.structure&&(CR(e,this.from,this.gapFrom)||CR(e,this.gapTo,this.to)))return ti.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return ti.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?ti.fromReplace(e,this.from,this.to,r):ti.fail("Content does not fit in gap")}getMap(){return new Mo([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new Fi(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),a=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||a<n.pos||s>r.pos?null:new Fi(n.pos,r.pos,a,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Fi(n.from,n.to,n.gapFrom,n.gapTo,Wt.fromJSON(e,n.slice),n.insert,!!n.structure)}}ws.jsonID("replaceAround",Fi);function CR(t,e,n){let r=t.resolve(e),a=n-e,s=r.depth;for(;a>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,a--;if(a>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;a>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,a--}}return!1}function NVe(t,e,n,r){let a=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&d.type.allowsMarkType(r.type)){let f=Math.max(u,e),p=Math.min(u+c.nodeSize,n),x=r.addToSet(h);for(let v=0;v<h.length;v++)h[v].isInSet(x)||(o&&o.to==f&&o.mark.eq(h[v])?o.to=p:a.push(o=new Wl(f,p,h[v])));l&&l.to==f?l.to=p:s.push(l=new Nh(f,p,r))}}),a.forEach(c=>t.step(c)),s.forEach(c=>t.step(c))}function CVe(t,e,n,r){let a=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof lA){let u=o.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let u=Math.min(l+o.nodeSize,n);for(let d=0;d<c.length;d++){let h=c[d],f;for(let p=0;p<a.length;p++){let x=a[p];x.step==s-1&&h.eq(a[p].style)&&(f=x)}f?(f.to=u,f.step=s):a.push({style:h,from:Math.max(l,e),to:u,step:s})}}}),a.forEach(o=>t.step(new Wl(o.from,o.to,o.style)))}function y4(t,e,n,r=n.contentMatch,a=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c<s.childCount;c++){let u=s.child(c),d=l+u.nodeSize,h=r.matchType(u.type);if(!h)o.push(new Di(l,d,Wt.empty));else{r=h;for(let f=0;f<u.marks.length;f++)n.allowsMarkType(u.marks[f].type)||t.step(new Wl(l,d,u.marks[f]));if(a&&u.isText&&n.whitespace!="pre"){let f,p=/\r?\n|\r/g,x;for(;f=p.exec(u.text);)x||(x=new Wt(Mt.from(n.schema.text(" ",n.allowedMarks(u.marks))),0,0)),o.push(new Di(l+f.index,l+f.index+f[0].length,x))}}l=d}if(!r.validEnd){let c=r.fillBefore(Mt.empty,!0);t.replace(l,l,new Wt(c,0,0))}for(let c=o.length-1;c>=0;c--)t.step(o[c])}function kVe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function lx(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,a=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+a,c=t.$to.indexAfter(r)-s;if(r<t.depth&&o.canReplace(l,c,n))return r;if(r==0||o.type.spec.isolating||!kVe(o,l,c))break;l&&(a=1),c<o.childCount&&(s=1)}return null}function AVe(t,e,n){let{$from:r,$to:a,depth:s}=e,o=r.before(s+1),l=a.after(s+1),c=o,u=l,d=Mt.empty,h=0;for(let x=s,v=!1;x>n;x--)v||r.index(x)>0?(v=!0,d=Mt.from(r.node(x).copy(d)),h++):c--;let f=Mt.empty,p=0;for(let x=s,v=!1;x>n;x--)v||a.after(x+1)<a.end(x)?(v=!0,f=Mt.from(a.node(x).copy(f)),p++):u++;t.step(new Fi(c,u,o,l,new Wt(d.append(f),h,p),d.size-h,!0))}function v4(t,e,n=null,r=t){let a=TVe(t,e),s=a&&MVe(r,e);return s?a.map(S9).concat({type:e,attrs:n}).concat(s.map(S9)):null}function S9(t){return{type:t,attrs:null}}function TVe(t,e){let{parent:n,startIndex:r,endIndex:a}=t,s=n.contentMatchAt(r).findWrapping(e);if(!s)return null;let o=s.length?s[0]:e;return n.canReplaceWith(r,a,o)?s:null}function MVe(t,e){let{parent:n,startIndex:r,endIndex:a}=t,s=n.child(r),o=e.contentMatch.findWrapping(s.type);if(!o)return null;let c=(o.length?o[o.length-1]:e).contentMatch;for(let u=r;c&&u<a;u++)c=c.matchType(n.child(u).type);return!c||!c.validEnd?null:o}function PVe(t,e,n){let r=Mt.empty;for(let o=n.length-1;o>=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Mt.from(n[o].type.create(n[o].attrs,r))}let a=e.start,s=e.end;t.step(new Fi(a,s,a,s,new Wt(r,0,0),n.length,!0))}function EVe(t,e,n,r,a){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof a=="function"?a(o):a;if(o.isTextblock&&!o.hasMarkup(r,c)&&jVe(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!x?u=!1:!p&&x&&(u=!0)}u===!1&&Kne(t,o,l,s),y4(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),h=d.map(l,1),f=d.map(l+o.nodeSize,1);return t.step(new Fi(h,f,h+1,f-1,new Wt(Mt.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&Wne(t,o,l,s),!1}})}function Wne(t,e,n,r){e.forEach((a,s)=>{if(a.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(a.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Kne(t,e,n,r){e.forEach((a,s)=>{if(a.type==a.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(`
  8163. `))}})}function jVe(t,e,n){let r=t.resolve(e),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function DVe(t,e,n,r,a){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let o=n.create(r,null,a||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,o);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new Fi(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new Wt(Mt.from(o),0,0),1,!0))}function Yu(t,e,n=1,r){let a=t.resolve(e),s=a.depth-n,o=r&&r[r.length-1]||a.parent;if(s<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!o.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let u=a.depth-1,d=n-2;u>s;u--,d--){let h=a.node(u),f=a.index(u);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(f,h.childCount),x=r&&r[d+1];x&&(p=p.replaceChild(0,x.type.create(x.attrs)));let v=r&&r[d]||h;if(!h.canReplace(f+1,h.childCount)||!v.type.validContent(p))return!1}let l=a.indexAfter(s),c=r&&r[0];return a.node(s).canReplaceWith(l,l,c?c.type:a.node(s+1).type)}function RVe(t,e,n=1,r){let a=t.doc.resolve(e),s=Mt.empty,o=Mt.empty;for(let l=a.depth,c=a.depth-n,u=n-1;l>c;l--,u--){s=Mt.from(a.node(l).copy(s));let d=r&&r[u];o=Mt.from(d?d.type.create(d.attrs,o):a.node(l).copy(o))}t.step(new Di(e,e,new Wt(s.append(o),n,n),!0))}function sm(t,e){let n=t.resolve(e),r=n.index();return Xne(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function FVe(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let a=0;a<e.childCount;a++){let s=e.child(a),o=s.type==r?t.type.schema.nodes.text:s.type;if(n=n.matchType(o),!n||!t.type.allowsMarks(s.marks))return!1}return n.validEnd}function Xne(t,e){return!!(t&&e&&!t.isLeaf&&FVe(t,e))}function cA(t,e,n=-1){let r=t.resolve(e);for(let a=r.depth;;a--){let s,o,l=r.index(a);if(a==r.depth?(s=r.nodeBefore,o=r.nodeAfter):n>0?(s=r.node(a+1),l++,o=r.node(a).maybeChild(l)):(s=r.node(a).maybeChild(l-1),o=r.node(a+1)),s&&!s.isTextblock&&Xne(s,o)&&r.node(a).canReplace(l,l+1))return e;if(a==0)break;e=n<0?r.before(a):r.after(a)}}function LVe(t,e,n){let r=null,{linebreakReplacement:a}=t.doc.type.schema,s=t.doc.resolve(e-n),o=s.node().type;if(a&&o.inlineContent){let d=o.whitespace=="pre",h=!!o.contentMatch.matchType(a);d&&!h?r=!1:!d&&h&&(r=!0)}let l=t.steps.length;if(r===!1){let d=t.doc.resolve(e+n);Kne(t,d.node(),d.before(),l)}o.inlineContent&&y4(t,e+n-1,o,s.node().contentMatchAt(s.index()),r==null);let c=t.mapping.slice(l),u=c.map(e-n);if(t.step(new Di(u,c.map(e+n,-1),Wt.empty,!0)),r===!0){let d=t.doc.resolve(u);Wne(t,d.node(),d.before(),t.steps.length)}return t}function OVe(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let a=r.depth-1;a>=0;a--){let s=r.index(a);if(r.node(a).canReplaceWith(s,s,n))return r.before(a+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let s=r.indexAfter(a);if(r.node(a).canReplaceWith(s,s,n))return r.after(a+1);if(s<r.node(a).childCount)return null}return null}function Yne(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let a=n.content;for(let s=0;s<n.openStart;s++)a=a.firstChild.content;for(let s=1;s<=(n.openStart==0&&n.size?2:1);s++)for(let o=r.depth;o>=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,c=r.index(o)+(l>0?1:0),u=r.node(o),d=!1;if(s==1)d=u.canReplace(c,c,a);else{let h=u.contentMatchAt(c).findWrapping(a.firstChild.type);d=h&&u.canReplaceWith(c,c,h[0])}if(d)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function uA(t,e,n=e,r=Wt.empty){if(e==n&&!r.size)return null;let a=t.resolve(e),s=t.resolve(n);return Qne(a,s,r)?new Di(e,n,r):new IVe(a,s,r).fit()}function Qne(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class IVe{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Mt.empty;for(let a=0;a<=e.depth;a++){let s=e.node(a);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(a))})}for(let a=e.depth;a>0;a--)this.placed=Mt.from(e.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let u=this.findFittable();u?this.placeNodes(u):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,a=this.close(e<0?this.$to:r.doc.resolve(e));if(!a)return null;let s=this.placed,o=r.depth,l=a.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let c=new Wt(s,o,l);return e>-1?new Fi(r.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Di(r.pos,a.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r<e;r++){let s=n.firstChild;if(n.childCount>1&&(a=0),s.type.spec.isolating&&a<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let a,s=null;r?(s=Zj(this.unplaced.content,r-1).firstChild,a=s.content):a=this.unplaced.content;let o=a.firstChild;for(let l=this.depth;l>=0;l--){let{type:c,match:u}=this.frontier[l],d,h=null;if(n==1&&(o?u.matchType(o.type)||(h=u.fillBefore(Mt.from(o),!1)):s&&c.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:h};if(n==2&&o&&(d=u.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:d};if(s&&u.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,a=Zj(e,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Wt(e,n+1,Math.max(r,a.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,a=Zj(e,n);if(a.childCount<=1&&n>0){let s=e.size-n<=n+a.size;this.unplaced=new Wt(Ry(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new Wt(Ry(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:a,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let v=0;v<s.length;v++)this.openFrontierNode(s[v]);let o=this.unplaced,l=r?r.content:o.content,c=o.openStart-e,u=0,d=[],{match:h,type:f}=this.frontier[n];if(a){for(let v=0;v<a.childCount;v++)d.push(a.child(v));h=h.matchFragment(a)}let p=l.size+e-(o.content.size-o.openEnd);for(;u<l.childCount;){let v=l.child(u),g=h.matchType(v.type);if(!g)break;u++,(u>1||c==0||v.content.size)&&(h=g,d.push(Zne(v.mark(f.allowedMarks(v.marks)),u==1?c:0,u==l.childCount?p:-1)))}let x=u==l.childCount;x||(p=-1),this.placed=Fy(this.placed,n,Mt.from(d)),this.frontier[n].match=h,x&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,g=l;v<p;v++){let y=g.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),g=y.content}this.unplaced=x?e==0?Wt.empty:new Wt(Ry(o.content,e-1,1),e-1,p<0?o.openEnd:e-1):new Wt(Ry(o.content,e,u),o.openStart,o.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],n;if(!e.type.isTextblock||!Jj(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,a=this.$to.after(r);for(;r>1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),o=Jj(e,n,a,r,s);if(o){for(let l=n-1;l>=0;l--){let{match:c,type:u}=this.frontier[l],d=Jj(e,l,u,c,!0);if(!d||d.childCount)continue e}return{depth:n,fit:o,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Fy(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let a=e.node(r),s=a.type.contentMatch.fillBefore(a.content,!0,e.index(r));this.openFrontierNode(a.type,a.attrs,s)}return e}openFrontierNode(e,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(e),this.placed=Fy(this.placed,this.depth,Mt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Mt.empty,!0);n.childCount&&(this.placed=Fy(this.placed,this.frontier.length,n))}}function Ry(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Ry(t.firstChild.content,e-1,n)))}function Fy(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Fy(t.lastChild.content,e-1,n)))}function Zj(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function Zne(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,Zne(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(Mt.empty,!0)))),t.copy(r)}function Jj(t,e,n,r,a){let s=t.node(e),o=a?t.indexAfter(e):t.index(e);if(o==s.childCount&&!n.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!zVe(n,s.content,o)?l:null}function zVe(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function UVe(t){return t.spec.defining||t.spec.definingForContent}function BVe(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let a=t.doc.resolve(e),s=t.doc.resolve(n);if(Qne(a,s,r))return t.step(new Di(e,n,r));let o=ere(a,s);o[o.length-1]==0&&o.pop();let l=-(a.depth+1);o.unshift(l);for(let f=a.depth,p=a.pos-1;f>0;f--,p--){let x=a.node(f).type.spec;if(x.defining||x.definingAsContext||x.isolating)break;o.indexOf(f)>-1?l=f:a.before(f)==p&&o.splice(1,0,-f)}let c=o.indexOf(l),u=[],d=r.openStart;for(let f=r.content,p=0;;p++){let x=f.firstChild;if(u.push(x),p==r.openStart)break;f=x.content}for(let f=d-1;f>=0;f--){let p=u[f],x=UVe(p.type);if(x&&!p.sameMarkup(a.node(Math.abs(l)-1)))d=f;else if(x||!p.type.isTextblock)break}for(let f=r.openStart;f>=0;f--){let p=(f+d+1)%(r.openStart+1),x=u[p];if(x)for(let v=0;v<o.length;v++){let g=o[(v+c)%o.length],y=!0;g<0&&(y=!1,g=-g);let _=a.node(g-1),N=a.index(g-1);if(_.canReplaceWith(N,N,x.type,x.marks))return t.replace(a.before(g),y?s.after(g):n,new Wt(Jne(r.content,0,r.openStart,p),p,r.openEnd))}}let h=t.steps.length;for(let f=o.length-1;f>=0&&(t.replace(e,n,r),!(t.steps.length>h));f--){let p=o[f];p<0||(e=a.before(p),n=s.after(p))}}function Jne(t,e,n,r,a){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(Jne(s.content,e+1,n,r,s)))}if(e>r){let s=a.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Mt.empty,!0))}return t}function HVe(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let a=OVe(t.doc,e,r.type);a!=null&&(e=n=a)}t.replaceRange(e,n,new Wt(Mt.from(r),0,0))}function $Ve(t,e,n){let r=t.doc.resolve(e),a=t.doc.resolve(n),s=ere(r,a);for(let o=0;o<s.length;o++){let l=s[o],c=o==s.length-1;if(c&&l==0||r.node(l).type.contentMatch.validEnd)return t.delete(r.start(l),a.end(l));if(l>0&&(c||r.node(l-1).canReplace(r.index(l-1),a.indexAfter(l-1))))return t.delete(r.before(l),a.after(l))}for(let o=1;o<=r.depth&&o<=a.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&a.end(o)-n!=a.depth-o&&r.start(o-1)==a.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),a.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function ere(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let a=r;a>=0;a--){let s=t.start(a);if(s<t.pos-(t.depth-a)||e.end(a)>e.pos+(e.depth-a)||t.node(a).type.spec.isolating||e.node(a).type.spec.isolating)break;(s==e.start(a)||a==t.depth&&a==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&a&&e.start(a-1)==s-1)&&n.push(a)}return n}class ab extends ws{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return ti.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return ti.fromReplace(e,this.pos,this.pos+1,new Wt(Mt.from(a),0,n.isLeaf?0:1))}getMap(){return Mo.empty}invert(e){return new ab(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new ab(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new ab(n.pos,n.attr,n.value)}}ws.jsonID("attr",ab);class Xv extends ws{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let a in e.attrs)n[a]=e.attrs[a];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return ti.ok(r)}getMap(){return Mo.empty}invert(e){return new Xv(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Xv(n.attr,n.value)}}ws.jsonID("docAttr",Xv);let Pb=class extends Error{};Pb=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Pb.prototype=Object.create(Error.prototype);Pb.prototype.constructor=Pb;Pb.prototype.name="TransformError";class tre{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Kv}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Pb(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let a=this.mapping.maps[r];r&&(e=a.map(e,1),n=a.map(n,-1)),a.forEach((s,o,l,c)=>{e=Math.min(e,l),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=Wt.empty){let a=uA(this.doc,e,n,r);return a&&this.step(a),this}replaceWith(e,n,r){return this.replace(e,n,new Wt(Mt.from(r),0,0))}delete(e,n){return this.replace(e,n,Wt.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return BVe(this,e,n,r),this}replaceRangeWith(e,n,r){return HVe(this,e,n,r),this}deleteRange(e,n){return $Ve(this,e,n),this}lift(e,n){return AVe(this,e,n),this}join(e,n=1){return LVe(this,e,n),this}wrap(e,n){return PVe(this,e,n),this}setBlockType(e,n=e,r,a=null){return EVe(this,e,n,r,a),this}setNodeMarkup(e,n,r=null,a){return DVe(this,e,n,r,a),this}setNodeAttribute(e,n,r){return this.step(new ab(e,n,r)),this}setDocAttribute(e,n){return this.step(new Xv(e,n)),this}addNodeMark(e,n){return this.step(new Ch(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof $r)n.isInSet(r.marks)&&this.step(new Yf(e,n));else{let a=r.marks,s,o=[];for(;s=n.isInSet(a);)o.push(new Yf(e,s)),a=s.removeFromSet(a);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return RVe(this,e,n,r),this}addMark(e,n,r){return NVe(this,e,n,r),this}removeMark(e,n,r){return CVe(this,e,n,r),this}clearIncompatible(e,n,r){return y4(this,e,n,r),this}}const e2=Object.create(null);class Bn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new VVe(e.min(n),e.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let n=0;n<e.length;n++)if(e[n].$from.pos!=e[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,n=Wt.empty){let r=n.content.lastChild,a=null;for(let l=0;l<n.openEnd;l++)a=r,r=r.lastChild;let s=e.steps.length,o=this.ranges;for(let l=0;l<o.length;l++){let{$from:c,$to:u}=o[l],d=e.mapping.slice(s);e.replaceRange(d.map(c.pos),d.map(u.pos),l?Wt.empty:n),l==0&&C9(e,s,(r?r.isInline:a&&a.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,a=this.ranges;for(let s=0;s<a.length;s++){let{$from:o,$to:l}=a[s],c=e.mapping.slice(r),u=c.map(o.pos),d=c.map(l.pos);s?e.deleteRange(u,d):(e.replaceRangeWith(u,d,n),C9(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let a=e.parent.inlineContent?new wn(e):Rg(e.node(0),e.parent,e.pos,e.index(),n,r);if(a)return a;for(let s=e.depth-1;s>=0;s--){let o=n<0?Rg(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Rg(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new Fo(e.node(0))}static atStart(e){return Rg(e,e,0,0,1)||new Fo(e)}static atEnd(e){return Rg(e,e,e.content.size,e.childCount,-1)||new Fo(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=e2[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in e2)throw new RangeError("Duplicate use of selection JSON ID "+e);return e2[e]=n,n.prototype.jsonID=e,n}getBookmark(){return wn.between(this.$anchor,this.$head).getBookmark()}}Bn.prototype.visible=!0;class VVe{constructor(e,n){this.$from=e,this.$to=n}}let _9=!1;function N9(t){!_9&&!t.parent.inlineContent&&(_9=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class wn extends Bn{constructor(e,n=e){N9(e),N9(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return Bn.near(r);let a=e.resolve(n.map(this.anchor));return new wn(a.parent.inlineContent?a:r,r)}replace(e,n=Wt.empty){if(super.replace(e,n),n==Wt.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof wn&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new dA(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new wn(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let a=e.resolve(n);return new this(a,r==n?a:e.resolve(r))}static between(e,n,r){let a=e.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let s=Bn.findFrom(n,r,!0)||Bn.findFrom(n,-r,!0);if(s)n=s.$head;else return Bn.near(n,r)}return e.parent.inlineContent||(a==0?e=n:(e=(Bn.findFrom(e,-r,!0)||Bn.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=a<0&&(e=n))),new wn(e,n)}}Bn.jsonID("text",wn);class dA{constructor(e,n){this.anchor=e,this.head=n}map(e){return new dA(e.map(this.anchor),e.map(this.head))}resolve(e){return wn.between(e.resolve(this.anchor),e.resolve(this.head))}}class cn extends Bn{constructor(e){let n=e.nodeAfter,r=e.node(0).resolve(e.pos+n.nodeSize);super(e,r),this.node=n}map(e,n){let{deleted:r,pos:a}=n.mapResult(this.anchor),s=e.resolve(a);return r?Bn.near(s):new cn(s)}content(){return new Wt(Mt.from(this.node),0,0)}eq(e){return e instanceof cn&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new w4(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new cn(e.resolve(n.anchor))}static create(e,n){return new cn(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}cn.prototype.visible=!1;Bn.jsonID("node",cn);class w4{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new dA(r,r):new w4(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&cn.isSelectable(r)?new cn(n):Bn.near(n)}}class Fo extends Bn{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=Wt.empty){if(n==Wt.empty){e.delete(0,e.doc.content.size);let r=Bn.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new Fo(e)}map(e){return new Fo(e)}eq(e){return e instanceof Fo}getBookmark(){return qVe}}Bn.jsonID("all",Fo);const qVe={map(){return this},resolve(t){return new Fo(t)}};function Rg(t,e,n,r,a,s=!1){if(e.inlineContent)return wn.create(t,n);for(let o=r-(a>0?0:1);a>0?o<e.childCount:o>=0;o+=a){let l=e.child(o);if(l.isAtom){if(!s&&cn.isSelectable(l))return cn.create(t,n-(a<0?l.nodeSize:0))}else{let c=Rg(t,l,n+a,a<0?l.childCount:0,a,s);if(c)return c}n+=l.nodeSize*a}return null}function C9(t,e,n){let r=t.steps.length-1;if(r<e)return;let a=t.steps[r];if(!(a instanceof Di||a instanceof Fi))return;let s=t.mapping.maps[r],o;s.forEach((l,c,u,d)=>{o==null&&(o=d)}),t.setSelection(Bn.near(t.doc.resolve(o),n))}const k9=1,C_=2,A9=4;class GVe extends tre{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|k9)&~C_,this.storedMarks=null,this}get selectionSet(){return(this.updated&k9)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=C_,this}ensureMarks(e){return $r.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&C_)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~C_,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||$r.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let a=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(a.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=r==n?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,a.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Bn.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=A9,this}get scrolledIntoView(){return(this.updated&A9)>0}}function T9(t,e){return!e||!t?t:t.bind(e)}class Ly{constructor(e,n,r){this.name=e,this.init=T9(n.init,r),this.apply=T9(n.apply,r)}}const WVe=[new Ly("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Ly("selection",{init(t,e){return t.selection||Bn.atStart(e.doc)},apply(t){return t.selection}}),new Ly("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Ly("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class t2{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=WVe.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Ly(r.key,r.spec.state,r))})}}class Vg{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=n){let a=this.config.plugins[r];if(a.spec.filterTransaction&&!a.spec.filterTransaction.call(a,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),a=null;for(;;){let s=!1;for(let o=0;o<this.config.plugins.length;o++){let l=this.config.plugins[o];if(l.spec.appendTransaction){let c=a?a[o].n:0,u=a?a[o].state:this,d=c<n.length&&l.spec.appendTransaction.call(l,c?n.slice(c):n,u,r);if(d&&r.filterTransaction(d,o)){if(d.setMeta("appendedTransaction",e),!a){a=[];for(let h=0;h<this.config.plugins.length;h++)a.push(h<o?{state:r,n:n.length}:{state:this,n:0})}n.push(d),r=r.applyInner(d),s=!0}a&&(a[o]={state:r,n:n.length})}}if(!s)return{state:r,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new Vg(this.config),r=this.config.fields;for(let a=0;a<r.length;a++){let s=r[a];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new GVe(this)}static create(e){let n=new t2(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new Vg(n);for(let a=0;a<n.fields.length;a++)r[n.fields[a].name]=n.fields[a].init(e,r);return r}reconfigure(e){let n=new t2(this.schema,e.plugins),r=n.fields,a=new Vg(n);for(let s=0;s<r.length;s++){let o=r[s].name;a[o]=this.hasOwnProperty(o)?this[o]:r[s].init(e,a)}return a}toJSON(e){let n={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(n.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=e[r],s=a.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(a,this[a.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let a=new t2(e.schema,e.plugins),s=new Vg(a);return a.fields.forEach(o=>{if(o.name=="doc")s.doc=Uh.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=Bn.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let c=r[l],u=c.spec.state;if(c.key==o.name&&u&&u.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=u.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function nre(t,e,n){for(let r in t){let a=t[r];a instanceof Function?a=a.bind(e):r=="handleDOMEvents"&&(a=nre(a,e,{})),n[r]=a}return n}class ya{constructor(e){this.spec=e,this.props={},e.props&&nre(e.props,this,this.props),this.key=e.key?e.key.key:rre("plugin")}getState(e){return e[this.key]}}const n2=Object.create(null);function rre(t){return t in n2?t+"$"+ ++n2[t]:(n2[t]=0,t+"$")}class Ni{constructor(e="key"){this.key=rre(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const S4=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function are(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const ire=(t,e,n)=>{let r=are(t,n);if(!r)return!1;let a=_4(r);if(!a){let o=r.blockRange(),l=o&&lx(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=a.nodeBefore;if(fre(t,a,e,-1))return!0;if(r.parent.content.size==0&&(Eb(s,"end")||cn.isSelectable(s)))for(let o=r.depth;;o--){let l=uA(t.doc,r.before(o),r.after(o),Wt.empty);if(l&&l.slice.size<l.to-l.from){if(e){let c=t.tr.step(l);c.setSelection(Eb(s,"end")?Bn.findFrom(c.doc.resolve(c.mapping.map(a.pos,-1)),-1):cn.create(c.doc,a.pos-s.nodeSize)),e(c.scrollIntoView())}return!0}if(o==1||r.node(o-1).childCount>1)break}return s.isAtom&&a.depth==r.depth-1?(e&&e(t.tr.delete(a.pos-s.nodeSize,a.pos).scrollIntoView()),!0):!1},KVe=(t,e,n)=>{let r=are(t,n);if(!r)return!1;let a=_4(r);return a?sre(t,a,e):!1},XVe=(t,e,n)=>{let r=lre(t,n);if(!r)return!1;let a=N4(r);return a?sre(t,a,e):!1};function sre(t,e,n){let r=e.nodeBefore,a=r,s=e.pos-1;for(;!a.isTextblock;s--){if(a.type.spec.isolating)return!1;let d=a.lastChild;if(!d)return!1;a=d}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let d=l.firstChild;if(!d)return!1;l=d}let u=uA(t.doc,s,c,Wt.empty);if(!u||u.from!=s||u instanceof Di&&u.slice.size>=c-s)return!1;if(n){let d=t.tr.step(u);d.setSelection(wn.create(d.doc,s)),n(d.scrollIntoView())}return!0}function Eb(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const ore=(t,e,n)=>{let{$head:r,empty:a}=t.selection,s=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=_4(r)}let o=s&&s.nodeBefore;return!o||!cn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(cn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function _4(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function lre(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const cre=(t,e,n)=>{let r=lre(t,n);if(!r)return!1;let a=N4(r);if(!a)return!1;let s=a.nodeAfter;if(fre(t,a,e,1))return!0;if(r.parent.content.size==0&&(Eb(s,"start")||cn.isSelectable(s))){let o=uA(t.doc,r.before(),r.after(),Wt.empty);if(o&&o.slice.size<o.to-o.from){if(e){let l=t.tr.step(o);l.setSelection(Eb(s,"start")?Bn.findFrom(l.doc.resolve(l.mapping.map(a.pos)),1):cn.create(l.doc,l.mapping.map(a.pos))),e(l.scrollIntoView())}return!0}}return s.isAtom&&a.depth==r.depth-1?(e&&e(t.tr.delete(a.pos,a.pos+s.nodeSize).scrollIntoView()),!0):!1},ure=(t,e,n)=>{let{$head:r,empty:a}=t.selection,s=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;s=N4(r)}let o=s&&s.nodeAfter;return!o||!cn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(cn.create(t.doc,s.pos)).scrollIntoView()),!0)};function N4(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}const YVe=(t,e)=>{let n=t.selection,r=n instanceof cn,a;if(r){if(n.node.isTextblock||!sm(t.doc,n.from))return!1;a=n.from}else if(a=cA(t.doc,n.from,-1),a==null)return!1;if(e){let s=t.tr.join(a);r&&s.setSelection(cn.create(s.doc,a-t.doc.resolve(a).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},QVe=(t,e)=>{let n=t.selection,r;if(n instanceof cn){if(n.node.isTextblock||!sm(t.doc,n.to))return!1;r=n.to}else if(r=cA(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},ZVe=(t,e)=>{let{$from:n,$to:r}=t.selection,a=n.blockRange(r),s=a&&lx(a);return s==null?!1:(e&&e(t.tr.lift(a,s).scrollIntoView()),!0)},dre=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
  8164. `).scrollIntoView()),!0)};function C4(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}const JVe=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),s=n.indexAfter(-1),o=C4(a.contentMatchAt(s));if(!o||!a.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(Bn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},hre=(t,e)=>{let n=t.selection,{$from:r,$to:a}=n;if(n instanceof Fo||r.parent.inlineContent||a.parent.inlineContent)return!1;let s=C4(a.parent.contentMatchAt(a.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&a.index()<a.parent.childCount?r:a).pos,l=t.tr.insert(o,s.createAndFill());l.setSelection(wn.create(l.doc,o+1)),e(l.scrollIntoView())}return!0},mre=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(Yu(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),a=r&&lx(r);return a==null?!1:(e&&e(t.tr.lift(r,a).scrollIntoView()),!0)};function eqe(t){return(e,n)=>{let{$from:r,$to:a}=e.selection;if(e.selection instanceof cn&&e.selection.node.isBlock)return!r.parentOffset||!Yu(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,c=!1,u=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){c=r.end(p)==r.pos+(r.depth-p),u=r.start(p)==r.pos-(r.depth-p),l=C4(r.node(p-1).contentMatchAt(r.indexAfter(p-1))),s.unshift(c&&l?{type:l}:null),o=p;break}else{if(p==1)return!1;s.unshift(null)}let d=e.tr;(e.selection instanceof wn||e.selection instanceof Fo)&&d.deleteSelection();let h=d.mapping.map(r.pos),f=Yu(d.doc,h,s.length,s);if(f||(s[0]=l?{type:l}:null,f=Yu(d.doc,h,s.length,s)),!f)return!1;if(d.split(h,s.length,s),!c&&u&&r.node(o).type!=l){let p=d.mapping.map(r.before(o)),x=d.doc.resolve(p);l&&r.node(o-1).canReplaceWith(x.index(),x.index()+1,l)&&d.setNodeMarkup(d.mapping.map(r.before(o)),l)}return n&&n(d.scrollIntoView()),!0}}const tqe=eqe(),nqe=(t,e)=>{let{$from:n,to:r}=t.selection,a,s=n.sharedDepth(r);return s==0?!1:(a=n.before(s),e&&e(t.tr.setSelection(cn.create(t.doc,a))),!0)};function rqe(t,e,n){let r=e.nodeBefore,a=e.nodeAfter,s=e.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(a.isTextblock||sm(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function fre(t,e,n,r){let a=e.nodeBefore,s=e.nodeAfter,o,l,c=a.type.spec.isolating||s.type.spec.isolating;if(!c&&rqe(t,e,n))return!0;let u=!c&&e.parent.canReplace(e.index(),e.index()+1);if(u&&(o=(l=a.contentMatchAt(a.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let p=e.pos+s.nodeSize,x=Mt.empty;for(let y=o.length-1;y>=0;y--)x=Mt.from(o[y].create(null,x));x=Mt.from(a.copy(x));let v=t.tr.step(new Fi(e.pos-1,p,e.pos,p,new Wt(x,1,0),o.length,!0)),g=v.doc.resolve(p+2*o.length);g.nodeAfter&&g.nodeAfter.type==a.type&&sm(v.doc,g.pos)&&v.join(g.pos),n(v.scrollIntoView())}return!0}let d=s.type.spec.isolating||r>0&&c?null:Bn.findFrom(e,1),h=d&&d.$from.blockRange(d.$to),f=h&&lx(h);if(f!=null&&f>=e.depth)return n&&n(t.tr.lift(h,f).scrollIntoView()),!0;if(u&&Eb(s,"start",!0)&&Eb(a,"end")){let p=a,x=[];for(;x.push(p),!p.isTextblock;)p=p.lastChild;let v=s,g=1;for(;!v.isTextblock;v=v.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,v.content)){if(n){let y=Mt.empty;for(let N=x.length-1;N>=0;N--)y=Mt.from(x[N].copy(y));let _=t.tr.step(new Fi(e.pos-x.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new Wt(y,x.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function pre(t){return function(e,n){let r=e.selection,a=t<0?r.$from:r.$to,s=a.depth;for(;a.node(s).isInline;){if(!s)return!1;s--}return a.node(s).isTextblock?(n&&n(e.tr.setSelection(wn.create(e.doc,t<0?a.start(s):a.end(s)))),!0):!1}}const aqe=pre(-1),iqe=pre(1);function sqe(t,e=null){return function(n,r){let{$from:a,$to:s}=n.selection,o=a.blockRange(s),l=o&&v4(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function M9(t,e=null){return function(n,r){let a=!1;for(let s=0;s<n.selection.ranges.length&&!a;s++){let{$from:{pos:o},$to:{pos:l}}=n.selection.ranges[s];n.doc.nodesBetween(o,l,(c,u)=>{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)a=!0;else{let d=n.doc.resolve(u),h=d.index();a=d.parent.canReplaceWith(h,h+1,t)}})}if(!a)return!1;if(r){let s=n.tr;for(let o=0;o<n.selection.ranges.length;o++){let{$from:{pos:l},$to:{pos:c}}=n.selection.ranges[o];s.setBlockType(l,c,t,e)}r(s.scrollIntoView())}return!0}}function k4(...t){return function(e,n,r){for(let a=0;a<t.length;a++)if(t[a](e,n,r))return!0;return!1}}k4(S4,ire,ore);k4(S4,cre,ure);k4(dre,hre,mre,tqe);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function oqe(t,e=null){return function(n,r){let{$from:a,$to:s}=n.selection,o=a.blockRange(s);if(!o)return!1;let l=r?n.tr:null;return lqe(l,o,t,e)?(r&&r(l.scrollIntoView()),!0):!1}}function lqe(t,e,n,r=null){let a=!1,s=e,o=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);s=new GN(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new GN(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),a=!0}let l=v4(s,n,r,e);return l?(t&&cqe(t,e,l,a,n),!0):!1}function cqe(t,e,n,r,a){let s=Mt.empty;for(let d=n.length-1;d>=0;d--)s=Mt.from(n[d].type.create(n[d].attrs,s));t.step(new Fi(e.start-(r?2:0),e.end,e.start,e.end,new Wt(s,0,0),n.length,!0));let o=0;for(let d=0;d<n.length;d++)n[d].type==a&&(o=d+1);let l=n.length-o,c=e.start+n.length-(r?2:0),u=e.parent;for(let d=e.startIndex,h=e.endIndex,f=!0;d<h;d++,f=!1)!f&&Yu(t.doc,c,l)&&(t.split(c,l),c+=2*l),c+=u.child(d).nodeSize;return t}function uqe(t){return function(e,n){let{$from:r,$to:a}=e.selection,s=r.blockRange(a,o=>o.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?dqe(e,n,t,s):hqe(e,n,s):!0:!1}}function dqe(t,e,n,r){let a=t.tr,s=r.end,o=r.$to.end(r.depth);s<o&&(a.step(new Fi(s-1,o,s,o,new Wt(Mt.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new GN(a.doc.resolve(r.$from.pos),a.doc.resolve(o),r.depth));const l=lx(r);if(l==null)return!1;a.lift(r,l);let c=a.doc.resolve(a.mapping.map(s,-1)-1);return sm(a.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&a.join(c.pos),e(a.scrollIntoView()),!0}function hqe(t,e,n){let r=t.tr,a=n.parent;for(let p=n.end,x=n.endIndex-1,v=n.startIndex;x>v;x--)p-=a.child(x).nodeSize,r.delete(p-1,p+1);let s=r.doc.resolve(n.start),o=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==a.childCount,u=s.node(-1),d=s.index(-1);if(!u.canReplace(d+(l?0:1),d+1,o.content.append(c?Mt.empty:Mt.from(a))))return!1;let h=s.pos,f=h+o.nodeSize;return r.step(new Fi(h-(l?1:0),f+(c?1:0),h+1,f-1,new Wt((l?Mt.empty:Mt.from(a.copy(Mt.empty))).append(c?Mt.empty:Mt.from(a.copy(Mt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function mqe(t){return function(e,n){let{$from:r,$to:a}=e.selection,s=r.blockRange(a,u=>u.childCount>0&&u.firstChild.type==t);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,c=l.child(o-1);if(c.type!=t)return!1;if(n){let u=c.lastChild&&c.lastChild.type==l.type,d=Mt.from(u?t.create():null),h=new Wt(Mt.from(t.create(null,Mt.from(l.type.create(null,d)))),u?3:1,0),f=s.start,p=s.end;n(e.tr.step(new Fi(f-(u?3:1),p,f,p,h,1,!0)).scrollIntoView())}return!0}}const Zi=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},jb=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let kR=null;const Eu=function(t,e,n){let r=kR||(kR=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},fqe=function(){kR=null},Qf=function(t,e,n,r){return n&&(P9(t,e,n,r,-1)||P9(t,e,n,r,1))},pqe=/^(img|br|input|textarea|hr)$/i;function P9(t,e,n,r,a){for(var s;;){if(t==n&&e==r)return!0;if(e==(a<0?0:dl(t))){let o=t.parentNode;if(!o||o.nodeType!=1||$0(t)||pqe.test(t.nodeName)||t.contentEditable=="false")return!1;e=Zi(t)+(a<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(a<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=a;else return!1;else t=o,e=a<0?dl(t):0}else return!1}}function dl(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function gqe(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=dl(t)}else if(t.parentNode&&!$0(t))e=Zi(t),t=t.parentNode;else return null}}function bqe(t,e){for(;;){if(t.nodeType==3&&e<t.nodeValue.length)return t;if(t.nodeType==1&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!$0(t))e=Zi(t)+1,t=t.parentNode;else return null}}function xqe(t,e,n){for(let r=e==0,a=e==dl(t);r||a;){if(t==n)return!0;let s=Zi(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,a=a&&s==dl(t)}}function $0(t){let e;for(let n=t;n&&!(e=n.pmViewDesc);n=n.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}const hA=function(t){return t.focusNode&&Qf(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Qm(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function yqe(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function vqe(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(dl(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(dl(r.startContainer),r.startOffset)}}}const Bc=typeof navigator<"u"?navigator:null,E9=typeof document<"u"?document:null,om=Bc&&Bc.userAgent||"",AR=/Edge\/(\d+)/.exec(om),gre=/MSIE \d/.exec(om),TR=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(om),ao=!!(gre||TR||AR),Bh=gre?document.documentMode:TR?+TR[1]:AR?+AR[1]:0,gl=!ao&&/gecko\/(\d+)/i.test(om);gl&&+(/Firefox\/(\d+)/.exec(om)||[0,0])[1];const MR=!ao&&/Chrome\/(\d+)/.exec(om),es=!!MR,bre=MR?+MR[1]:0,xs=!ao&&!!Bc&&/Apple Computer/.test(Bc.vendor),Db=xs&&(/Mobile\/\w+/.test(om)||!!Bc&&Bc.maxTouchPoints>2),al=Db||(Bc?/Mac/.test(Bc.platform):!1),xre=Bc?/Win/.test(Bc.platform):!1,Hu=/Android \d/.test(om),V0=!!E9&&"webkitFontSmoothing"in E9.documentElement.style,wqe=V0?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Sqe(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function Nu(t,e){return typeof t=="number"?t:t[e]}function _qe(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function j9(t,e,n){let r=t.someProp("scrollThreshold")||0,a=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=jb(o);continue}let l=o,c=l==s.body,u=c?Sqe(s):_qe(l),d=0,h=0;if(e.top<u.top+Nu(r,"top")?h=-(u.top-e.top+Nu(a,"top")):e.bottom>u.bottom-Nu(r,"bottom")&&(h=e.bottom-e.top>u.bottom-u.top?e.top+Nu(a,"top")-u.top:e.bottom-u.bottom+Nu(a,"bottom")),e.left<u.left+Nu(r,"left")?d=-(u.left-e.left+Nu(a,"left")):e.right>u.right-Nu(r,"right")&&(d=e.right-u.right+Nu(a,"right")),d||h)if(c)s.defaultView.scrollBy(d,h);else{let p=l.scrollLeft,x=l.scrollTop;h&&(l.scrollTop+=h),d&&(l.scrollLeft+=d);let v=l.scrollLeft-p,g=l.scrollTop-x;e={left:e.left-v,top:e.top-g,right:e.right-v,bottom:e.bottom-g}}let f=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(f))break;o=f=="absolute"?o.offsetParent:jb(o)}}function Nqe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,a;for(let s=(e.left+e.right)/2,o=n+1;o<Math.min(innerHeight,e.bottom);o+=5){let l=t.root.elementFromPoint(s,o);if(!l||l==t.dom||!t.dom.contains(l))continue;let c=l.getBoundingClientRect();if(c.top>=n-20){r=l,a=c.top;break}}return{refDOM:r,refTop:a,stack:yre(t.dom)}}function yre(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=jb(r));return e}function Cqe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;vre(n,r==0?0:r-e)}function vre(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:a,left:s}=t[n];r.scrollTop!=a+e&&(r.scrollTop=a+e),r.scrollLeft!=s&&(r.scrollLeft=s)}}let kg=null;function kqe(t){if(t.setActive)return t.setActive();if(kg)return t.focus(kg);let e=yre(t);t.focus(kg==null?{get preventScroll(){return kg={preventScroll:!0},!0}}:void 0),kg||(kg=!1,vre(e,0))}function wre(t,e){let n,r=2e8,a,s=0,o=e.top,l=e.top,c,u;for(let d=t.firstChild,h=0;d;d=d.nextSibling,h++){let f;if(d.nodeType==1)f=d.getClientRects();else if(d.nodeType==3)f=Eu(d).getClientRects();else continue;for(let p=0;p<f.length;p++){let x=f[p];if(x.top<=o&&x.bottom>=l){o=Math.max(x.bottom,o),l=Math.min(x.top,l);let v=x.left>e.left?x.left-e.left:x.right<e.left?e.left-x.right:0;if(v<r){n=d,r=v,a=v&&n.nodeType==3?{left:x.right<e.left?x.right:x.left,top:e.top}:e,d.nodeType==1&&v&&(s=h+(e.left>=(x.left+x.right)/2?1:0));continue}}else x.top>e.top&&!c&&x.left<=e.left&&x.right>=e.left&&(c=d,u={left:Math.max(x.left,Math.min(x.right,e.left)),top:x.top});!n&&(e.left>=x.right&&e.top>=x.top||e.left>=x.left&&e.top>=x.bottom)&&(s=h+1)}}return!n&&c&&(n=c,a=u,r=0),n&&n.nodeType==3?Aqe(n,a):!n||r&&n.nodeType==1?{node:t,offset:s}:wre(n,a)}function Aqe(t,e){let n=t.nodeValue.length,r=document.createRange(),a;for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let o=ah(r,1);if(o.top!=o.bottom&&A4(e,o)){a={node:t,offset:s+(e.left>=(o.left+o.right)/2?1:0)};break}}return r.detach(),a||{node:t,offset:0}}function A4(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function Tqe(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function Mqe(t,e,n){let{node:r,offset:a}=wre(e,n),s=-1;if(r.nodeType==1&&!r.firstChild){let o=r.getBoundingClientRect();s=o.left!=o.right&&n.left>(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(r,a,s)}function Pqe(t,e,n,r){let a=-1;for(let s=e,o=!1;s!=t.dom;){let l=t.docView.nearestDesc(s,!0),c;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&c.left>r.left||c.top>r.top?a=l.posBefore:(!o&&c.right<r.left||c.bottom<r.top)&&(a=l.posAfter),o=!0),!l.contentDOM&&a<0&&!l.node.isText))return(l.node.isBlock?r.top<(c.top+c.bottom)/2:r.left<(c.left+c.right)/2)?l.posBefore:l.posAfter;s=l.dom.parentNode}return a>-1?a:t.docView.posFromDOM(e,n,-1)}function Sre(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let a=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),s=a;;){let o=t.childNodes[s];if(o.nodeType==1){let l=o.getClientRects();for(let c=0;c<l.length;c++){let u=l[c];if(A4(e,u))return Sre(o,e,u)}}if((s=(s+1)%r)==a)break}return t}function Eqe(t,e){let n=t.dom.ownerDocument,r,a=0,s=vqe(n,e.left,e.top);s&&({node:r,offset:a}=s);let o=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),l;if(!o||!t.dom.contains(o.nodeType!=1?o.parentNode:o)){let u=t.dom.getBoundingClientRect();if(!A4(e,u)||(o=Sre(t.dom,e,u),!o))return null}if(xs)for(let u=o;r&&u;u=jb(u))u.draggable&&(r=void 0);if(o=Tqe(o,e),r){if(gl&&r.nodeType==1&&(a=Math.min(a,r.childNodes.length),a<r.childNodes.length)){let d=r.childNodes[a],h;d.nodeName=="IMG"&&(h=d.getBoundingClientRect()).right<=e.left&&h.bottom>e.top&&a++}let u;V0&&a&&r.nodeType==1&&(u=r.childNodes[a-1]).nodeType==1&&u.contentEditable=="false"&&u.getBoundingClientRect().top>=e.top&&a--,r==t.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(l=Pqe(t,r,a,e))}l==null&&(l=Mqe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function D9(t){return t.top<t.bottom||t.left<t.right}function ah(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(D9(r))return r}return Array.prototype.find.call(n,D9)||t.getBoundingClientRect()}const jqe=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function _re(t,e,n){let{node:r,offset:a,atom:s}=t.docView.domFromPos(e,n<0?-1:1),o=V0||gl;if(r.nodeType==3)if(o&&(jqe.test(r.nodeValue)||(n<0?!a:a==r.nodeValue.length))){let c=ah(Eu(r,a,a),n);if(gl&&a&&/\s/.test(r.nodeValue[a-1])&&a<r.nodeValue.length){let u=ah(Eu(r,a-1,a-1),-1);if(u.top==c.top){let d=ah(Eu(r,a,a+1),-1);if(d.top!=c.top)return _y(d,d.left<u.left)}}return c}else{let c=a,u=a,d=n<0?1:-1;return n<0&&!a?(u++,d=-1):n>=0&&a==r.nodeValue.length?(c--,d=1):n<0?c--:u++,_y(ah(Eu(r,c,u),d),d<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&a&&(n<0||a==dl(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return r2(c.getBoundingClientRect(),!1)}if(s==null&&a<dl(r)){let c=r.childNodes[a];if(c.nodeType==1)return r2(c.getBoundingClientRect(),!0)}return r2(r.getBoundingClientRect(),n>=0)}if(s==null&&a&&(n<0||a==dl(r))){let c=r.childNodes[a-1],u=c.nodeType==3?Eu(c,dl(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(u)return _y(ah(u,1),!1)}if(s==null&&a<dl(r)){let c=r.childNodes[a];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let u=c?c.nodeType==3?Eu(c,0,o?0:1):c.nodeType==1?c:null:null;if(u)return _y(ah(u,-1),!0)}return _y(ah(r.nodeType==3?Eu(r):r,-n),n>=0)}function _y(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function r2(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Nre(t,e,n){let r=t.state,a=t.root.activeElement;r!=e&&t.updateState(e),a!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),a!=t.dom&&a&&a.focus()}}function Dqe(t,e,n){let r=e.selection,a=n=="up"?r.$from:r.$to;return Nre(t,e,()=>{let{node:s}=t.docView.domFromPos(a.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=_re(t,a.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let c;if(l.nodeType==1)c=l.getClientRects();else if(l.nodeType==3)c=Eu(l,0,l.nodeValue.length).getClientRects();else continue;for(let u=0;u<c.length;u++){let d=c[u];if(d.bottom>d.top+1&&(n=="up"?o.top-d.top>(d.bottom-o.top)*2:d.bottom-o.bottom>(o.bottom-d.top)*2))return!1}}return!0})}const Rqe=/[\u0590-\u08ac]/;function Fqe(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,s=!a,o=a==r.parent.content.size,l=t.domSelection();return l?!Rqe.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:Nre(t,e,()=>{let{focusNode:c,focusOffset:u,anchorNode:d,anchorOffset:h}=t.domSelectionRange(),f=l.caretBidiLevel;l.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:x,focusOffset:v}=t.domSelectionRange(),g=x&&!p.contains(x.nodeType==1?x:x.parentNode)||c==x&&u==v;try{l.collapse(d,h),c&&(c!=d||u!=h)&&l.extend&&l.extend(c,u)}catch{}return f!=null&&(l.caretBidiLevel=f),g}):r.pos==r.start()||r.pos==r.end()}let R9=null,F9=null,L9=!1;function Lqe(t,e,n){return R9==e&&F9==n?L9:(R9=e,F9=n,L9=n=="up"||n=="down"?Dqe(t,e,n):Fqe(t,e,n))}const bl=0,O9=1,lf=2,Hc=3;class q0{constructor(e,n,r,a){this.parent=e,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=bl,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n<this.children.length;n++)e+=this.children[n].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let n=0,r=this.posAtStart;;n++){let a=this.children[n];if(a==e)return r;r+=a.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,n,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let s,o;if(e==this.contentDOM)s=e.childNodes[n-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.previousSibling}for(;s&&!((o=s.pmViewDesc)&&o.parent==this);)s=s.previousSibling;return s?this.posBeforeChild(o)+o.size:this.posAtStart}else{let s,o;if(e==this.contentDOM)s=e.childNodes[n];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.nextSibling}for(;s&&!((o=s.pmViewDesc)&&o.parent==this);)s=s.nextSibling;return s?this.posBeforeChild(o):this.posAtEnd}let a;if(e==this.dom&&this.contentDOM)a=n>Zi(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!1;break}if(s.previousSibling)break}if(a==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){a=!0;break}if(s.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,a=e;a;a=a.parentNode){let s=this.getDesc(a),o;if(s&&(!n||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let a=e;a;a=a.parentNode){let s=this.getDesc(a);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let a=this.children[n],s=r+a.size;if(r==e&&s!=r){for(;!a.border&&a.children.length;)for(let o=0;o<a.children.length;o++){let l=a.children[o];if(l.size){a=l;break}}return a}if(e<s)return a.descAt(e-r-a.border);r=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,a=0;for(let s=0;r<this.children.length;r++){let o=this.children[r],l=s+o.size;if(l>e||o instanceof kre){a=e-s;break}s=l}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof Cre&&s.side>=0;r--);if(n<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?Zi(s.dom)+1:0}}else{let s,o=!0;for(;s=r<this.children.length?this.children[r]:null,!(!s||s.dom.parentNode==this.contentDOM);r++,o=!1);return s&&o&&!s.border&&!s.domAtom?s.domFromPos(0,n):{node:this.contentDOM,offset:s?Zi(s.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:n,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let a=-1,s=-1;for(let o=r,l=0;;l++){let c=this.children[l],u=o+c.size;if(a==-1&&e<=u){let d=o+c.border;if(e>=d&&n<=u-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,d);e=o;for(let h=l;h>0;h--){let f=this.children[h-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){a=Zi(f.dom)+1;break}e-=f.size}a==-1&&(a=0)}if(a>-1&&(u>n||l==this.children.length-1)){n=u;for(let d=l+1;d<this.children.length;d++){let h=this.children[d];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(-1)){s=Zi(h.dom);break}n+=h.size}s==-1&&(s=this.contentDOM.childNodes.length);break}o=u}return{node:this.contentDOM,from:e,to:n,fromOffset:a,toOffset:s}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let n=this.children[e<0?0:this.children.length-1];return n.size==0||n.emptyChildAt(e)}domAfterPos(e){let{node:n,offset:r}=this.domFromPos(e,0);if(n.nodeType!=1||r==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[r]}setSelection(e,n,r,a=!1){let s=Math.min(e,n),o=Math.max(e,n);for(let p=0,x=0;p<this.children.length;p++){let v=this.children[p],g=x+v.size;if(s>x&&o<g)return v.setSelection(e-x-v.border,n-x-v.border,r,a);x=g}let l=this.domFromPos(e,e?-1:1),c=n==e?l:this.domFromPos(n,n?-1:1),u=r.root.getSelection(),d=r.domSelectionRange(),h=!1;if((gl||xs)&&e==n){let{node:p,offset:x}=l;if(p.nodeType==3){if(h=!!(x&&p.nodeValue[x-1]==`
  8165. `),h&&x==p.nodeValue.length)for(let v=p,g;v;v=v.parentNode){if(g=v.nextSibling){g.nodeName=="BR"&&(l=c={node:g.parentNode,offset:Zi(g)+1});break}let y=v.pmViewDesc;if(y&&y.node&&y.node.isBlock)break}}else{let v=p.childNodes[x-1];h=v&&(v.nodeName=="BR"||v.contentEditable=="false")}}if(gl&&d.focusNode&&d.focusNode!=c.node&&d.focusNode.nodeType==1){let p=d.focusNode.childNodes[d.focusOffset];p&&p.contentEditable=="false"&&(a=!0)}if(!(a||h&&xs)&&Qf(l.node,l.offset,d.anchorNode,d.anchorOffset)&&Qf(c.node,c.offset,d.focusNode,d.focusOffset))return;let f=!1;if((u.extend||e==n)&&!(h&&gl)){u.collapse(l.node,l.offset);try{e!=n&&u.extend(c.node,c.offset),f=!0}catch{}}if(!f){if(e>n){let x=l;l=c,c=x}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,a=0;a<this.children.length;a++){let s=this.children[a],o=r+s.size;if(r==o?e<=o&&n>=r:e<o&&n>r){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?lf:O9,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Hc:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?lf:Hc}r=o}this.dirty=lf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?lf:O9;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class Cre extends q0{constructor(e,n,r,a){let s,o=n.type.toDOM;if(typeof o=="function"&&(o=o(r,()=>{if(!s)return a;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==bl&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Oqe extends q0{constructor(e,n,r,a){super(e,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Zf extends q0{constructor(e,n,r,a,s){super(e,[],r,a),this.mark=n,this.spec=s}static create(e,n,r,a){let s=a.nodeViews[n.type.name],o=s&&s(n,a,r);return(!o||!o.dom)&&(o=sp.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Zf(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Hc||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Hc&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=bl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=bl}}slice(e,n,r){let a=Zf.create(this.parent,this.mark,!0,r),s=this.children,o=this.size;n<o&&(s=ER(s,n,o,r)),e>0&&(s=ER(s,0,e,r));for(let l=0;l<s.length;l++)s[l].parent=a;return a.children=s,a}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class Hh extends q0{constructor(e,n,r,a,s,o,l,c,u){super(e,[],s,o),this.node=n,this.outerDeco=r,this.innerDeco=a,this.nodeDOM=l}static create(e,n,r,a,s,o){let l=s.nodeViews[n.type.name],c,u=l&&l(n,s,()=>{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,a),d=u&&u.dom,h=u&&u.contentDOM;if(n.isText){if(!d)d=document.createTextNode(n.text);else if(d.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else d||({dom:d,contentDOM:h}=sp.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&d.nodeName!="BR"&&(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let f=d;return d=Mre(d,r,n),u?c=new Iqe(e,n,r,a,d,h||null,f,u,s,o+1):n.isText?new mA(e,n,r,a,d,f,s):new Hh(e,n,r,a,d,h||null,f,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Mt.empty)}return e}matchesNode(e,n,r){return this.dirty==bl&&e.eq(this.node)&&KN(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,a=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new Uqe(this,o&&o.node,e);$qe(this.node,this.innerDeco,(u,d,h)=>{u.spec.marks?c.syncToMarks(u.spec.marks,r,e,d):u.type.side>=0&&!h&&c.syncToMarks(d==this.node.childCount?$r.none:this.node.child(d).marks,r,e,d),c.placeWidget(u,e,a)},(u,d,h,f)=>{c.syncToMarks(u.marks,r,e,f);let p;c.findNodeMatch(u,d,h,f)||l&&e.state.selection.from>a&&e.state.selection.to<a+u.nodeSize&&(p=c.findIndexWithChild(s.node))>-1&&c.updateNodeAt(u,d,h,p,e)||c.updateNextNode(u,d,h,e,f,a)||c.addNode(u,d,h,e,a),a+=u.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==lf)&&(o&&this.protectLocalComposition(e,o),Are(this.contentDOM,this.children,e),Db&&Vqe(this.dom))}localCompositionInfo(e,n){let{from:r,to:a}=e.state.selection;if(!(e.state.selection instanceof wn)||r<n||a>n+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=qqe(this.node.content,o,r-n,a-n);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:a}){if(this.getDesc(n))return;let s=n;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Oqe(this,s,n,a);e.input.compositionNodes.push(o),this.children=ER(this.children,r,r+a.length,e,o)}update(e,n,r,a){return this.dirty==Hc||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,a),!0)}updateInner(e,n,r,a){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=bl}updateOuterDeco(e){if(KN(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Tre(this.dom,this.nodeDOM,PR(this.outerDeco,this.node,n),PR(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function I9(t,e,n,r,a){Mre(r,e,t);let s=new Hh(void 0,t,e,n,r,r,r,a,0);return s.contentDOM&&s.updateChildren(a,0),s}class mA extends Hh{constructor(e,n,r,a,s,o,l){super(e,n,r,a,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,a){return this.dirty==Hc||this.dirty!=bl&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=bl||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,a.trackWrites==this.nodeDOM&&(a.trackWrites=null)),this.node=e,this.dirty=bl,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let a=this.node.cut(e,n),s=document.createTextNode(a.text);return new mA(this.parent,a,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Hc)}get domAtom(){return!1}isText(e){return this.node.text==e}}class kre extends q0{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==bl&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Iqe extends Hh{constructor(e,n,r,a,s,o,l,c,u,d){super(e,n,r,a,s,o,l,u,d),this.spec=c}update(e,n,r,a){if(this.dirty==Hc)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,a),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,a){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,a)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Are(t,e,n){let r=t.firstChild,a=!1;for(let s=0;s<e.length;s++){let o=e[s],l=o.dom;if(l.parentNode==t){for(;l!=r;)r=z9(r),a=!0;r=r.nextSibling}else a=!0,t.insertBefore(l,r);if(o instanceof Zf){let c=r?r.previousSibling:t.lastChild;Are(o.contentDOM,o.children,n),r=c?c.nextSibling:t.firstChild}}for(;r;)r=z9(r),a=!0;a&&n.trackWrites==t&&(n.trackWrites=null)}const ev=function(t){t&&(this.nodeName=t)};ev.prototype=Object.create(null);const cf=[new ev];function PR(t,e,n){if(t.length==0)return cf;let r=n?cf[0]:new ev,a=[r];for(let s=0;s<t.length;s++){let o=t[s].type.attrs;if(o){o.nodeName&&a.push(r=new ev(o.nodeName));for(let l in o){let c=o[l];c!=null&&(n&&a.length==1&&a.push(r=new ev(e.isInline?"span":"div")),l=="class"?r.class=(r.class?r.class+" ":"")+c:l=="style"?r.style=(r.style?r.style+";":"")+c:l!="nodeName"&&(r[l]=c))}}}return a}function Tre(t,e,n,r){if(n==cf&&r==cf)return e;let a=e;for(let s=0;s<r.length;s++){let o=r[s],l=n[s];if(s){let c;l&&l.nodeName==o.nodeName&&a!=t&&(c=a.parentNode)&&c.nodeName.toLowerCase()==o.nodeName||(c=document.createElement(o.nodeName),c.pmIsDeco=!0,c.appendChild(a),l=cf[0]),a=c}zqe(a,l||cf[0],o)}return a}function zqe(t,e,n){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in n)&&t.removeAttribute(r);for(let r in n)r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],a=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<r.length;s++)a.indexOf(r[s])==-1&&t.classList.remove(r[s]);for(let s=0;s<a.length;s++)r.indexOf(a[s])==-1&&t.classList.add(a[s]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,a;for(;a=r.exec(e.style);)t.style.removeProperty(a[1])}n.style&&(t.style.cssText+=n.style)}}function Mre(t,e,n){return Tre(t,t,cf,PR(e,n,t.nodeType!=1))}function KN(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function z9(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class Uqe{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=Bqe(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let r=e;r<n;r++)this.top.children[r].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,r,a){let s=0,o=this.stack.length>>1,l=Math.min(o,e.length);for(;s<l&&(s==o-1?this.top:this.stack[s+1<<1]).matchesMark(e[s])&&e[s].type.spec.spanning!==!1;)s++;for(;s<o;)this.destroyRest(),this.top.dirty=bl,this.index=this.stack.pop(),this.top=this.stack.pop(),o--;for(;o<e.length;){this.stack.push(this.top,this.index+1);let c=-1,u=this.top.children.length;a<this.preMatch.index&&(u=Math.min(this.index+3,u));for(let d=this.index;d<u;d++){let h=this.top.children[d];if(h.matchesMark(e[o])&&!this.isLocked(h.dom)){c=d;break}}if(c>-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let d=Zf.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,d),this.top=d,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,a){let s=-1,o;if(a>=this.preMatch.index&&(o=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&o.matchesNode(e,n,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,c=Math.min(this.top.children.length,l+5);l<c;l++){let u=this.top.children[l];if(u.matchesNode(e,n,r)&&!this.preMatch.matched.has(u)){s=l;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,r,a,s){let o=this.top.children[a];return o.dirty==Hc&&o.dom==o.contentDOM&&(o.dirty=lf),o.update(e,n,r,s)?(this.destroyBetween(this.index,a),this.index++,!0):!1}findIndexWithChild(e){for(;;){let n=e.parentNode;if(!n)return-1;if(n==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let a=this.index;a<this.top.children.length;a++)if(this.top.children[a]==r)return a}return-1}e=n}}updateNextNode(e,n,r,a,s,o){for(let l=this.index;l<this.top.children.length;l++){let c=this.top.children[l];if(c instanceof Hh){let u=this.preMatch.matched.get(c);if(u!=null&&u!=s)return!1;let d=c.dom,h,f=this.isLocked(d)&&!(e.isText&&c.node&&c.node.isText&&c.nodeDOM.nodeValue==e.text&&c.dirty!=Hc&&KN(n,c.outerDeco));if(!f&&c.update(e,n,r,a))return this.destroyBetween(this.index,l),c.dom!=d&&(this.changed=!0),this.index++,!0;if(!f&&(h=this.recreateWrapper(c,e,n,r,a,o)))return this.destroyBetween(this.index,l),this.top.children[this.index]=h,h.contentDOM&&(h.dirty=lf,h.updateChildren(a,o+1),h.dirty=bl),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,a,s,o){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!KN(r,e.outerDeco)||!a.eq(e.innerDeco))return null;let l=Hh.create(this.top,n,r,a,s,o);if(l.contentDOM){l.children=e.children,e.children=[];for(let c of l.children)c.parent=l}return e.destroy(),l}addNode(e,n,r,a,s){let o=Hh.create(this.top,e,n,r,a,s);o.contentDOM&&o.updateChildren(a,s+1),this.top.children.splice(this.index++,0,o),this.changed=!0}placeWidget(e,n,r){let a=this.index<this.top.children.length?this.top.children[this.index]:null;if(a&&a.matchesWidget(e)&&(e==a.widget||!a.widget.type.toDOM.parentNode))this.index++;else{let s=new Cre(this.top,e,n,r);this.top.children.splice(this.index++,0,s),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],n=this.top;for(;e instanceof Zf;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof mA)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((xs||es)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",n),this.addHackNode("BR",this.top))}addHackNode(e,n){if(n==this.top&&this.index<n.children.length&&n.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let a=new kre(this.top,[],r,null);n!=this.top?n.children.push(a):n.children.splice(this.index++,0,a),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function Bqe(t,e){let n=e,r=n.children.length,a=t.childCount,s=new Map,o=[];e:for(;a>0;){let l;for(;;)if(r){let u=n.children[r-1];if(u instanceof Zf)n=u,r=u.children.length;else{l=u,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=l.node;if(c){if(c!=t.child(a-1))break;--a,s.set(l,a),o.push(l)}}return{index:a,matched:s,matches:o.reverse()}}function Hqe(t,e){return t.type.side-e.type.side}function $qe(t,e,n,r){let a=e.locals(t),s=0;if(a.length==0){for(let u=0;u<t.childCount;u++){let d=t.child(u);r(d,a,e.forChild(s,d),u),s+=d.nodeSize}return}let o=0,l=[],c=null;for(let u=0;;){let d,h;for(;o<a.length&&a[o].to==s;){let g=a[o++];g.widget&&(d?(h||(h=[d])).push(g):d=g)}if(d)if(h){h.sort(Hqe);for(let g=0;g<h.length;g++)n(h[g],u,!!c)}else n(d,u,!!c);let f,p;if(c)p=-1,f=c,c=null;else if(u<t.childCount)p=u,f=t.child(u++);else break;for(let g=0;g<l.length;g++)l[g].to<=s&&l.splice(g--,1);for(;o<a.length&&a[o].from<=s&&a[o].to>s;)l.push(a[o++]);let x=s+f.nodeSize;if(f.isText){let g=x;o<a.length&&a[o].from<g&&(g=a[o].from);for(let y=0;y<l.length;y++)l[y].to<g&&(g=l[y].to);g<x&&(c=f.cut(g-s),f=f.cut(0,g-s),x=g,p=-1)}else for(;o<a.length&&a[o].to<x;)o++;let v=f.isInline&&!f.isLeaf?l.filter(g=>!g.inline):l.slice();r(f,v,e.forChild(s,f),p),s=x}}function Vqe(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function qqe(t,e,n,r){for(let a=0,s=0;a<t.childCount&&s<=r;){let o=t.child(a++),l=s;if(s+=o.nodeSize,!o.isText)continue;let c=o.text;for(;a<t.childCount;){let u=t.child(a++);if(s+=u.nodeSize,!u.isText)break;c+=u.text}if(s>=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let u=l<r?c.lastIndexOf(e,r-l-1):-1;if(u>=0&&u+e.length+l>=n)return l+u;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function ER(t,e,n,r,a){let s=[];for(let o=0,l=0;o<t.length;o++){let c=t[o],u=l,d=l+=c.size;u>=n||d<=e?s.push(c):(u<e&&s.push(c.slice(0,e-u,r)),a&&(s.push(a),a=void 0),d>n&&s.push(c.slice(n-u,c.size,r)))}return s}function T4(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let a=t.docView.nearestDesc(n.focusNode),s=a&&a.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,u;if(hA(n)){for(c=o;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&cn.isSelectable(h)&&a.parent&&!(h.isInline&&xqe(n.focusNode,n.focusOffset,a.dom))){let f=a.posBefore;u=new cn(o==f?l:r.resolve(f))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=o,f=o;for(let p=0;p<n.rangeCount;p++){let x=n.getRangeAt(p);h=Math.min(h,t.docView.posFromDOM(x.startContainer,x.startOffset,1)),f=Math.max(f,t.docView.posFromDOM(x.endContainer,x.endOffset,-1))}if(h<0)return null;[c,o]=f==t.state.selection.anchor?[f,h]:[h,f],l=r.resolve(o)}else c=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(c<0)return null}let d=r.resolve(c);if(!u){let h=e=="pointer"||t.state.selection.head<l.pos&&!s?1:-1;u=M4(t,d,l,h)}return u}function Pre(t){return t.editable?t.hasFocus():jre(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Qu(t,e=!1){let n=t.state.selection;if(Ere(t,n),!!Pre(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&es){let r=t.domSelectionRange(),a=t.domObserver.currentSelection;if(r.anchorNode&&a.anchorNode&&Qf(r.anchorNode,r.anchorOffset,a.anchorNode,a.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)Wqe(t);else{let{anchor:r,head:a}=n,s,o;U9&&!(n instanceof wn)&&(n.$from.parent.inlineContent||(s=B9(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(o=B9(t,n.to))),t.docView.setSelection(r,a,t,e),U9&&(s&&H9(s),o&&H9(o)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&Gqe(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const U9=xs||es&&bre<63;function B9(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),a=r<n.childNodes.length?n.childNodes[r]:null,s=r?n.childNodes[r-1]:null;if(xs&&a&&a.contentEditable=="false")return a2(a);if((!a||a.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(a)return a2(a);if(s)return a2(s)}}function a2(t){return t.contentEditable="true",xs&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function H9(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function Gqe(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,a=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=a)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Pre(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function Wqe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,Zi(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&ao&&Bh<=11&&(n.disabled=!0,n.disabled=!1)}function Ere(t,e){if(e instanceof cn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&($9(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else $9(t)}function $9(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function M4(t,e,n,r){return t.someProp("createSelectionBetween",a=>a(t,e,n))||wn.between(e,n,r)}function V9(t){return t.editable&&!t.hasFocus()?!1:jre(t)}function jre(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function Kqe(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Qf(e.node,e.offset,n.anchorNode,n.anchorOffset)}function jR(t,e){let{$anchor:n,$head:r}=t.selection,a=e>0?n.max(r):n.min(r),s=a.parent.inlineContent?a.depth?t.doc.resolve(e>0?a.after():a.before()):null:a;return s&&Bn.findFrom(s,e)}function ch(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function q9(t,e,n){let r=t.state.selection;if(r instanceof wn)if(n.indexOf("s")>-1){let{$head:a}=r,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(a.pos+s.nodeSize*(e<0?-1:1));return ch(t,new wn(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let a=jR(t.state,e);return a&&a instanceof cn?ch(t,a):!1}else if(!(al&&n.indexOf("m")>-1)){let a=r.$head,s=a.textOffset?null:e<0?a.nodeBefore:a.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?a.pos-s.nodeSize:a.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?cn.isSelectable(s)?ch(t,new cn(e<0?t.state.doc.resolve(a.pos-s.nodeSize):a)):V0?ch(t,new wn(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof cn&&r.node.isInline)return ch(t,new wn(e>0?r.$to:r.$from));{let a=jR(t.state,e);return a?ch(t,a):!1}}}function XN(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function tv(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Ag(t,e){return e<0?Xqe(t):Yqe(t)}function Xqe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a,s,o=!1;for(gl&&n.nodeType==1&&r<XN(n)&&tv(n.childNodes[r],-1)&&(o=!0);;)if(r>0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(tv(l,-1))a=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Dre(n))break;{let l=n.previousSibling;for(;l&&tv(l,-1);)a=n.parentNode,s=Zi(l),l=l.previousSibling;if(l)n=l,r=XN(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?DR(t,n,r):a&&DR(t,a,s)}function Yqe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let a=XN(n),s,o;for(;;)if(r<a){if(n.nodeType!=1)break;let l=n.childNodes[r];if(tv(l,1))s=n,o=++r;else break}else{if(Dre(n))break;{let l=n.nextSibling;for(;l&&tv(l,1);)s=l.parentNode,o=Zi(l)+1,l=l.nextSibling;if(l)n=l,r=0,a=XN(n);else{if(n=n.parentNode,n==t.dom)break;r=a=0}}}s&&DR(t,s,o)}function Dre(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function Qqe(t,e){for(;t&&e==t.childNodes.length&&!$0(t);)e=Zi(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let n=t.childNodes[e];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=0}}function Zqe(t,e){for(;t&&!e&&!$0(t);)e=Zi(t),t=t.parentNode;for(;t&&e;){let n=t.childNodes[e-1];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=t.childNodes.length}}function DR(t,e,n){if(e.nodeType!=3){let s,o;(o=Qqe(e,n))?(e=o,n=0):(s=Zqe(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(hA(r)){let s=document.createRange();s.setEnd(e,n),s.setStart(e,n),r.removeAllRanges(),r.addRange(s)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:a}=t;setTimeout(()=>{t.state==a&&Qu(t)},50)}function G9(t,e){let n=t.state.doc.resolve(e);if(!(es||xre)&&n.parent.inlineContent){let a=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>a.top&&o<a.bottom&&Math.abs(s.left-a.left)>1)return s.left<a.left?"ltr":"rtl"}if(e<n.end()){let s=t.coordsAtPos(e+1),o=(s.top+s.bottom)/2;if(o>a.top&&o<a.bottom&&Math.abs(s.left-a.left)>1)return s.left>a.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function W9(t,e,n){let r=t.state.selection;if(r instanceof wn&&!r.empty||n.indexOf("s")>-1||al&&n.indexOf("m")>-1)return!1;let{$from:a,$to:s}=r;if(!a.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=jR(t.state,e);if(o&&o instanceof cn)return ch(t,o)}if(!a.parent.inlineContent){let o=e<0?a:s,l=r instanceof Fo?Bn.near(o,e):Bn.findFrom(o,e);return l?ch(t,l):!1}return!1}function K9(t,e){if(!(t.state.selection instanceof wn))return!0;let{$head:n,$anchor:r,empty:a}=t.state.selection;if(!n.sameParent(r))return!0;if(!a)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let o=t.state.tr;return e<0?o.delete(n.pos-s.nodeSize,n.pos):o.delete(n.pos,n.pos+s.nodeSize),t.dispatch(o),!0}return!1}function X9(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function Jqe(t){if(!xs||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;X9(t,r,"true"),setTimeout(()=>X9(t,r,"false"),20)}return!1}function eGe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function tGe(t,e){let n=e.keyCode,r=eGe(e);if(n==8||al&&n==72&&r=="c")return K9(t,-1)||Ag(t,-1);if(n==46&&!e.shiftKey||al&&n==68&&r=="c")return K9(t,1)||Ag(t,1);if(n==13||n==27)return!0;if(n==37||al&&n==66&&r=="c"){let a=n==37?G9(t,t.state.selection.from)=="ltr"?-1:1:-1;return q9(t,a,r)||Ag(t,a)}else if(n==39||al&&n==70&&r=="c"){let a=n==39?G9(t,t.state.selection.from)=="ltr"?1:-1:1;return q9(t,a,r)||Ag(t,a)}else{if(n==38||al&&n==80&&r=="c")return W9(t,-1,r)||Ag(t,-1);if(n==40||al&&n==78&&r=="c")return Jqe(t)||W9(t,1,r)||Ag(t,1);if(r==(al?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function P4(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:a,openEnd:s}=e;for(;a>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,s--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let o=t.someProp("clipboardSerializer")||sp.fromSchema(t.state.schema),l=zre(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let u=c.firstChild,d,h=0;for(;u&&u.nodeType==1&&(d=Ire[u.nodeName.toLowerCase()]);){for(let p=d.length-1;p>=0;p--){let x=l.createElement(d[p]);for(;c.firstChild;)x.appendChild(c.firstChild);c.appendChild(x),h++}u=c.firstChild}u&&u.nodeType==1&&u.setAttribute("data-pm-slice",`${a} ${s}${h?` -${h}`:""} ${JSON.stringify(n)}`);let f=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,`
  8166. `);return{dom:c,text:f,slice:e}}function Rre(t,e,n,r,a){let s=a.parent.type.spec.code,o,l;if(!n&&!e)return null;let c=!!e&&(r||s||!n);if(c){if(t.someProp("transformPastedText",f=>{e=f(e,s||r,t)}),s)return l=new Wt(Mt.from(t.state.schema.text(e.replace(/\r\n?/g,`
  8167. `))),0,0),t.someProp("transformPasted",f=>{l=f(l,t,!0)}),l;let h=t.someProp("clipboardTextParser",f=>f(e,a,r,t));if(h)l=h;else{let f=a.marks(),{schema:p}=t.state,x=sp.fromSchema(p);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let g=o.appendChild(document.createElement("p"));v&&g.appendChild(x.serializeNode(p.text(v,f)))})}}else t.someProp("transformPastedHTML",h=>{n=h(n,t)}),o=iGe(n),V0&&sGe(o);let u=o&&o.querySelector("[data-pm-slice]"),d=u&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(u.getAttribute("data-pm-slice")||"");if(d&&d[3])for(let h=+d[3];h>0;h--){let f=o.firstChild;for(;f&&f.nodeType!=1;)f=f.nextSibling;if(!f)break;o=f}if(l||(l=(t.someProp("clipboardParser")||t.someProp("domParser")||Zy.fromSchema(t.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||d),context:a,ruleFromNode(f){return f.nodeName=="BR"&&!f.nextSibling&&f.parentNode&&!nGe.test(f.parentNode.nodeName)?{ignore:!0}:null}})),d)l=oGe(Y9(l,+d[1],+d[2]),d[4]);else if(l=Wt.maxOpen(rGe(l.content,a),!0),l.openStart||l.openEnd){let h=0,f=0;for(let p=l.content.firstChild;h<l.openStart&&!p.type.spec.isolating;h++,p=p.firstChild);for(let p=l.content.lastChild;f<l.openEnd&&!p.type.spec.isolating;f++,p=p.lastChild);l=Y9(l,h,f)}return t.someProp("transformPasted",h=>{l=h(l,t,c)}),l}const nGe=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function rGe(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let a=e.node(n).contentMatchAt(e.index(n)),s,o=[];if(t.forEach(l=>{if(!o)return;let c=a.findWrapping(l.type),u;if(!c)return o=null;if(u=o.length&&s.length&&Lre(c,s,l,o[o.length-1],0))o[o.length-1]=u;else{o.length&&(o[o.length-1]=Ore(o[o.length-1],s.length));let d=Fre(l,c);o.push(d),a=a.matchType(d.type),s=c}}),o)return Mt.from(o)}return t}function Fre(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,Mt.from(t));return t}function Lre(t,e,n,r,a){if(a<t.length&&a<e.length&&t[a]==e[a]){let s=Lre(t,e,n,r.lastChild,a+1);if(s)return r.copy(r.content.replaceChild(r.childCount-1,s));if(r.contentMatchAt(r.childCount).matchType(a==t.length-1?n.type:t[a+1]))return r.copy(r.content.append(Mt.from(Fre(n,t,a+1))))}}function Ore(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Ore(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(Mt.empty,!0);return t.copy(n.append(r))}function RR(t,e,n,r,a,s){let o=e<0?t.firstChild:t.lastChild,l=o.content;return t.childCount>1&&(s=0),a<r-1&&(l=RR(l,e,n,r,a+1,s)),a>=n&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=a).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(Mt.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(l))}function Y9(t,e,n){return e<t.openStart&&(t=new Wt(RR(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new Wt(RR(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Ire={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let Q9=null;function zre(){return Q9||(Q9=document.implementation.createHTMLDocument("title"))}let i2=null;function aGe(t){let e=window.trustedTypes;return e?(i2||(i2=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),i2.createHTML(t)):t}function iGe(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=zre().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),a;if((a=r&&Ire[r[1].toLowerCase()])&&(t=a.map(s=>"<"+s+">").join("")+t+a.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=aGe(t),a)for(let s=0;s<a.length;s++)n=n.querySelector(a[s])||n;return n}function sGe(t){let e=t.querySelectorAll(es?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent==" "&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function oGe(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:a,openStart:s,openEnd:o}=t;for(let l=r.length-2;l>=0;l-=2){let c=n.nodes[r[l]];if(!c||c.hasRequiredAttrs())break;a=Mt.from(c.create(r[l+1],a)),s++,o++}return new Wt(a,s,o)}const Os={},Is={},lGe={touchstart:!0,touchmove:!0};class cGe{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function uGe(t){for(let e in Os){let n=Os[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{hGe(t,r)&&!E4(t,r)&&(t.editable||!(r.type in Is))&&n(t,r)},lGe[e]?{passive:!0}:void 0)}xs&&t.dom.addEventListener("input",()=>null),FR(t)}function kh(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function dGe(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function FR(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>E4(t,r))})}function E4(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function hGe(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function mGe(t,e){!E4(t,e)&&Os[e.type]&&(t.editable||!(e.type in Is))&&Os[e.type](t,e)}Is.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Bre(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Hu&&es&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Db&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",a=>a(t,Qm(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||tGe(t,n)?n.preventDefault():kh(t,"key")};Is.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Is.keypress=(t,e)=>{let n=e;if(Bre(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||al&&n.metaKey)return;if(t.someProp("handleKeyPress",a=>a(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof wn)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!t.someProp("handleTextInput",o=>o(t,r.$from.pos,r.$to.pos,a,s))&&t.dispatch(s()),n.preventDefault()}};function fA(t){return{left:t.clientX,top:t.clientY}}function fGe(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function j4(t,e,n,r,a){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(t.someProp(e,l=>o>s.depth?l(t,n,s.nodeAfter,s.before(o),a,!0):l(t,n,s.node(o),s.before(o),a,!1)))return!0;return!1}function ib(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function pGe(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&cn.isSelectable(r)?(ib(t,new cn(n)),!0):!1}function gGe(t,e){if(e==-1)return!1;let n=t.state.selection,r,a;n instanceof cn&&(r=n.node);let s=t.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(cn.isSelectable(l)){r&&n.$from.depth>0&&o>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?a=s.before(n.$from.depth):a=s.before(o);break}}return a!=null?(ib(t,cn.create(t.state.doc,a)),!0):!1}function bGe(t,e,n,r,a){return j4(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(a?gGe(t,n):pGe(t,n))}function xGe(t,e,n,r){return j4(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",a=>a(t,e,r))}function yGe(t,e,n,r){return j4(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",a=>a(t,e,r))||vGe(t,n,r)}function vGe(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(ib(t,wn.create(r,0,r.content.size)),!0):!1;let a=r.resolve(e);for(let s=a.depth+1;s>0;s--){let o=s>a.depth?a.nodeAfter:a.node(s),l=a.before(s);if(o.inlineContent)ib(t,wn.create(r,l+1,l+1+o.content.size));else if(cn.isSelectable(o))ib(t,cn.create(r,l));else continue;return!0}}function D4(t){return YN(t)}const Ure=al?"metaKey":"ctrlKey";Os.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=D4(t),a=Date.now(),s="singleClick";a-t.input.lastClick.time<500&&fGe(n,t.input.lastClick)&&!n[Ure]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:s,button:n.button};let o=t.posAtCoords(fA(n));o&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new wGe(t,o,n,!!r)):(s=="doubleClick"?xGe:yGe)(t,o.pos,o.inside,n)?n.preventDefault():kh(t,"pointer"))};class wGe{constructor(e,n,r,a){this.view=e,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[Ure],this.allowDefault=r.shiftKey;let s,o;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),o=n.inside;else{let d=e.state.doc.resolve(n.pos);s=d.parent,o=d.depth?d.before():0}const l=a?null:r.target,c=l?e.docView.nearestDesc(l,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:u}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||u instanceof cn&&u.from<=o&&u.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&gl&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),kh(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Qu(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(fA(e))),this.updateAllowDefault(e),this.allowDefault||!n?kh(this.view,"pointer"):bGe(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||xs&&this.mightDrag&&!this.mightDrag.node.isAtom||es&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(ib(this.view,Bn.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):kh(this.view,"pointer")}move(e){this.updateAllowDefault(e),kh(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}Os.touchstart=t=>{t.input.lastTouch=Date.now(),D4(t),kh(t,"pointer")};Os.touchmove=t=>{t.input.lastTouch=Date.now(),kh(t,"pointer")};Os.contextmenu=t=>D4(t);function Bre(t,e){return t.composing?!0:xs&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const SGe=Hu?5e3:-1;Is.compositionstart=Is.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof wn&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||es&&xre&&_Ge(t)))t.markCursor=t.state.storedMarks||n.marks(),YN(t,!0),t.markCursor=null;else if(YN(t,!e.selection.empty),gl&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let a=r.focusNode,s=r.focusOffset;a&&a.nodeType==1&&s!=0;){let o=s<0?a.lastChild:a.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=t.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else a=o,s=-1}}t.input.composing=!0}Hre(t,SGe)};function _Ge(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Is.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,Hre(t,20))};function Hre(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>YN(t),e))}function $re(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=CGe());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function NGe(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=gqe(e.focusNode,e.focusOffset),r=bqe(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!a||!a.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let o=n.pmViewDesc;if(!(!o||!o.isText(n.nodeValue)))return r}}return n||r}function CGe(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function YN(t,e=!1){if(!(Hu&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),$re(t),e||t.docView&&t.docView.dirty){let n=T4(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function kGe(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),a=document.createRange();a.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Yv=ao&&Bh<15||Db&&wqe<604;Os.copy=Is.cut=(t,e)=>{let n=e,r=t.state.selection,a=n.type=="cut";if(r.empty)return;let s=Yv?null:n.clipboardData,o=r.content(),{dom:l,text:c}=P4(t,o);s?(n.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",c)):kGe(t,l),a&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function AGe(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function TGe(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let a=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?Qv(t,r.value,null,a,e):Qv(t,r.textContent,r.innerHTML,a,e)},50)}function Qv(t,e,n,r,a){let s=Rre(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,a,s||Wt.empty)))return!0;if(!s)return!1;let o=AGe(s),l=o?t.state.tr.replaceSelectionWith(o,r):t.state.tr.replaceSelection(s);return t.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Vre(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Is.paste=(t,e)=>{let n=e;if(t.composing&&!Hu)return;let r=Yv?null:n.clipboardData,a=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Qv(t,Vre(r),r.getData("text/html"),a,n)?n.preventDefault():TGe(t,n)};class qre{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const MGe=al?"altKey":"ctrlKey";function Gre(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[MGe]}Os.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=t.state.selection,s=a.empty?null:t.posAtCoords(fA(n)),o;if(!(s&&s.pos>=a.from&&s.pos<=(a instanceof cn?a.to-1:a.to))){if(r&&r.mightDrag)o=cn.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=t.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=t.docView&&(o=cn.create(t.state.doc,h.posBefore))}}let l=(o||t.state.selection).content(),{dom:c,text:u,slice:d}=P4(t,l);(!n.dataTransfer.files.length||!es||bre>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Yv?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Yv||n.dataTransfer.setData("text/plain",u),t.dragging=new qre(d,Gre(t,n),o)};Os.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Is.dragover=Is.dragenter=(t,e)=>e.preventDefault();Is.drop=(t,e)=>{try{PGe(t,e,t.dragging)}finally{t.dragging=null}};function PGe(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(fA(e));if(!r)return;let a=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",p=>{s=p(s,t,!1)}):s=Rre(t,Vre(e.dataTransfer),Yv?null:e.dataTransfer.getData("text/html"),!1,a);let o=!!(n&&Gre(t,e));if(t.someProp("handleDrop",p=>p(t,e,s||Wt.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Yne(t.state.doc,a.pos,s):a.pos;l==null&&(l=a.pos);let c=t.state.tr;if(o){let{node:p}=n;p?p.replace(c):c.deleteSelection()}let u=c.mapping.map(l),d=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,h=c.doc;if(d?c.replaceRangeWith(u,u,s.content.firstChild):c.replaceRange(u,u,s),c.doc.eq(h))return;let f=c.doc.resolve(u);if(d&&cn.isSelectable(s.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(s.content.firstChild))c.setSelection(new cn(f));else{let p=c.mapping.map(l);c.mapping.maps[c.mapping.maps.length-1].forEach((x,v,g,y)=>p=y),c.setSelection(M4(t,f,c.doc.resolve(p)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Os.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Qu(t)},20))};Os.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Os.beforeinput=(t,e)=>{if(es&&Hu&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,Qm(8,"Backspace")))))return;let{$cursor:a}=t.state.selection;a&&a.pos>0&&t.dispatch(t.state.tr.delete(a.pos-1,a.pos).scrollIntoView())},50)}};for(let t in Is)Os[t]=Is[t];function Zv(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class QN{constructor(e,n){this.toDOM=e,this.spec=n||_f,this.side=this.spec.side||0}map(e,n,r,a){let{pos:s,deleted:o}=e.mapResult(n.from+a,this.side<0?-1:1);return o?null:new Es(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof QN&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Zv(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class $h{constructor(e,n){this.attrs=e,this.spec=n||_f}map(e,n,r,a){let s=e.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,o=e.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new Es(s,o,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof $h&&Zv(this.attrs,e.attrs)&&Zv(this.spec,e.spec)}static is(e){return e.type instanceof $h}destroy(){}}class R4{constructor(e,n){this.attrs=e,this.spec=n||_f}map(e,n,r,a){let s=e.mapResult(n.from+a,1);if(s.deleted)return null;let o=e.mapResult(n.to+a,-1);return o.deleted||o.pos<=s.pos?null:new Es(s.pos-r,o.pos-r,this)}valid(e,n){let{index:r,offset:a}=e.content.findIndex(n.from),s;return a==n.from&&!(s=e.child(r)).isText&&a+s.nodeSize==n.to}eq(e){return this==e||e instanceof R4&&Zv(this.attrs,e.attrs)&&Zv(this.spec,e.spec)}destroy(){}}class Es{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new Es(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new Es(e,e,new QN(n,r))}static inline(e,n,r,a){return new Es(e,n,new $h(r,a))}static node(e,n,r,a){return new Es(e,n,new R4(r,a))}get spec(){return this.type.spec}get inline(){return this.type instanceof $h}get widget(){return this.type instanceof QN}}const Fg=[],_f={};class pa{constructor(e,n){this.local=e.length?e:Fg,this.children=n.length?n:Fg}static create(e,n){return n.length?ZN(n,e,0,_f):hs}find(e,n,r){let a=[];return this.findInner(e??0,n??1e9,a,0,r),a}findInner(e,n,r,a,s){for(let o=0;o<this.local.length;o++){let l=this.local[o];l.from<=n&&l.to>=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+a,l.to+a))}for(let o=0;o<this.children.length;o+=3)if(this.children[o]<n&&this.children[o+1]>e){let l=this.children[o]+1;this.children[o+2].findInner(e-l,n-l,r,a+l,s)}}map(e,n,r){return this==hs||e.maps.length==0?this:this.mapInner(e,n,0,0,r||_f)}mapInner(e,n,r,a,s){let o;for(let l=0;l<this.local.length;l++){let c=this.local[l].map(e,r,a);c&&c.type.valid(n,c)?(o||(o=[])).push(c):s.onRemove&&s.onRemove(this.local[l].spec)}return this.children.length?EGe(this.children,o||[],e,n,r,a,s):o?new pa(o.sort(Nf),Fg):hs}add(e,n){return n.length?this==hs?pa.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let a,s=0;e.forEach((l,c)=>{let u=c+r,d;if(d=Kre(n,l,u)){for(a||(a=this.children.slice());s<a.length&&a[s]<c;)s+=3;a[s]==c?a[s+2]=a[s+2].addInner(l,d,u+1):a.splice(s,0,c,c+l.nodeSize,ZN(d,l,u+1,_f)),s+=3}});let o=Wre(s?Xre(n):n,-r);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||o.splice(l--,1);return new pa(o.length?this.local.concat(o).sort(Nf):this.local,a||this.children)}remove(e){return e.length==0||this==hs?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,a=this.local;for(let s=0;s<r.length;s+=3){let o,l=r[s]+n,c=r[s+1]+n;for(let d=0,h;d<e.length;d++)(h=e[d])&&h.from>l&&h.to<c&&(e[d]=null,(o||(o=[])).push(h));if(!o)continue;r==this.children&&(r=this.children.slice());let u=r[s+2].removeInner(o,l+1);u!=hs?r[s+2]=u:(r.splice(s,3),s-=3)}if(a.length){for(let s=0,o;s<e.length;s++)if(o=e[s])for(let l=0;l<a.length;l++)a[l].eq(o,n)&&(a==this.local&&(a=this.local.slice()),a.splice(l--,1))}return r==this.children&&a==this.local?this:a.length||r.length?new pa(a,r):hs}forChild(e,n){if(this==hs)return this;if(n.isLeaf)return pa.empty;let r,a;for(let l=0;l<this.children.length;l+=3)if(this.children[l]>=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+n.content.size;for(let l=0;l<this.local.length;l++){let c=this.local[l];if(c.from<o&&c.to>s&&c.type instanceof $h){let u=Math.max(s,c.from)-s,d=Math.min(o,c.to)-s;u<d&&(a||(a=[])).push(c.copy(u,d))}}if(a){let l=new pa(a.sort(Nf),Fg);return r?new gh([l,r]):l}return r||hs}eq(e){if(this==e)return!0;if(!(e instanceof pa)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return F4(this.localsInner(e))}localsInner(e){if(this==hs)return Fg;if(e.inlineContent||!this.local.some($h.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof $h||n.push(this.local[r]);return n}forEachSet(e){e(this)}}pa.empty=new pa([],[]);pa.removeOverlap=F4;const hs=pa.empty;class gh{constructor(e){this.members=e}map(e,n){const r=this.members.map(a=>a.map(e,n,_f));return gh.from(r)}forChild(e,n){if(n.isLeaf)return pa.empty;let r=[];for(let a=0;a<this.members.length;a++){let s=this.members[a].forChild(e,n);s!=hs&&(s instanceof gh?r=r.concat(s.members):r.push(s))}return gh.from(r)}eq(e){if(!(e instanceof gh)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let a=0;a<this.members.length;a++){let s=this.members[a].localsInner(e);if(s.length)if(!n)n=s;else{r&&(n=n.slice(),r=!1);for(let o=0;o<s.length;o++)n.push(s[o])}}return n?F4(r?n:n.sort(Nf)):Fg}static from(e){switch(e.length){case 0:return hs;case 1:return e[0];default:return new gh(e.every(n=>n instanceof pa)?e:e.reduce((n,r)=>n.concat(r instanceof pa?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function EGe(t,e,n,r,a,s,o){let l=t.slice();for(let u=0,d=s;u<n.maps.length;u++){let h=0;n.maps[u].forEach((f,p,x,v)=>{let g=v-x-(p-f);for(let y=0;y<l.length;y+=3){let _=l[y+1];if(_<0||f>_+d-h)continue;let N=l[y]+d-h;p>=N?l[y+1]=f<=N?-2:-1:f>=d&&g&&(l[y]+=g,l[y+1]+=g)}h+=g}),d=n.maps[u].map(d,-1)}let c=!1;for(let u=0;u<l.length;u+=3)if(l[u+1]<0){if(l[u+1]==-2){c=!0,l[u+1]=-1;continue}let d=n.map(t[u]+s),h=d-a;if(h<0||h>=r.content.size){c=!0;continue}let f=n.map(t[u+1]+s,-1),p=f-a,{index:x,offset:v}=r.content.findIndex(h),g=r.maybeChild(x);if(g&&v==h&&v+g.nodeSize==p){let y=l[u+2].mapInner(n,g,d+1,t[u]+s+1,o);y!=hs?(l[u]=h,l[u+1]=p,l[u+2]=y):(l[u+1]=-2,c=!0)}else c=!0}if(c){let u=jGe(l,t,e,n,a,s,o),d=ZN(u,r,0,o);e=d.local;for(let h=0;h<l.length;h+=3)l[h+1]<0&&(l.splice(h,3),h-=3);for(let h=0,f=0;h<d.children.length;h+=3){let p=d.children[h];for(;f<l.length&&l[f]<p;)f+=3;l.splice(f,0,d.children[h],d.children[h+1],d.children[h+2])}}return new pa(e.sort(Nf),l)}function Wre(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let a=t[r];n.push(new Es(a.from+e,a.to+e,a.type))}return n}function jGe(t,e,n,r,a,s,o){function l(c,u){for(let d=0;d<c.local.length;d++){let h=c.local[d].map(r,a,u);h?n.push(h):o.onRemove&&o.onRemove(c.local[d].spec)}for(let d=0;d<c.children.length;d+=3)l(c.children[d+2],c.children[d]+u+1)}for(let c=0;c<t.length;c+=3)t[c+1]==-1&&l(t[c+2],e[c]+s+1);return n}function Kre(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,a=null;for(let s=0,o;s<t.length;s++)(o=t[s])&&o.from>n&&o.to<r&&((a||(a=[])).push(o),t[s]=null);return a}function Xre(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function ZN(t,e,n,r){let a=[],s=!1;e.forEach((l,c)=>{let u=Kre(t,l,c+n);if(u){s=!0;let d=ZN(u,l,n+c+1,r);d!=hs&&a.push(c,c+l.nodeSize,d)}});let o=Wre(s?Xre(t):t,-n).sort(Nf);for(let l=0;l<o.length;l++)o[l].type.valid(e,o[l])||(r.onRemove&&r.onRemove(o[l].spec),o.splice(l--,1));return o.length||a.length?new pa(o,a):hs}function Nf(t,e){return t.from-e.from||t.to-e.to}function F4(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let a=n+1;a<e.length;a++){let s=e[a];if(s.from==r.from){s.to!=r.to&&(e==t&&(e=t.slice()),e[a]=s.copy(s.from,r.to),Z9(e,a+1,s.copy(r.to,s.to)));continue}else{s.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,s.from),Z9(e,a,r.copy(s.from,r.to)));break}}}return e}function Z9(t,e,n){for(;e<t.length&&Nf(n,t[e])>0;)e++;t.splice(e,0,n)}function s2(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=hs&&e.push(r)}),t.cursorWrapper&&e.push(pa.create(t.state.doc,[t.cursorWrapper.deco])),gh.from(e)}const DGe={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},RGe=ao&&Bh<=11;class FGe{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class LGe{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new FGe,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;a<r.length;a++)this.queue.push(r[a]);ao&&Bh<=11&&r.some(a=>a.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():xs&&e.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),RGe&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,DGe)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(V9(this.view)){if(this.suppressingSelectionUpdates)return Qu(this.view);if(ao&&Bh<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Qf(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,r;for(let s=e.focusNode;s;s=jb(s))n.add(s);for(let s=e.anchorNode;s;s=jb(s))if(n.has(s)){r=s;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&V9(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,c=[];if(e.editable)for(let d=0;d<n.length;d++){let h=this.registerMutation(n[d],c);h&&(s=s<0?h.from:Math.min(h.from,s),o=o<0?h.to:Math.max(h.to,o),h.typeOver&&(l=!0))}if(c.some(d=>d.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let d of c)if(d.nodeName=="BR"&&d.parentNode){let h=d.nextSibling;h&&h.nodeType==1&&h.contentEditable=="false"&&d.parentNode.removeChild(d)}}else if(gl&&c.length){let d=c.filter(h=>h.nodeName=="BR");if(d.length==2){let[h,f]=d;h.parentNode&&h.parentNode.parentNode==f.parentNode?f.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let f of d){let p=f.parentNode;p&&p.nodeName=="LI"&&(!h||zGe(e,h)!=p)&&f.remove()}}}let u=null;s<0&&a&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&hA(r)&&(u=T4(e))&&u.eq(Bn.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Qu(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||a)&&(s>-1&&(e.docView.markDirty(s,o),OGe(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,UGe(e,c)),this.handleDOMChange(s,o,l,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Qu(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let d=0;d<e.addedNodes.length;d++){let h=e.addedNodes[d];n.push(h),h.nodeType==3&&(this.lastChangedTextNode=h)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let a=e.previousSibling,s=e.nextSibling;if(ao&&Bh<=11&&e.addedNodes.length)for(let d=0;d<e.addedNodes.length;d++){let{previousSibling:h,nextSibling:f}=e.addedNodes[d];(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(a=h),(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(s=f)}let o=a&&a.parentNode==e.target?Zi(a)+1:0,l=r.localPosFromDOM(e.target,o,-1),c=s&&s.parentNode==e.target?Zi(s):e.target.childNodes.length,u=r.localPosFromDOM(e.target,c,1);return{from:l,to:u}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let J9=new WeakMap,eW=!1;function OGe(t){if(!J9.has(t)&&(J9.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=gl,eW)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),eW=!0}}function tW(t,e){let n=e.startContainer,r=e.startOffset,a=e.endContainer,s=e.endOffset,o=t.domAtPos(t.state.selection.anchor);return Qf(o.node,o.offset,a,s)&&([n,r,a,s]=[a,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:a,focusOffset:s}}function IGe(t,e){if(e.getComposedRanges){let a=e.getComposedRanges(t.root)[0];if(a)return tW(t,a)}let n;function r(a){a.preventDefault(),a.stopImmediatePropagation(),n=a.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?tW(t,n):null}function zGe(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function UGe(t,e){var n;let{focusNode:r,focusOffset:a}=t.domSelectionRange();for(let s of e)if(((n=s.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let o=s.nextSibling;for(;o&&o.nodeName!="TD"&&o.nodeName!="TH";)o=o.nextSibling;if(o){let l=o;for(;;){let c=l.firstChild;if(!c||c.nodeType!=1||c.contentEditable=="false"||/^(BR|IMG)$/.test(c.nodeName))break;l=c}l.insertBefore(s,l.firstChild),r==s&&t.domSelection().collapse(s,a)}else s.parentNode.removeChild(s)}}function BGe(t,e,n){let{node:r,fromOffset:a,toOffset:s,from:o,to:l}=t.docView.parseRange(e,n),c=t.domSelectionRange(),u,d=c.anchorNode;if(d&&t.dom.contains(d.nodeType==1?d:d.parentNode)&&(u=[{node:d,offset:c.anchorOffset}],hA(c)||u.push({node:c.focusNode,offset:c.focusOffset})),es&&t.input.lastKeyCode===8)for(let g=s;g>a;g--){let y=r.childNodes[g-1],_=y.pmViewDesc;if(y.nodeName=="BR"&&!_){s=g;break}if(!_||_.size)break}let h=t.state.doc,f=t.someProp("domParser")||Zy.fromSchema(t.state.schema),p=h.resolve(o),x=null,v=f.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:a,to:s,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:HGe,context:p});if(u&&u[0].pos!=null){let g=u[0].pos,y=u[1]&&u[1].pos;y==null&&(y=g),x={anchor:g+o,head:y+o}}return{doc:v,sel:x,from:o,to:l}}function HGe(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(xs&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||xs&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const $Ge=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function VGe(t,e,n,r,a){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let C=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,j=T4(t,C);if(j&&!t.state.selection.eq(j)){if(es&&Hu&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",E=>E(t,Qm(13,"Enter"))))return;let P=t.state.tr.setSelection(j);C=="pointer"?P.setMeta("pointer",!0):C=="key"&&P.scrollIntoView(),s&&P.setMeta("composition",s),t.dispatch(P)}return}let o=t.state.doc.resolve(e),l=o.sharedDepth(n);e=o.before(l+1),n=t.state.doc.resolve(n).after(l+1);let c=t.state.selection,u=BGe(t,e,n),d=t.state.doc,h=d.slice(u.from,u.to),f,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(f=t.state.selection.to,p="end"):(f=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let x=WGe(h.content,u.doc.content,u.from,f,p);if(x&&t.input.domChangeCount++,(Db&&t.input.lastIOSEnter>Date.now()-225||Hu)&&a.some(C=>C.nodeType==1&&!$Ge.test(C.nodeName))&&(!x||x.endA>=x.endB)&&t.someProp("handleKeyDown",C=>C(t,Qm(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!x)if(r&&c instanceof wn&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(u.sel&&u.sel.anchor!=u.sel.head))x={start:c.from,endA:c.to,endB:c.to};else{if(u.sel){let C=nW(t,t.state.doc,u.sel);if(C&&!C.eq(t.state.selection)){let j=t.state.tr.setSelection(C);s&&j.setMeta("composition",s),t.dispatch(j)}}return}t.state.selection.from<t.state.selection.to&&x.start==x.endB&&t.state.selection instanceof wn&&(x.start>t.state.selection.from&&x.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?x.start=t.state.selection.from:x.endA<t.state.selection.to&&x.endA>=t.state.selection.to-2&&t.state.selection.to<=u.to&&(x.endB+=t.state.selection.to-x.endA,x.endA=t.state.selection.to)),ao&&Bh<=11&&x.endB==x.start+1&&x.endA==x.start&&x.start>u.from&&u.doc.textBetween(x.start-u.from-1,x.start-u.from+1)=="  "&&(x.start--,x.endA--,x.endB--);let v=u.doc.resolveNoCache(x.start-u.from),g=u.doc.resolveNoCache(x.endB-u.from),y=d.resolve(x.start),_=v.sameParent(g)&&v.parent.inlineContent&&y.end()>=x.endA;if((Db&&t.input.lastIOSEnter>Date.now()-225&&(!_||a.some(C=>C.nodeName=="DIV"||C.nodeName=="P"))||!_&&v.pos<u.doc.content.size&&(!v.sameParent(g)||!v.parent.inlineContent)&&v.pos<g.pos&&!/\S/.test(u.doc.textBetween(v.pos,g.pos,"","")))&&t.someProp("handleKeyDown",C=>C(t,Qm(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>x.start&&GGe(d,x.start,x.endA,v,g)&&t.someProp("handleKeyDown",C=>C(t,Qm(8,"Backspace")))){Hu&&es&&t.domObserver.suppressSelectionUpdates();return}es&&x.endB==x.start&&(t.input.lastChromeDelete=Date.now()),Hu&&!_&&v.start()!=g.start()&&g.parentOffset==0&&v.depth==g.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==x.endA&&(x.endB-=2,g=u.doc.resolveNoCache(x.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(C){return C(t,Qm(13,"Enter"))})},20));let N=x.start,k=x.endA,A=C=>{let j=C||t.state.tr.replace(N,k,u.doc.slice(x.start-u.from,x.endB-u.from));if(u.sel){let P=nW(t,j.doc,u.sel);P&&!(es&&t.composing&&P.empty&&(x.start!=x.endB||t.input.lastChromeDelete<Date.now()-100)&&(P.head==N||P.head==j.mapping.map(k)-1)||ao&&P.empty&&P.head==N)&&j.setSelection(P)}return s&&j.setMeta("composition",s),j.scrollIntoView()},M;if(_)if(v.pos==g.pos){ao&&Bh<=11&&v.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Qu(t),20));let C=A(t.state.tr.delete(N,k)),j=d.resolve(x.start).marksAcross(d.resolve(x.endA));j&&C.ensureMarks(j),t.dispatch(C)}else if(x.endA==x.endB&&(M=qGe(v.parent.content.cut(v.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,x.endA-y.start())))){let C=A(t.state.tr);M.type=="add"?C.addMark(N,k,M.mark):C.removeMark(N,k,M.mark),t.dispatch(C)}else if(v.parent.child(v.index()).isText&&v.index()==g.index()-(g.textOffset?0:1)){let C=v.parent.textBetween(v.parentOffset,g.parentOffset),j=()=>A(t.state.tr.insertText(C,N,k));t.someProp("handleTextInput",P=>P(t,N,k,C,j))||t.dispatch(j())}else t.dispatch(A());else t.dispatch(A())}function nW(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:M4(t,e.resolve(n.anchor),e.resolve(n.head))}function qGe(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,a=n,s=r,o,l,c;for(let d=0;d<r.length;d++)a=r[d].removeFromSet(a);for(let d=0;d<n.length;d++)s=n[d].removeFromSet(s);if(a.length==1&&s.length==0)l=a[0],o="add",c=d=>d.mark(l.addToSet(d.marks));else if(a.length==0&&s.length==1)l=s[0],o="remove",c=d=>d.mark(l.removeFromSet(d.marks));else return null;let u=[];for(let d=0;d<e.childCount;d++)u.push(c(e.child(d)));if(Mt.from(u).eq(t))return{mark:l,type:o}}function GGe(t,e,n,r,a){if(n-e<=a.pos-r.pos||o2(r,!0,!1)<a.pos)return!1;let s=t.resolve(e);if(!r.parent.isTextblock){let l=s.nodeAfter;return l!=null&&n==e+l.nodeSize}if(s.parentOffset<s.parent.content.size||!s.parent.isTextblock)return!1;let o=t.resolve(o2(s,!0,!0));return!o.parent.isTextblock||o.pos>n||o2(o,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(o.parent.content)}function o2(t,e,n){let r=t.depth,a=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,a++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,a++}return a}function WGe(t,e,n,r,a){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:o,b:l}=t.findDiffEnd(e,n+t.size,n+e.size);if(a=="end"){let c=Math.max(0,s-Math.min(o,l));r-=o+c-s}if(o<s&&t.size<e.size){let c=r<=s&&r>=o?s-r:0;s-=c,s&&s<e.size&&rW(e.textBetween(s-1,s+1))&&(s+=c?1:-1),l=s+(l-o),o=s}else if(l<s){let c=r<=s&&r>=l?s-r:0;s-=c,s&&s<t.size&&rW(t.textBetween(s-1,s+1))&&(s+=c?1:-1),o=s+(o-l),l=s}return{start:s,endA:o,endB:l}}function rW(t){if(t.length!=2)return!1;let e=t.charCodeAt(0),n=t.charCodeAt(1);return e>=56320&&e<=57343&&n>=55296&&n<=56319}class Yre{constructor(e,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new cGe,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(lW),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=sW(this),iW(this),this.nodeViews=oW(this),this.docView=I9(this.state.doc,aW(this),s2(this),this.dom,this),this.domObserver=new LGe(this,(r,a,s,o)=>VGe(this,r,a,s,o)),this.domObserver.start(),uGe(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&FR(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(lW),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let a=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&($re(this),o=!0),this.state=e;let l=a.plugins!=e.plugins||this._props.plugins!=n.plugins;if(l||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=oW(this);XGe(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(l||n.handleDOMEvents!=this._props.handleDOMEvents)&&FR(this),this.editable=sW(this),iW(this);let c=s2(this),u=aW(this),d=a.plugins!=e.plugins&&!a.doc.eq(e.doc)?"reset":e.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=s||!this.docView.matchesNode(e.doc,u,c);(h||!e.selection.eq(a.selection))&&(o=!0);let f=d=="preserve"&&o&&this.dom.style.overflowAnchor==null&&Nqe(this);if(o){this.domObserver.stop();let p=h&&(ao||es)&&!this.composing&&!a.selection.empty&&!e.selection.empty&&KGe(a.selection,e.selection);if(h){let x=es?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=NGe(this)),(s||!this.docView.update(e.doc,u,c,this))&&(this.docView.updateOuterDeco(u),this.docView.destroy(),this.docView=I9(e.doc,u,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&Kqe(this))?Qu(this,p):(Ere(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,a),d=="reset"?this.dom.scrollTop=0:d=="to selection"?this.scrollToSelection():f&&Cqe(f)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof cn){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&j9(this,n.getBoundingClientRect(),e)}else j9(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,a=-1;if(this.state.doc.nodeAt(r.from)==r.node)a=r.from;else{let s=r.from+(this.state.doc.content.size-n.doc.content.size);(s>0&&this.state.doc.nodeAt(s))==r.node&&(a=s)}this.dragging=new qre(e.slice,e.move,a<0?void 0:cn.create(this.state.doc,a))}someProp(e,n){let r=this._props&&this._props[e],a;if(r!=null&&(a=n?n(r):r))return a;for(let o=0;o<this.directPlugins.length;o++){let l=this.directPlugins[o].props[e];if(l!=null&&(a=n?n(l):l))return a}let s=this.state.plugins;if(s)for(let o=0;o<s.length;o++){let l=s[o].props[e];if(l!=null&&(a=n?n(l):l))return a}}hasFocus(){if(ao){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&kqe(this.dom),Qu(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Eqe(this,e)}coordsAtPos(e,n=1){return _re(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let a=this.docView.posFromDOM(e,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(e,n){return Lqe(this,n||this.state,e)}pasteHTML(e,n){return Qv(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Qv(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return P4(this,e)}destroy(){this.docView&&(dGe(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],s2(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,fqe())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return mGe(this,e)}domSelectionRange(){let e=this.domSelection();return e?xs&&this.root.nodeType===11&&yqe(this.dom.ownerDocument)==this.dom&&IGe(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Yre.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function aW(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[Es.node(0,t.state.doc.content.size,e)]}function iW(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:Es.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function sW(t){return!t.someProp("editable",e=>e(t.state)===!1)}function KGe(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function oW(t){let e=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(e,a)||(e[a]=r[a])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function XGe(t,e){let n=0,r=0;for(let a in t){if(t[a]!=e[a])return!0;n++}for(let a in e)r++;return n!=r}function lW(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Zh={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},JN={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},YGe=typeof navigator<"u"&&/Mac/.test(navigator.platform),QGe=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Ji=0;Ji<10;Ji++)Zh[48+Ji]=Zh[96+Ji]=String(Ji);for(var Ji=1;Ji<=24;Ji++)Zh[Ji+111]="F"+Ji;for(var Ji=65;Ji<=90;Ji++)Zh[Ji]=String.fromCharCode(Ji+32),JN[Ji]=String.fromCharCode(Ji);for(var l2 in Zh)JN.hasOwnProperty(l2)||(JN[l2]=Zh[l2]);function ZGe(t){var e=YGe&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||QGe&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?JN:Zh)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const JGe=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),e7e=typeof navigator<"u"&&/Win/.test(navigator.platform);function t7e(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,a,s,o;for(let l=0;l<e.length-1;l++){let c=e[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))JGe?o=!0:a=!0;else throw new Error("Unrecognized modifier name: "+c)}return r&&(n="Alt-"+n),a&&(n="Ctrl-"+n),o&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function n7e(t){let e=Object.create(null);for(let n in t)e[t7e(n)]=t[n];return e}function c2(t,e,n=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n&&e.shiftKey&&(t="Shift-"+t),t}function r7e(t){return new ya({props:{handleKeyDown:Qre(t)}})}function Qre(t){let e=n7e(t);return function(n,r){let a=ZGe(r),s,o=e[c2(a,r)];if(o&&o(n.state,n.dispatch,n))return!0;if(a.length==1&&a!=" "){if(r.shiftKey){let l=e[c2(a,r,!1)];if(l&&l(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(e7e&&r.ctrlKey&&r.altKey)&&(s=Zh[r.keyCode])&&s!=a){let l=e[c2(s,r)];if(l&&l(n.state,n.dispatch,n))return!0}}return!1}}var a7e=Object.defineProperty,L4=(t,e)=>{for(var n in e)a7e(t,n,{get:e[n],enumerable:!0})};function pA(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:a}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,s=n.storedMarks,n}}}var gA=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:a}=n,s=this.buildProps(a);return Object.fromEntries(Object.entries(t).map(([o,l])=>[o,(...u)=>{const d=l(...u)(s);return!a.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(a),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o=[],l=!!t,c=t||a.tr,u=()=>(!l&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(c),o.every(h=>h===!0)),d={...Object.fromEntries(Object.entries(n).map(([h,f])=>[h,(...x)=>{const v=this.buildProps(c,e),g=f(...x)(v);return o.push(g),d}])),run:u};return d}createCan(t){const{rawCommands:e,state:n}=this,r=!1,a=t||n.tr,s=this.buildProps(a,r);return{...Object.fromEntries(Object.entries(e).map(([l,c])=>[l,(...u)=>c(...u)({...s,dispatch:void 0})])),chain:()=>this.createChain(a,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:a}=this,{view:s}=r,o={tr:t,editor:r,view:s,state:pA({state:a,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(...u)=>c(...u)(o)]))}};return o}},Zre={};L4(Zre,{blur:()=>i7e,clearContent:()=>s7e,clearNodes:()=>o7e,command:()=>l7e,createParagraphNear:()=>c7e,cut:()=>u7e,deleteCurrentNode:()=>d7e,deleteNode:()=>h7e,deleteRange:()=>m7e,deleteSelection:()=>f7e,enter:()=>p7e,exitCode:()=>g7e,extendMarkRange:()=>b7e,first:()=>x7e,focus:()=>v7e,forEach:()=>w7e,insertContent:()=>S7e,insertContentAt:()=>C7e,joinBackward:()=>T7e,joinDown:()=>A7e,joinForward:()=>M7e,joinItemBackward:()=>P7e,joinItemForward:()=>E7e,joinTextblockBackward:()=>j7e,joinTextblockForward:()=>D7e,joinUp:()=>k7e,keyboardShortcut:()=>F7e,lift:()=>L7e,liftEmptyBlock:()=>O7e,liftListItem:()=>I7e,newlineInCode:()=>z7e,resetAttributes:()=>U7e,scrollIntoView:()=>B7e,selectAll:()=>H7e,selectNodeBackward:()=>$7e,selectNodeForward:()=>V7e,selectParentNode:()=>q7e,selectTextblockEnd:()=>G7e,selectTextblockStart:()=>W7e,setContent:()=>K7e,setMark:()=>f9e,setMeta:()=>p9e,setNode:()=>g9e,setNodeSelection:()=>b9e,setTextDirection:()=>x9e,setTextSelection:()=>y9e,sinkListItem:()=>v9e,splitBlock:()=>w9e,splitListItem:()=>S9e,toggleList:()=>_9e,toggleMark:()=>N9e,toggleNode:()=>C9e,toggleWrap:()=>k9e,undoInputRule:()=>A9e,unsetAllMarks:()=>T9e,unsetMark:()=>M9e,unsetTextDirection:()=>P9e,updateAttributes:()=>E9e,wrapIn:()=>j9e,wrapInList:()=>D9e});var i7e=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window?.getSelection())==null||n.removeAllRanges())}),!0),s7e=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),o7e=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:a}=r;return n&&a.forEach(({$from:s,$to:o})=>{t.doc.nodesBetween(s.pos,o.pos,(l,c)=>{if(l.type.isText)return;const{doc:u,mapping:d}=e,h=u.resolve(d.map(c)),f=u.resolve(d.map(c+l.nodeSize)),p=h.blockRange(f);if(!p)return;const x=lx(p);if(l.type.isTextblock){const{defaultType:v}=h.parent.contentMatchAt(h.index());e.setNodeMarkup(p.start,v)}(x||x===0)&&e.lift(p,x)})}),!0},l7e=t=>e=>t(e),c7e=()=>({state:t,dispatch:e})=>hre(t,e),u7e=(t,e)=>({editor:n,tr:r})=>{const{state:a}=n,s=a.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new wn(r.doc.resolve(Math.max(o-1,0)))),!0},d7e=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const a=t.selection.$anchor;for(let s=a.depth;s>0;s-=1)if(a.node(s).type===r.type){if(e){const l=a.before(s),c=a.after(s);t.delete(l,c).scrollIntoView()}return!0}return!1};function ii(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var h7e=t=>({tr:e,state:n,dispatch:r})=>{const a=ii(t,n.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===a){if(r){const c=s.before(o),u=s.after(o);e.delete(c,u).scrollIntoView()}return!0}return!1},m7e=t=>({tr:e,dispatch:n})=>{const{from:r,to:a}=t;return n&&e.delete(r,a),!0},f7e=()=>({state:t,dispatch:e})=>S4(t,e),p7e=()=>({commands:t})=>t.keyboardShortcut("Enter"),g7e=()=>({state:t,dispatch:e})=>JVe(t,e);function O4(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function eC(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(a=>n.strict?e[a]===t[a]:O4(e[a])?e[a].test(t[a]):e[a]===t[a]):!0}function Jre(t,e,n={}){return t.find(r=>r.type===e&&eC(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function cW(t,e,n={}){return!!Jre(t,e,n)}function I4(t,e,n){var r;if(!t||!e)return;let a=t.parent.childAfter(t.parentOffset);if((!a.node||!a.node.marks.some(d=>d.type===e))&&(a=t.parent.childBefore(t.parentOffset)),!a.node||!a.node.marks.some(d=>d.type===e)||(n=n||((r=a.node.marks[0])==null?void 0:r.attrs),!Jre([...a.node.marks],e,n)))return;let o=a.index,l=t.start()+a.offset,c=o+1,u=l+a.node.nodeSize;for(;o>0&&cW([...t.parent.child(o-1).marks],e,n);)o-=1,l-=t.parent.child(o).nodeSize;for(;c<t.parent.childCount&&cW([...t.parent.child(c).marks],e,n);)u+=t.parent.child(c).nodeSize,c+=1;return{from:l,to:u}}function yd(t,e){if(typeof t=="string"){if(!e.marks[t])throw Error(`There is no mark type named '${t}'. Maybe you forgot to add the extension?`);return e.marks[t]}return t}var b7e=(t,e={})=>({tr:n,state:r,dispatch:a})=>{const s=yd(t,r.schema),{doc:o,selection:l}=n,{$from:c,from:u,to:d}=l;if(a){const h=I4(c,s,e);if(h&&h.from<=u&&h.to>=d){const f=wn.create(o,h.from,h.to);n.setSelection(f)}}return!0},x7e=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r<n.length;r+=1)if(n[r](e))return!0;return!1};function eae(t){return t instanceof wn}function uf(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function tae(t,e=null){if(!e)return null;const n=Bn.atStart(t),r=Bn.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const a=n.from,s=r.to;return e==="all"?wn.create(t,uf(0,a,s),uf(t.content.size,a,s)):wn.create(t,uf(e,a,s),uf(e,a,s))}function uW(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function tC(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function y7e(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var v7e=(t=null,e={})=>({editor:n,view:r,tr:a,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(tC()||uW())&&r.dom.focus(),y7e()&&!tC()&&!uW()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e?.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!eae(n.state.selection))return o(),!0;const l=tae(a.doc,t)||n.state.selection,c=n.state.selection.eq(l);return s&&(c||a.setSelection(l),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),o()),!0},w7e=(t,e)=>n=>t.every((r,a)=>e(r,{...n,index:a})),S7e=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),nae=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&nae(r)}return t};function k_(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${t}</body>`,n=new window.DOMParser().parseFromString(e,"text/html").body;return nae(n)}function Jv(t,e,n){if(t instanceof Uh||t instanceof Mt)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,a=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return Mt.fromArray(t.map(l=>e.nodeFromJSON(l)));const o=e.nodeFromJSON(t);return n.errorOnInvalidContent&&o.check(),o}catch(s){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",s),Jv("",e,n)}if(a){if(n.errorOnInvalidContent){let o=!1,l="";const c=new zne({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:u=>(o=!0,l=typeof u=="string"?u:u.outerHTML,null)}]}})});if(n.slice?Zy.fromSchema(c).parseSlice(k_(t),n.parseOptions):Zy.fromSchema(c).parse(k_(t),n.parseOptions),n.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=Zy.fromSchema(e);return n.slice?s.parseSlice(k_(t),n.parseOptions).content:s.parse(k_(t),n.parseOptions)}return Jv("",e,n)}function _7e(t,e,n){const r=t.steps.length-1;if(r<e)return;const a=t.steps[r];if(!(a instanceof Di||a instanceof Fi))return;const s=t.mapping.maps[r];let o=0;s.forEach((l,c,u,d)=>{o===0&&(o=d)}),t.setSelection(Bn.near(t.doc.resolve(o),n))}var N7e=t=>!("type"in t),C7e=(t,e,n)=>({tr:r,dispatch:a,editor:s})=>{var o;if(a){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let l;const c=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},u={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{Jv(e,s.schema,{parseOptions:u,errorOnInvalidContent:!0})}catch(g){c(g)}try{l=Jv(e,s.schema,{parseOptions:u,errorOnInvalidContent:(o=n.errorOnInvalidContent)!=null?o:s.options.enableContentCheck})}catch(g){return c(g),!1}let{from:d,to:h}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},f=!0,p=!0;if((N7e(l)?l:[l]).forEach(g=>{g.check(),f=f?g.isText&&g.marks.length===0:!1,p=p?g.isBlock:!1}),d===h&&p){const{parent:g}=r.doc.resolve(d);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(d-=1,h+=1)}let v;if(f){if(Array.isArray(e))v=e.map(g=>g.text||"").join("");else if(e instanceof Mt){let g="";e.forEach(y=>{y.text&&(g+=y.text)}),v=g}else typeof e=="object"&&e&&e.text?v=e.text:v=e;r.insertText(v,d,h)}else{v=l;const g=r.doc.resolve(d),y=g.node(),_=g.parentOffset===0,N=y.isText||y.isTextblock,k=y.content.size>0;_&&N&&k&&(d=Math.max(0,d-1)),r.replaceWith(d,h,v)}n.updateSelection&&_7e(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:d,text:v}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:d,text:v})}return!0},k7e=()=>({state:t,dispatch:e})=>YVe(t,e),A7e=()=>({state:t,dispatch:e})=>QVe(t,e),T7e=()=>({state:t,dispatch:e})=>ire(t,e),M7e=()=>({state:t,dispatch:e})=>cre(t,e),P7e=()=>({state:t,dispatch:e,tr:n})=>{try{const r=cA(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},E7e=()=>({state:t,dispatch:e,tr:n})=>{try{const r=cA(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},j7e=()=>({state:t,dispatch:e})=>KVe(t,e),D7e=()=>({state:t,dispatch:e})=>XVe(t,e);function rae(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function R7e(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,a,s,o;for(let l=0;l<e.length-1;l+=1){const c=e[l];if(/^(cmd|meta|m)$/i.test(c))o=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))s=!0;else if(/^mod$/i.test(c))tC()||rae()?o=!0:a=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),a&&(n=`Ctrl-${n}`),o&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var F7e=t=>({editor:e,view:n,tr:r,dispatch:a})=>{const s=R7e(t).split(/-(?!$)/),o=s.find(u=>!["Alt","Ctrl","Meta","Shift"].includes(u)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{n.someProp("handleKeyDown",u=>u(n,l))});return c?.steps.forEach(u=>{const d=u.map(r.mapping);d&&a&&r.maybeStep(d)}),!0};function Jh(t,e,n={}){const{from:r,to:a,empty:s}=t.selection,o=e?ii(e,t.schema):null,l=[];t.doc.nodesBetween(r,a,(h,f)=>{if(h.isText)return;const p=Math.max(r,f),x=Math.min(a,f+h.nodeSize);l.push({node:h,from:p,to:x})});const c=a-r,u=l.filter(h=>o?o.name===h.node.type.name:!0).filter(h=>eC(h.node.attrs,n,{strict:!1}));return s?!!u.length:u.reduce((h,f)=>h+f.to-f.from,0)>=c}var L7e=(t,e={})=>({state:n,dispatch:r})=>{const a=ii(t,n.schema);return Jh(n,a,e)?ZVe(n,r):!1},O7e=()=>({state:t,dispatch:e})=>mre(t,e),I7e=t=>({state:e,dispatch:n})=>{const r=ii(t,e.schema);return uqe(r)(e,n)},z7e=()=>({state:t,dispatch:e})=>dre(t,e);function bA(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function dW(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,a)=>(n.includes(a)||(r[a]=t[a]),r),{})}var U7e=(t,e)=>({tr:n,state:r,dispatch:a})=>{let s=null,o=null;const l=bA(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ii(t,r.schema)),l==="mark"&&(o=yd(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{r.doc.nodesBetween(u.$from.pos,u.$to.pos,(d,h)=>{s&&s===d.type&&(c=!0,a&&n.setNodeMarkup(h,void 0,dW(d.attrs,e))),o&&d.marks.length&&d.marks.forEach(f=>{o===f.type&&(c=!0,a&&n.addMark(h,h+d.nodeSize,o.create(dW(f.attrs,e))))})})}),c},B7e=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),H7e=()=>({tr:t,dispatch:e})=>{if(e){const n=new Fo(t.doc);t.setSelection(n)}return!0},$7e=()=>({state:t,dispatch:e})=>ore(t,e),V7e=()=>({state:t,dispatch:e})=>ure(t,e),q7e=()=>({state:t,dispatch:e})=>nqe(t,e),G7e=()=>({state:t,dispatch:e})=>iqe(t,e),W7e=()=>({state:t,dispatch:e})=>aqe(t,e);function LR(t,e,n={},r={}){return Jv(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var K7e=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:a,tr:s,dispatch:o,commands:l})=>{const{doc:c}=s;if(r.preserveWhitespace!=="full"){const u=LR(t,a.schema,r,{errorOnInvalidContent:e??a.options.enableContentCheck});return o&&s.replaceWith(0,c.content.size,u).setMeta("preventUpdate",!n),!0}return o&&s.setMeta("preventUpdate",!n),l.insertContentAt({from:0,to:c.content.size},t,{parseOptions:r,errorOnInvalidContent:e??a.options.enableContentCheck})};function aae(t,e){const n=yd(e,t.schema),{from:r,to:a,empty:s}=t.selection,o=[];s?(t.storedMarks&&o.push(...t.storedMarks),o.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,a,c=>{o.push(...c.marks)});const l=o.find(c=>c.type.name===n.name);return l?{...l.attrs}:{}}function iae(t,e){const n=new tre(t);return e.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function X7e(t){for(let e=0;e<t.edgeCount;e+=1){const{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function Y7e(t,e,n){const r=[];return t.nodesBetween(e.from,e.to,(a,s)=>{n(a)&&r.push({node:a,pos:s})}),r}function Q7e(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function xA(t){return e=>Q7e(e.$from,t)}function rn(t,e,n){return t.config[e]===void 0&&t.parent?rn(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?rn(t.parent,e,n):null}):t.config[e]}function z4(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=rn(e,"addExtensions",n);return r?[e,...z4(r())]:e}).flat(10)}function U4(t,e){const n=sp.fromSchema(e).serializeFragment(t),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}function sae(t){return typeof t=="function"}function Cr(t,e=void 0,...n){return sae(t)?e?t.bind(e)(...n):t(...n):t}function Z7e(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Rb(t){const e=t.filter(a=>a.type==="extension"),n=t.filter(a=>a.type==="node"),r=t.filter(a=>a.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function oae(t){const e=[],{nodeExtensions:n,markExtensions:r}=Rb(t),a=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage,extensions:a},c=rn(o,"addGlobalAttributes",l);if(!c)return;c().forEach(d=>{d.types.forEach(h=>{Object.entries(d.attributes).forEach(([f,p])=>{e.push({type:h,name:f,attribute:{...s,...p}})})})})}),a.forEach(o=>{const l={name:o.name,options:o.options,storage:o.storage},c=rn(o,"addAttributes",l);if(!c)return;const u=c();Object.entries(u).forEach(([d,h])=>{const f={...s,...h};typeof f?.default=="function"&&(f.default=f.default()),f?.isRequired&&f?.default===void 0&&delete f.default,e.push({type:o.name,name:d,attribute:f})})}),e}function Fa(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([a,s])=>{if(!r[a]){r[a]=s;return}if(a==="class"){const l=s?String(s).split(" "):[],c=r[a]?r[a].split(" "):[],u=l.filter(d=>!c.includes(d));r[a]=[...c,...u].join(" ")}else if(a==="style"){const l=s?s.split(";").map(d=>d.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(d=>d.trim()).filter(Boolean):[],u=new Map;c.forEach(d=>{const[h,f]=d.split(":").map(p=>p.trim());u.set(h,f)}),l.forEach(d=>{const[h,f]=d.split(":").map(p=>p.trim());u.set(h,f)}),r[a]=Array.from(u.entries()).map(([d,h])=>`${d}: ${h}`).join("; ")}else r[a]=s}),r},{})}function e0(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>Fa(n,r),{})}function J7e(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function hW(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const a=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(n):J7e(n.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...a}}}}function mW(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&Z7e(n)?!1:n!=null))}function fW(t){var e,n;const r={};return!((e=t?.attribute)!=null&&e.isRequired)&&"default"in(t?.attribute||{})&&(r.default=t.attribute.default),((n=t?.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function e9e(t,e){var n;const r=oae(t),{nodeExtensions:a,markExtensions:s}=Rb(t),o=(n=a.find(u=>rn(u,"topNode")))==null?void 0:n.name,l=Object.fromEntries(a.map(u=>{const d=r.filter(y=>y.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},f=t.reduce((y,_)=>{const N=rn(_,"extendNodeSchema",h);return{...y,...N?N(u):{}}},{}),p=mW({...f,content:Cr(rn(u,"content",h)),marks:Cr(rn(u,"marks",h)),group:Cr(rn(u,"group",h)),inline:Cr(rn(u,"inline",h)),atom:Cr(rn(u,"atom",h)),selectable:Cr(rn(u,"selectable",h)),draggable:Cr(rn(u,"draggable",h)),code:Cr(rn(u,"code",h)),whitespace:Cr(rn(u,"whitespace",h)),linebreakReplacement:Cr(rn(u,"linebreakReplacement",h)),defining:Cr(rn(u,"defining",h)),isolating:Cr(rn(u,"isolating",h)),attrs:Object.fromEntries(d.map(fW))}),x=Cr(rn(u,"parseHTML",h));x&&(p.parseDOM=x.map(y=>hW(y,d)));const v=rn(u,"renderHTML",h);v&&(p.toDOM=y=>v({node:y,HTMLAttributes:e0(y,d)}));const g=rn(u,"renderText",h);return g&&(p.toText=g),[u.name,p]})),c=Object.fromEntries(s.map(u=>{const d=r.filter(g=>g.type===u.name),h={name:u.name,options:u.options,storage:u.storage,editor:e},f=t.reduce((g,y)=>{const _=rn(y,"extendMarkSchema",h);return{...g,..._?_(u):{}}},{}),p=mW({...f,inclusive:Cr(rn(u,"inclusive",h)),excludes:Cr(rn(u,"excludes",h)),group:Cr(rn(u,"group",h)),spanning:Cr(rn(u,"spanning",h)),code:Cr(rn(u,"code",h)),attrs:Object.fromEntries(d.map(fW))}),x=Cr(rn(u,"parseHTML",h));x&&(p.parseDOM=x.map(g=>hW(g,d)));const v=rn(u,"renderHTML",h);return v&&(p.toDOM=g=>v({mark:g,HTMLAttributes:e0(g,d)})),[u.name,p]}));return new zne({topNode:o,nodes:l,marks:c})}function t9e(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function nC(t){return t.sort((n,r)=>{const a=rn(n,"priority")||100,s=rn(r,"priority")||100;return a>s?-1:a<s?1:0})}function lae(t){const e=nC(z4(t)),n=t9e(e.map(r=>r.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function cae(t,e,n){const{from:r,to:a}=e,{blockSeparator:s=`
  8168. `,textSerializers:o={}}=n||{};let l="";return t.nodesBetween(r,a,(c,u,d,h)=>{var f;c.isBlock&&u>r&&(l+=s);const p=o?.[c.type.name];if(p)return d&&(l+=p({node:c,pos:u,parent:d,index:h,range:e})),!1;c.isText&&(l+=(f=c?.text)==null?void 0:f.slice(Math.max(r,u)-u,a-u))}),l}function n9e(t,e){const n={from:0,to:t.content.size};return cae(t,n,e)}function uae(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function r9e(t,e){const n=ii(e,t.schema),{from:r,to:a}=t.selection,s=[];t.doc.nodesBetween(r,a,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===n.name);return o?{...o.attrs}:{}}function dae(t,e){const n=bA(typeof e=="string"?e:e.name,t.schema);return n==="node"?r9e(t,e):n==="mark"?aae(t,e):{}}function a9e(t,e=JSON.stringify){const n={};return t.filter(r=>{const a=e(r);return Object.prototype.hasOwnProperty.call(n,a)?!1:n[a]=!0})}function i9e(t){const e=a9e(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,o)=>o!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function hae(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((a,s)=>{const o=[];if(a.ranges.length)a.forEach((l,c)=>{o.push({from:l,to:c})});else{const{from:l,to:c}=n[s];if(l===void 0||c===void 0)return;o.push({from:l,to:c})}o.forEach(({from:l,to:c})=>{const u=e.slice(s).map(l,-1),d=e.slice(s).map(c),h=e.invert().map(u,-1),f=e.invert().map(d);r.push({oldRange:{from:h,to:f},newRange:{from:u,to:d}})})}),i9e(r)}function B4(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(a=>{const s=n.resolve(t),o=I4(s,a.type);o&&r.push({mark:a,...o})}):n.nodesBetween(t,e,(a,s)=>{!a||a?.nodeSize===void 0||r.push(...a.marks.map(o=>({from:s,to:s+a.nodeSize,mark:o})))}),r}var s9e=(t,e,n,r=20)=>{const a=t.doc.resolve(n);let s=r,o=null;for(;s>0&&o===null;){const l=a.node(s);l?.type.name===e?o=l:s-=1}return[o,s]};function A_(t,e){return e.nodes[t]||e.marks[t]||null}function c1(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=t.find(s=>s.type===e&&s.name===r);return a?a.attribute.keepOnSplit:!1}))}var o9e=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(a,s,o,l)=>{var c,u;const d=((u=(c=a.type.spec).toText)==null?void 0:u.call(c,{node:a,pos:s,parent:o,index:l}))||a.textContent||"%leaf%";n+=a.isAtom&&!a.isText?d:d.slice(0,Math.max(0,r-s))}),n};function OR(t,e,n={}){const{empty:r,ranges:a}=t.selection,s=e?yd(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(h=>s?s.name===h.type.name:!0).find(h=>eC(h.attrs,n,{strict:!1}));let o=0;const l=[];if(a.forEach(({$from:h,$to:f})=>{const p=h.pos,x=f.pos;t.doc.nodesBetween(p,x,(v,g)=>{if(!v.isText&&!v.marks.length)return;const y=Math.max(p,g),_=Math.min(x,g+v.nodeSize),N=_-y;o+=N,l.push(...v.marks.map(k=>({mark:k,from:y,to:_})))})}),o===0)return!1;const c=l.filter(h=>s?s.name===h.mark.type.name:!0).filter(h=>eC(h.mark.attrs,n,{strict:!1})).reduce((h,f)=>h+f.to-f.from,0),u=l.filter(h=>s?h.mark.type!==s&&h.mark.type.excludes(s):!0).reduce((h,f)=>h+f.to-f.from,0);return(c>0?c+u:c)>=o}function l9e(t,e,n={}){if(!e)return Jh(t,null,n)||OR(t,null,n);const r=bA(e,t.schema);return r==="node"?Jh(t,e,n):r==="mark"?OR(t,e,n):!1}var c9e=(t,e)=>{const{$from:n,$to:r,$anchor:a}=t.selection;if(e){const s=xA(l=>l.type.name===e)(t.selection);if(!s)return!1;const o=t.doc.resolve(s.pos+1);return a.pos+1===o.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)},u9e=t=>{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function pW(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function gW(t,e){const{nodeExtensions:n}=Rb(e),r=n.find(o=>o.name===t);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},s=Cr(rn(r,"group",a));return typeof s!="string"?!1:s.split(" ").includes("list")}function yA(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let a=!0;return t.content.forEach(s=>{a!==!1&&(yA(s,{ignoreWhitespace:n,checkChildren:e})||(a=!1))}),a}return!1}function mae(t){return t instanceof cn}var fae=class pae{constructor(e){this.position=e}static fromJSON(e){return new pae(e.position)}toJSON(){return{position:this.position}}};function d9e(t,e){const n=e.mapping.mapResult(t.position);return{position:new fae(n.pos),mapResult:n}}function h9e(t){return new fae(t)}function m9e(t,e,n){var r;const{selection:a}=e;let s=null;if(eae(a)&&(s=a.$cursor),s){const l=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(l)||!l.some(u=>u.type.excludes(n)))}const{ranges:o}=a;return o.some(({$from:l,$to:c})=>{let u=l.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(l.pos,c.pos,(d,h,f)=>{if(u)return!1;if(d.isInline){const p=!f||f.type.allowsMarkType(n),x=!!n.isInSet(d.marks)||!d.marks.some(v=>v.type.excludes(n));u=p&&x}return!u}),u})}var f9e=(t,e={})=>({tr:n,state:r,dispatch:a})=>{const{selection:s}=n,{empty:o,ranges:l}=s,c=yd(t,r.schema);if(a)if(o){const u=aae(r,c);n.addStoredMark(c.create({...u,...e}))}else l.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;r.doc.nodesBetween(d,h,(f,p)=>{const x=Math.max(p,d),v=Math.min(p+f.nodeSize,h);f.marks.find(y=>y.type===c)?f.marks.forEach(y=>{c===y.type&&n.addMark(x,v,c.create({...y.attrs,...e}))}):n.addMark(x,v,c.create(e))})});return m9e(r,n,c)},p9e=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),g9e=(t,e={})=>({state:n,dispatch:r,chain:a})=>{const s=ii(t,n.schema);let o;return n.selection.$anchor.sameParent(n.selection.$head)&&(o=n.selection.$anchor.parent.attrs),s.isTextblock?a().command(({commands:l})=>M9(s,{...o,...e})(n)?!0:l.clearNodes()).command(({state:l})=>M9(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},b9e=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,a=uf(t,0,r.content.size),s=cn.create(r,a);e.setSelection(s)}return!0},x9e=(t,e)=>({tr:n,state:r,dispatch:a})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),a&&n.doc.nodesBetween(o,l,(c,u)=>{c.isText||n.setNodeMarkup(u,void 0,{...c.attrs,dir:t})}),!0},y9e=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:a,to:s}=typeof t=="number"?{from:t,to:t}:t,o=wn.atStart(r).from,l=wn.atEnd(r).to,c=uf(a,o,l),u=uf(s,o,l),d=wn.create(r,c,u);e.setSelection(d)}return!0},v9e=t=>({state:e,dispatch:n})=>{const r=ii(t,e.schema);return mqe(r)(e,n)};function bW(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(a=>e?.includes(a.type.name));t.tr.ensureMarks(r)}}var w9e=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:a})=>{const{selection:s,doc:o}=e,{$from:l,$to:c}=s,u=a.extensionManager.attributes,d=c1(u,l.node().type.name,l.node().attrs);if(s instanceof cn&&s.node.isBlock)return!l.parentOffset||!Yu(o,l.pos)?!1:(r&&(t&&bW(n,a.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,f=l.depth===0?void 0:X7e(l.node(-1).contentMatchAt(l.indexAfter(-1)));let p=h&&f?[{type:f,attrs:d}]:void 0,x=Yu(e.doc,e.mapping.map(l.pos),1,p);if(!p&&!x&&Yu(e.doc,e.mapping.map(l.pos),1,f?[{type:f}]:void 0)&&(x=!0,p=f?[{type:f,attrs:d}]:void 0),r){if(x&&(s instanceof wn&&e.deleteSelection(),e.split(e.mapping.map(l.pos),1,p),f&&!h&&!l.parentOffset&&l.parent.type!==f)){const v=e.mapping.map(l.before()),g=e.doc.resolve(v);l.node(-1).canReplaceWith(g.index(),g.index()+1,f)&&e.setNodeMarkup(e.mapping.map(l.before()),f)}t&&bW(n,a.extensionManager.splittableMarks),e.scrollIntoView()}return x},S9e=(t,e={})=>({tr:n,state:r,dispatch:a,editor:s})=>{var o;const l=ii(t,r.schema),{$from:c,$to:u}=r.selection,d=r.selection.node;if(d&&d.isBlock||c.depth<2||!c.sameParent(u))return!1;const h=c.node(-1);if(h.type!==l)return!1;const f=s.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==l||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let y=Mt.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let j=c.depth-_;j>=c.depth-3;j-=1)y=Mt.from(c.node(j).copy(y));const N=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,k={...c1(f,c.node().type.name,c.node().attrs),...e},A=((o=l.contentMatch.defaultType)==null?void 0:o.createAndFill(k))||void 0;y=y.append(Mt.from(l.createAndFill(null,A)||void 0));const M=c.before(c.depth-(_-1));n.replace(M,c.after(-N),new Wt(y,4-_,0));let C=-1;n.doc.nodesBetween(M,n.doc.content.size,(j,P)=>{if(C>-1)return!1;j.isTextblock&&j.content.size===0&&(C=P+1)}),C>-1&&n.setSelection(wn.near(n.doc.resolve(C))),n.scrollIntoView()}return!0}const p=u.pos===c.end()?h.contentMatchAt(0).defaultType:null,x={...c1(f,h.type.name,h.attrs),...e},v={...c1(f,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,u.pos);const g=p?[{type:l,attrs:x},{type:p,attrs:v}]:[{type:l,attrs:x}];if(!Yu(n.doc,c.pos,2))return!1;if(a){const{selection:y,storedMarks:_}=r,{splittableMarks:N}=s.extensionManager,k=_||y.$to.parentOffset&&y.$from.marks();if(n.split(c.pos,2,g).scrollIntoView(),!k||!a)return!0;const A=k.filter(M=>N.includes(M.type.name));n.ensureMarks(A)}return!0},u2=(t,e)=>{const n=xA(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=t.doc.nodeAt(r);return n.node.type===a?.type&&sm(t.doc,n.pos)&&t.join(n.pos),!0},d2=(t,e)=>{const n=xA(o=>o.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=t.doc.nodeAt(r);return n.node.type===a?.type&&sm(t.doc,r)&&t.join(r),!0},_9e=(t,e,n,r={})=>({editor:a,tr:s,state:o,dispatch:l,chain:c,commands:u,can:d})=>{const{extensions:h,splittableMarks:f}=a.extensionManager,p=ii(t,o.schema),x=ii(e,o.schema),{selection:v,storedMarks:g}=o,{$from:y,$to:_}=v,N=y.blockRange(_),k=g||v.$to.parentOffset&&v.$from.marks();if(!N)return!1;const A=xA(M=>gW(M.type.name,h))(v);if(N.depth>=1&&A&&N.depth-A.depth<=1){if(A.node.type===p)return u.liftListItem(x);if(gW(A.node.type.name,h)&&p.validContent(A.node.content)&&l)return c().command(()=>(s.setNodeMarkup(A.pos,p),!0)).command(()=>u2(s,p)).command(()=>d2(s,p)).run()}return!n||!k||!l?c().command(()=>d().wrapInList(p,r)?!0:u.clearNodes()).wrapInList(p,r).command(()=>u2(s,p)).command(()=>d2(s,p)).run():c().command(()=>{const M=d().wrapInList(p,r),C=k.filter(j=>f.includes(j.type.name));return s.ensureMarks(C),M?!0:u.clearNodes()}).wrapInList(p,r).command(()=>u2(s,p)).command(()=>d2(s,p)).run()},N9e=(t,e={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:s=!1}=n,o=yd(t,r.schema);return OR(r,o,e)?a.unsetMark(o,{extendEmptyMarkRange:s}):a.setMark(o,e)},C9e=(t,e,n={})=>({state:r,commands:a})=>{const s=ii(t,r.schema),o=ii(e,r.schema),l=Jh(r,s,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),l?a.setNode(o,c):a.setNode(s,{...c,...n})},k9e=(t,e={})=>({state:n,commands:r})=>{const a=ii(t,n.schema);return Jh(n,a,e)?r.lift(a):r.wrapIn(a,e)},A9e=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const a=n[r];let s;if(a.spec.isInputRules&&(s=a.getState(t))){if(e){const o=t.tr,l=s.transform;for(let c=l.steps.length-1;c>=0;c-=1)o.step(l.steps[c].invert(l.docs[c]));if(s.text){const c=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,t.schema.text(s.text,c))}else o.delete(s.from,s.to)}return!0}}return!1},T9e=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:a}=n;return r||e&&a.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},M9e=(t,e={})=>({tr:n,state:r,dispatch:a})=>{var s;const{extendEmptyMarkRange:o=!1}=e,{selection:l}=n,c=yd(t,r.schema),{$from:u,empty:d,ranges:h}=l;if(!a)return!0;if(d&&o){let{from:f,to:p}=l;const x=(s=u.marks().find(g=>g.type===c))==null?void 0:s.attrs,v=I4(u,c,x);v&&(f=v.from,p=v.to),n.removeMark(f,p,c)}else h.forEach(f=>{n.removeMark(f.$from.pos,f.$to.pos,c)});return n.removeStoredMark(c),!0},P9e=t=>({tr:e,state:n,dispatch:r})=>{const{selection:a}=n;let s,o;return typeof t=="number"?(s=t,o=t):t&&"from"in t&&"to"in t?(s=t.from,o=t.to):(s=a.from,o=a.to),r&&e.doc.nodesBetween(s,o,(l,c)=>{if(l.isText)return;const u={...l.attrs};delete u.dir,e.setNodeMarkup(c,void 0,u)}),!0},E9e=(t,e={})=>({tr:n,state:r,dispatch:a})=>{let s=null,o=null;const l=bA(typeof t=="string"?t:t.name,r.schema);if(!l)return!1;l==="node"&&(s=ii(t,r.schema)),l==="mark"&&(o=yd(t,r.schema));let c=!1;return n.selection.ranges.forEach(u=>{const d=u.$from.pos,h=u.$to.pos;let f,p,x,v;n.selection.empty?r.doc.nodesBetween(d,h,(g,y)=>{s&&s===g.type&&(c=!0,x=Math.max(y,d),v=Math.min(y+g.nodeSize,h),f=y,p=g)}):r.doc.nodesBetween(d,h,(g,y)=>{y<d&&s&&s===g.type&&(c=!0,x=Math.max(y,d),v=Math.min(y+g.nodeSize,h),f=y,p=g),y>=d&&y<=h&&(s&&s===g.type&&(c=!0,a&&n.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(_=>{if(o===_.type&&(c=!0,a)){const N=Math.max(y,d),k=Math.min(y+g.nodeSize,h);n.addMark(N,k,o.create({..._.attrs,...e}))}}))}),p&&(f!==void 0&&a&&n.setNodeMarkup(f,void 0,{...p.attrs,...e}),o&&p.marks.length&&p.marks.forEach(g=>{o===g.type&&a&&n.addMark(x,v,o.create({...g.attrs,...e}))}))}),c},j9e=(t,e={})=>({state:n,dispatch:r})=>{const a=ii(t,n.schema);return sqe(a,e)(n,r)},D9e=(t,e={})=>({state:n,dispatch:r})=>{const a=ii(t,n.schema);return oqe(a,e)(n,r)},R9e=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},vA=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},F9e=(t,e)=>{if(O4(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function T_(t){var e;const{editor:n,from:r,to:a,text:s,rules:o,plugin:l}=t,{view:c}=n;if(c.composing)return!1;const u=c.state.doc.resolve(r);if(u.parent.type.spec.code||(e=u.nodeBefore||u.nodeAfter)!=null&&e.marks.find(f=>f.type.spec.code))return!1;let d=!1;const h=o9e(u)+s;return o.forEach(f=>{if(d)return;const p=F9e(h,f.find);if(!p)return;const x=c.state.tr,v=pA({state:c.state,transaction:x}),g={from:r-(p[0].length-s.length),to:a},{commands:y,chain:_,can:N}=new gA({editor:n,state:v});f.handler({state:v,range:g,match:p,commands:y,chain:_,can:N})===null||!x.steps.length||(f.undoable&&x.setMeta(l,{transform:x,from:r,to:a,text:s}),c.dispatch(x),d=!0)}),d}function L9e(t){const{editor:e,rules:n}=t,r=new ya({state:{init(){return null},apply(a,s,o){const l=a.getMeta(r);if(l)return l;const c=a.getMeta("applyInputRules");return c&&setTimeout(()=>{let{text:d}=c;typeof d=="string"?d=d:d=U4(Mt.from(d),o.schema);const{from:h}=c,f=h+d.length;T_({editor:e,from:h,to:f,text:d,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:s}},props:{handleTextInput(a,s,o,l){return T_({editor:e,from:s,to:o,text:l,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:s}=a.state.selection;s&&T_({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(a,s){if(s.key!=="Enter")return!1;const{$cursor:o}=a.state.selection;return o?T_({editor:e,from:o.pos,to:o.pos,text:`
  8169. `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function O9e(t){return Object.prototype.toString.call(t).slice(8,-1)}function M_(t){return O9e(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function gae(t,e){const n={...t};return M_(t)&&M_(e)&&Object.keys(e).forEach(r=>{M_(e[r])&&M_(t[r])?n[r]=gae(t[r],e[r]):n[r]=e[r]}),n}var H4=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...Cr(rn(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Cr(rn(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>gae(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},lm=class bae extends H4{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new bae(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,a=e.state.selection.$from;if(a.pos===a.end()){const o=a.marks();if(!!!o.find(u=>u?.type.name===n.name))return!1;const c=o.find(u=>u?.type.name===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",a.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function I9e(t){return typeof t=="number"}var z9e=class{constructor(t){this.find=t.find,this.handler=t.handler}},U9e=(t,e,n)=>{if(O4(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(a=>{const s=[a.text];return s.index=a.index,s.input=t,s.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(a.replaceWith)),s}):[]};function B9e(t){const{editor:e,state:n,from:r,to:a,rule:s,pasteEvent:o,dropEvent:l}=t,{commands:c,chain:u,can:d}=new gA({editor:e,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,x)=>{var v,g,y,_,N;if((g=(v=p.type)==null?void 0:v.spec)!=null&&g.code||!(p.isText||p.isTextblock||p.isInline))return;const k=(N=(_=(y=p.content)==null?void 0:y.size)!=null?_:p.nodeSize)!=null?N:0,A=Math.max(r,x),M=Math.min(a,x+k);if(A>=M)return;const C=p.isText?p.text||"":p.textBetween(A-x,M-x,void 0,"");U9e(C,s.find,o).forEach(P=>{if(P.index===void 0)return;const E=A+P.index+1,U=E+P[0].length,L={from:n.tr.mapping.map(E),to:n.tr.mapping.map(U)},B=s.handler({state:n,range:L,match:P,commands:c,chain:u,can:d,pasteEvent:o,dropEvent:l});h.push(B)})}),h.every(p=>p!==null)}var P_=null,H9e=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function $9e(t){const{editor:e,rules:n}=t;let r=null,a=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const c=({state:d,from:h,to:f,rule:p,pasteEvt:x})=>{const v=d.tr,g=pA({state:d,transaction:v});if(!(!B9e({editor:e,state:g,from:Math.max(h-1,0),to:f.b-1,rule:p,pasteEvent:x,dropEvent:l})||!v.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,v}};return n.map(d=>new ya({view(h){const f=x=>{var v;r=(v=h.dom.parentElement)!=null&&v.contains(x.target)?h.dom.parentElement:null,r&&(P_=e)},p=()=>{P_&&(P_=null)};return window.addEventListener("dragstart",f),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",f),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,f)=>{if(s=r===h.dom.parentElement,l=f,!s){const p=P_;p?.isEditable&&setTimeout(()=>{const x=p.state.selection;x&&p.commands.deleteRange({from:x.from,to:x.to})},10)}return!1},paste:(h,f)=>{var p;const x=(p=f.clipboardData)==null?void 0:p.getData("text/html");return o=f,a=!!x?.includes("data-pm-slice"),!1}}},appendTransaction:(h,f,p)=>{const x=h[0],v=x.getMeta("uiEvent")==="paste"&&!a,g=x.getMeta("uiEvent")==="drop"&&!s,y=x.getMeta("applyPasteRules"),_=!!y;if(!v&&!g&&!_)return;if(_){let{text:A}=y;typeof A=="string"?A=A:A=U4(Mt.from(A),p.schema);const{from:M}=y,C=M+A.length,j=H9e(A);return c({rule:d,state:p,from:M,to:{b:C},pasteEvt:j})}const N=f.doc.content.findDiffStart(p.doc.content),k=f.doc.content.findDiffEnd(p.doc.content);if(!(!I9e(N)||!k||N===k.b))return c({rule:d,state:p,from:N,to:k,pasteEvt:o})}}))}var wA=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=lae(t),this.schema=e9e(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:A_(e.name,this.schema)},r=rn(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return nC([...this.extensions].reverse()).flatMap(r=>{const a={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:A_(r.name,this.schema)},s=[],o=rn(r,"addKeyboardShortcuts",a);let l={};if(r.type==="mark"&&rn(r,"exitable",a)&&(l.ArrowRight=()=>lm.handleExit({editor:t,mark:r})),o){const f=Object.fromEntries(Object.entries(o()).map(([p,x])=>[p,()=>x({editor:t})]));l={...l,...f}}const c=r7e(l);s.push(c);const u=rn(r,"addInputRules",a);if(pW(r,t.options.enableInputRules)&&u){const f=u();if(f&&f.length){const p=L9e({editor:t,rules:f}),x=Array.isArray(p)?p:[p];s.push(...x)}}const d=rn(r,"addPasteRules",a);if(pW(r,t.options.enablePasteRules)&&d){const f=d();if(f&&f.length){const p=$9e({editor:t,rules:f});s.push(...p)}}const h=rn(r,"addProseMirrorPlugins",a);if(h){const f=h();s.push(...f)}return s})}get attributes(){return oae(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Rb(this.extensions);return Object.fromEntries(e.filter(n=>!!rn(n,"addNodeView")).map(n=>{const r=this.attributes.filter(c=>c.type===n.name),a={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:ii(n.name,this.schema)},s=rn(n,"addNodeView",a);if(!s)return[];const o=s();if(!o)return[];const l=(c,u,d,h,f)=>{const p=e0(c,r);return o({node:c,view:u,getPos:d,decorations:h,innerDecorations:f,editor:t,extension:n,HTMLAttributes:p})};return[n.name,l]}))}dispatchTransaction(t){const{editor:e}=this;return nC([...this.extensions].reverse()).reduceRight((r,a)=>{const s={name:a.name,options:a.options,storage:this.editor.extensionStorage[a.name],editor:e,type:A_(a.name,this.schema)},o=rn(a,"dispatchTransaction",s);return o?l=>{o.call(s,{transaction:l,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Rb(this.extensions);return Object.fromEntries(e.filter(n=>!!rn(n,"addMarkView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),a={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:yd(n.name,this.schema)},s=rn(n,"addMarkView",a);if(!s)return[];const o=(l,c,u)=>{const d=e0(l,r);return s()({mark:l,view:c,inline:u,editor:t,extension:n,HTMLAttributes:d,updateAttributes:h=>{aWe(l,t,h)}})};return[n.name,o]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:A_(e.name,this.schema)};e.type==="mark"&&((n=Cr(rn(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const a=rn(e,"onBeforeCreate",r),s=rn(e,"onCreate",r),o=rn(e,"onUpdate",r),l=rn(e,"onSelectionUpdate",r),c=rn(e,"onTransaction",r),u=rn(e,"onFocus",r),d=rn(e,"onBlur",r),h=rn(e,"onDestroy",r);a&&this.editor.on("beforeCreate",a),s&&this.editor.on("create",s),o&&this.editor.on("update",o),l&&this.editor.on("selectionUpdate",l),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};wA.resolve=lae;wA.sort=nC;wA.flatten=z4;var V9e={};L4(V9e,{ClipboardTextSerializer:()=>yae,Commands:()=>vae,Delete:()=>wae,Drop:()=>Sae,Editable:()=>_ae,FocusEvents:()=>Cae,Keymap:()=>kae,Paste:()=>Aae,Tabindex:()=>Tae,TextDirection:()=>Mae,focusEventsPluginKey:()=>Nae});var zr=class xae extends H4{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new xae(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},yae=zr.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ya({key:new Ni("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:a}=e,{ranges:s}=a,o=Math.min(...s.map(d=>d.$from.pos)),l=Math.max(...s.map(d=>d.$to.pos)),c=uae(n);return cae(r,{from:o,to:l},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),vae=zr.create({name:"commands",addCommands(){return{...Zre}}}),wae=zr.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,a;const s=()=>{var o,l,c,u;if((u=(c=(l=(o=this.editor.options.coreExtensionOptions)==null?void 0:o.delete)==null?void 0:l.filterTransaction)==null?void 0:c.call(l,t))!=null?u:t.getMeta("y-sync$"))return;const d=iae(t.before,[t,...e]);hae(d).forEach(p=>{d.mapping.mapResult(p.oldRange.from).deletedAfter&&d.mapping.mapResult(p.oldRange.to).deletedBefore&&d.before.nodesBetween(p.oldRange.from,p.oldRange.to,(x,v)=>{const g=v+x.nodeSize-2,y=p.oldRange.from<=v&&g<=p.oldRange.to;this.editor.emit("delete",{type:"node",node:x,from:v,to:g,newFrom:d.mapping.map(v),newTo:d.mapping.map(g),deletedRange:p.oldRange,newRange:p.newRange,partial:!y,editor:this.editor,transaction:t,combinedTransform:d})})});const f=d.mapping;d.steps.forEach((p,x)=>{var v,g;if(p instanceof Wl){const y=f.slice(x).map(p.from,-1),_=f.slice(x).map(p.to),N=f.invert().map(y,-1),k=f.invert().map(_),A=(v=d.doc.nodeAt(y-1))==null?void 0:v.marks.some(C=>C.eq(p.mark)),M=(g=d.doc.nodeAt(_))==null?void 0:g.marks.some(C=>C.eq(p.mark));this.editor.emit("delete",{type:"mark",mark:p.mark,from:p.from,to:p.to,deletedRange:{from:N,to:k},newRange:{from:y,to:_},partial:!!(M||A),editor:this.editor,transaction:t,combinedTransform:d})}})};(a=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||a?setTimeout(s,0):s()}}),Sae=zr.create({name:"drop",addProseMirrorPlugins(){return[new ya({key:new Ni("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),_ae=zr.create({name:"editable",addProseMirrorPlugins(){return[new ya({key:new Ni("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Nae=new Ni("focusEvents"),Cae=zr.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new ya({key:Nae,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),kae=zr.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:c,doc:u}=l,{empty:d,$anchor:h}=c,{pos:f,parent:p}=h,x=h.parent.isTextblock&&f>0?l.doc.resolve(f-1):h,v=x.parent.type.spec.isolating,g=h.pos-h.parentOffset,y=v&&x.parent.childCount===1?g===h.pos:Bn.atStart(u).from===f;return!d||!p.type.isTextblock||p.textContent.length||!y||y&&h.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return tC()||rae()?s:a},addProseMirrorPlugins(){return[new ya({key:new Ni("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(v=>v.getMeta("composition")))return;const r=t.some(v=>v.docChanged)&&!e.doc.eq(n.doc),a=t.some(v=>v.getMeta("preventClearDocument"));if(!r||a)return;const{empty:s,from:o,to:l}=e.selection,c=Bn.atStart(e.doc).from,u=Bn.atEnd(e.doc).to;if(s||!(o===c&&l===u)||!yA(n.doc))return;const f=n.tr,p=pA({state:n,transaction:f}),{commands:x}=new gA({editor:this.editor,state:p});if(x.clearNodes(),!!f.steps.length)return f}})]}}),Aae=zr.create({name:"paste",addProseMirrorPlugins(){return[new ya({key:new Ni("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),Tae=zr.create({name:"tabindex",addProseMirrorPlugins(){return[new ya({key:new Ni("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Mae=zr.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Rb(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ya({key:new Ni("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),q9e=class Oy{constructor(e,n,r=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=a}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new Oy(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new Oy(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new Oy(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const a=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,o=n.isInline,l=this.pos+r+(s?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const c=this.resolvedPos.doc.resolve(l);if(!a&&!o&&c.depth<=this.depth)return;const u=new Oy(c,this.editor,a,a||o?n:null);a&&(u.actualDepth=this.depth+1),e.push(u)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,a=this.parent;for(;a&&!r;){if(a.node.type.name===e)if(Object.keys(n).length>0){const s=a.node.attrs,o=Object.keys(n);for(let l=0;l<o.length;l+=1){const c=o[l];if(s[c]!==n[c])break}}else r=a;a=a.parent}return r}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},r=!1){let a=[];if(!this.children||this.children.length===0)return a;const s=Object.keys(n);return this.children.forEach(o=>{r&&a.length>0||(o.node.type.name===e&&s.every(c=>n[c]===o.node.attrs[c])&&a.push(o),!(r&&a.length>0)&&(a=a.concat(o.querySelectorAll(e,n,r))))}),a}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},G9e=`.ProseMirror {
  8170. position: relative;
  8171. }
  8172. .ProseMirror {
  8173. word-wrap: break-word;
  8174. white-space: pre-wrap;
  8175. white-space: break-spaces;
  8176. -webkit-font-variant-ligatures: none;
  8177. font-variant-ligatures: none;
  8178. font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
  8179. }
  8180. .ProseMirror [contenteditable="false"] {
  8181. white-space: normal;
  8182. }
  8183. .ProseMirror [contenteditable="false"] [contenteditable="true"] {
  8184. white-space: pre-wrap;
  8185. }
  8186. .ProseMirror pre {
  8187. white-space: pre-wrap;
  8188. }
  8189. img.ProseMirror-separator {
  8190. display: inline !important;
  8191. border: none !important;
  8192. margin: 0 !important;
  8193. width: 0 !important;
  8194. height: 0 !important;
  8195. }
  8196. .ProseMirror-gapcursor {
  8197. display: none;
  8198. pointer-events: none;
  8199. position: absolute;
  8200. margin: 0;
  8201. }
  8202. .ProseMirror-gapcursor:after {
  8203. content: "";
  8204. display: block;
  8205. position: absolute;
  8206. top: -2px;
  8207. width: 20px;
  8208. border-top: 1px solid black;
  8209. animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
  8210. }
  8211. @keyframes ProseMirror-cursor-blink {
  8212. to {
  8213. visibility: hidden;
  8214. }
  8215. }
  8216. .ProseMirror-hideselection *::selection {
  8217. background: transparent;
  8218. }
  8219. .ProseMirror-hideselection *::-moz-selection {
  8220. background: transparent;
  8221. }
  8222. .ProseMirror-hideselection * {
  8223. caret-color: transparent;
  8224. }
  8225. .ProseMirror-focused .ProseMirror-gapcursor {
  8226. display: block;
  8227. }`;function W9e(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const a=document.createElement("style");return e&&a.setAttribute("nonce",e),a.setAttribute("data-tiptap-style",""),a.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(a),a}var K9e=class extends R9e{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:d9e,createMappablePosition:h9e},this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:a,moved:s})=>this.options.onDrop(r,a,s)),this.on("paste",({event:r,slice:a})=>this.options.onPaste(r,a)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=tae(e,this.options.autofocus);this.editorState=Vg.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;t?.editor&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=W9e(G9e,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=sae(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(a=>{const s=typeof a=="string"?`${a}$`:a.key;n=n.filter(o=>!o.key.startsWith(s))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e;const r=[...this.options.enableCoreExtensions?[_ae,yae.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),vae,Cae,kae,Tae,Sae,Aae,wae,Mae.configure({direction:this.options.textDirection})].filter(a=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[a.name]!==!1:!0):[],...this.options.extensions].filter(a=>["extension","node","mark"].includes(a?.type));this.extensionManager=new wA(r,this)}createCommandManager(){this.commandManager=new gA({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=LR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),t=LR(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),a=n?this.extensionManager.dispatchTransaction(r):r;this.editorView=new Yre(t,{...e,attributes:{role:"textbox",...e?.attributes},dispatchTransaction:a,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const s=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(s),this.prependClass(),this.injectCSS();const o=this.view.dom;o.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(u=>{var d;return(d=this.capturedTransaction)==null?void 0:d.step(u)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),a=n.includes(t),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!a)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const o=n.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),l=o?.getMeta("focus"),c=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),c&&this.emit("blur",{editor:this,event:c.event,transaction:o}),!(t.getMeta("preventUpdate")||!n.some(u=>u.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return dae(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,r=typeof t=="string"?e:t;return l9e(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return U4(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=`
  8228. `,textSerializers:n={}}=t||{};return n9e(this.state.doc,{blockSeparator:e,textSerializers:{...uae(this.schema),...n}})}get isEmpty(){return yA(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new q9e(e,this)}get $doc(){return this.$pos(0)}};function Fb(t){return new vA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=Cr(t.getAttributes,void 0,r);if(a===!1||a===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const c=l.search(/\S/),u=n.from+l.indexOf(o),d=u+o.length;if(B4(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(v=>v===t.type&&v!==p.mark.type)).filter(p=>p.to>u).length)return null;d<n.to&&s.delete(d,n.to),u>n.from&&s.delete(n.from+c,u);const f=n.from+c+o.length;s.addMark(n.from+c,f,t.type.create(a||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}function Pae(t){return new vA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=Cr(t.getAttributes,void 0,r)||{},{tr:s}=e,o=n.from;let l=n.to;const c=t.type.create(a);if(r[1]){const u=r[0].lastIndexOf(r[1]);let d=o+u;d>l?d=l:l=d+r[1].length;const h=r[0][r[0].length-1];s.insertText(h,o+r[0].length-1),s.replaceWith(d,l,c)}else if(r[0]){const u=t.type.isInline?o:o-1;s.insert(u,t.type.create(a)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:t.undoable})}function IR(t){return new vA({find:t.find,handler:({state:e,range:n,match:r})=>{const a=e.doc.resolve(n.from),s=Cr(t.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,s)},undoable:t.undoable})}function Lb(t){return new vA({find:t.find,handler:({state:e,range:n,match:r,chain:a})=>{const s=Cr(t.getAttributes,void 0,r)||{},o=e.tr.delete(n.from,n.to),c=o.doc.resolve(n.from).blockRange(),u=c&&v4(c,t.type,s);if(!u)return null;if(o.wrap(c,u),t.keepMarks&&t.editor){const{selection:h,storedMarks:f}=e,{splittableMarks:p}=t.editor.extensionManager,x=f||h.$to.parentOffset&&h.$from.marks();if(x){const v=x.filter(g=>p.includes(g.type.name));o.ensureMarks(v)}}if(t.keepAttributes){const h=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(h,s).run()}const d=o.doc.resolve(n.from-1).nodeBefore;d&&d.type===t.type&&sm(o.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,d))&&o.join(n.from-1)},undoable:t.undoable})}var X9e=t=>"touches"in t,Y9e=class{constructor(t){this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.clientX-this.startX,u=l.clientY-this.startY;this.handleResize(c,u)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const c=l.touches[0];if(!c)return;const u=c.clientX-this.startX,d=c.clientY-this.startY;this.handleResize(u,d)},this.handleMouseUp=()=>{if(!this.isResizing)return;const l=this.element.offsetWidth,c=this.element.offsetHeight;this.onCommit(l,c),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)};var e,n,r,a,s,o;this.node=t.node,this.editor=t.editor,this.element=t.element,this.contentElement=t.contentElement,this.getPos=t.getPos,this.onResize=t.onResize,this.onCommit=t.onCommit,this.onUpdate=t.onUpdate,(e=t.options)!=null&&e.min&&(this.minSize={...this.minSize,...t.options.min}),(n=t.options)!=null&&n.max&&(this.maxSize=t.options.max),(r=t?.options)!=null&&r.directions&&(this.directions=t.options.directions),(a=t.options)!=null&&a.preserveAspectRatio&&(this.preserveAspectRatio=t.options.preserveAspectRatio),(s=t.options)!=null&&s.className&&(this.classNames={container:t.options.className.container||"",wrapper:t.options.className.wrapper||"",handle:t.options.className.handle||"",resizing:t.options.className.resizing||""}),(o=t.options)!=null&&o.createCustomHandle&&(this.createCustomHandle=t.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var t;return(t=this.contentElement)!=null?t:null}handleEditorUpdate(){const t=this.editor.isEditable;t!==this.lastEditableState&&(this.lastEditableState=t,t?t&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}update(t,e,n){return t.type!==this.node.type?!1:(this.node=t,this.onUpdate?this.onUpdate(t,e,n):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const t=document.createElement("div");return t.dataset.resizeContainer="",t.dataset.node=this.node.type.name,t.style.display="flex",this.classNames.container&&(t.className=this.classNames.container),t.appendChild(this.wrapper),t}createWrapper(){const t=document.createElement("div");return t.style.position="relative",t.style.display="block",t.dataset.resizeWrapper="",this.classNames.wrapper&&(t.className=this.classNames.wrapper),t.appendChild(this.element),t}createHandle(t){const e=document.createElement("div");return e.dataset.resizeHandle=t,e.style.position="absolute",this.classNames.handle&&(e.className=this.classNames.handle),e}positionHandle(t,e){const n=e.includes("top"),r=e.includes("bottom"),a=e.includes("left"),s=e.includes("right");n&&(t.style.top="0"),r&&(t.style.bottom="0"),a&&(t.style.left="0"),s&&(t.style.right="0"),(e==="top"||e==="bottom")&&(t.style.left="0",t.style.right="0"),(e==="left"||e==="right")&&(t.style.top="0",t.style.bottom="0")}attachHandles(){this.directions.forEach(t=>{let e;this.createCustomHandle?e=this.createCustomHandle(t):e=this.createHandle(t),e instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${t}") did not return an HTMLElement. Falling back to default handle.`),e=this.createHandle(t)),this.createCustomHandle||this.positionHandle(e,t),e.addEventListener("mousedown",n=>this.handleResizeStart(n,t)),e.addEventListener("touchstart",n=>this.handleResizeStart(n,t)),this.handleMap.set(t,e),this.wrapper.appendChild(e)})}removeHandles(){this.handleMap.forEach(t=>t.remove()),this.handleMap.clear()}applyInitialSize(){const t=this.node.attrs.width,e=this.node.attrs.height;t?(this.element.style.width=`${t}px`,this.initialWidth=t):this.initialWidth=this.element.offsetWidth,e?(this.element.style.height=`${e}px`,this.initialHeight=e):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(t,e){t.preventDefault(),t.stopPropagation(),this.isResizing=!0,this.activeHandle=e,X9e(t)?(this.startX=t.touches[0].clientX,this.startY=t.touches[0].clientY):(this.startX=t.clientX,this.startY=t.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(t,e){if(!this.activeHandle)return;const n=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:a}=this.calculateNewDimensions(this.activeHandle,t,e),s=this.applyConstraints(r,a,n);this.element.style.width=`${s.width}px`,this.element.style.height=`${s.height}px`,this.onResize&&this.onResize(s.width,s.height)}calculateNewDimensions(t,e,n){let r=this.startWidth,a=this.startHeight;const s=t.includes("right"),o=t.includes("left"),l=t.includes("bottom"),c=t.includes("top");return s?r=this.startWidth+e:o&&(r=this.startWidth-e),l?a=this.startHeight+n:c&&(a=this.startHeight-n),(t==="right"||t==="left")&&(r=this.startWidth+(s?e:-e)),(t==="top"||t==="bottom")&&(a=this.startHeight+(l?n:-n)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,a,t):{width:r,height:a}}applyConstraints(t,e,n){var r,a,s,o;if(!n){let u=Math.max(this.minSize.width,t),d=Math.max(this.minSize.height,e);return(r=this.maxSize)!=null&&r.width&&(u=Math.min(this.maxSize.width,u)),(a=this.maxSize)!=null&&a.height&&(d=Math.min(this.maxSize.height,d)),{width:u,height:d}}let l=t,c=e;return l<this.minSize.width&&(l=this.minSize.width,c=l/this.aspectRatio),c<this.minSize.height&&(c=this.minSize.height,l=c*this.aspectRatio),(s=this.maxSize)!=null&&s.width&&l>this.maxSize.width&&(l=this.maxSize.width,c=l/this.aspectRatio),(o=this.maxSize)!=null&&o.height&&c>this.maxSize.height&&(c=this.maxSize.height,l=c*this.aspectRatio),{width:l,height:c}}applyAspectRatio(t,e,n){const r=n==="left"||n==="right",a=n==="top"||n==="bottom";return r?{width:t,height:t/this.aspectRatio}:a?{width:e*this.aspectRatio,height:e}:{width:t,height:t/this.aspectRatio}}};function Q9e(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof cn){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let a=r.depth;for(;a>=0;){const s=r.index(a);if(r.node(a).contentMatchAt(s).matchType(e))return!0;a-=1}return!1}var Z9e={};L4(Z9e,{createAtomBlockMarkdownSpec:()=>J9e,createBlockMarkdownSpec:()=>eWe,createInlineMarkdownSpec:()=>rWe,parseAttributes:()=>$4,parseIndentedBlocks:()=>zR,renderNestedMarkdownContent:()=>q4,serializeAttributes:()=>V4});function $4(t){if(!t?.trim())return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,u=>(n.push(u),`__QUOTED_${n.length-1}__`)),a=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(a){const u=a.map(d=>d.trim().slice(1));e.class=u.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const o=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(o)).forEach(([,u,d])=>{var h;const f=parseInt(((h=d.match(/__QUOTED_(\d+)__/))==null?void 0:h[1])||"0",10),p=n[f];p&&(e[u]=p.slice(1,-1))});const c=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(d=>{d.match(/^[a-zA-Z][\w-]*$/)&&(e[d]=!0)}),e}function V4(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function J9e(t){const{nodeName:e,name:n,parseAttributes:r=$4,serializeAttributes:a=V4,defaultAttributes:s={},requiredAttributes:o=[],allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const h={};return l.forEach(f=>{f in d&&(h[f]=d[f])}),h};return{parseMarkdown:(d,h)=>{const f={...s,...d.attributes};return h.createNode(e,f,[])},markdownTokenizer:{name:e,level:"block",start(d){var h;const f=new RegExp(`^:::${c}(?:\\s|$)`,"m"),p=(h=d.match(f))==null?void 0:h.index;return p!==void 0?p:-1},tokenize(d,h,f){const p=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),x=d.match(p);if(!x)return;const v=x[1]||"",g=r(v);if(!o.find(_=>!(_ in g)))return{type:e,raw:x[0],attributes:g}}},renderMarkdown:d=>{const h=u(d.attrs||{}),f=a(h),p=f?` {${f}}`:"";return`:::${c}${p} :::`}}}function eWe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:a=$4,serializeAttributes:s=V4,defaultAttributes:o={},content:l="block",allowedAttributes:c}=t,u=n||e,d=h=>{if(!c)return h;const f={};return c.forEach(p=>{p in h&&(f[p]=h[p])}),f};return{parseMarkdown:(h,f)=>{let p;if(r){const v=r(h);p=typeof v=="string"?[{type:"text",text:v}]:v}else l==="block"?p=f.parseChildren(h.tokens||[]):p=f.parseInline(h.tokens||[]);const x={...o,...h.attributes};return f.createNode(e,x,p)},markdownTokenizer:{name:e,level:"block",start(h){var f;const p=new RegExp(`^:::${u}`,"m"),x=(f=h.match(p))==null?void 0:f.index;return x!==void 0?x:-1},tokenize(h,f,p){var x;const v=new RegExp(`^:::${u}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),g=h.match(v);if(!g)return;const[y,_=""]=g,N=a(_);let k=1;const A=y.length;let M="";const C=/^:::([\w-]*)(\s.*)?/gm,j=h.slice(A);for(C.lastIndex=0;;){const P=C.exec(j);if(P===null)break;const E=P.index,U=P[1];if(!((x=P[2])!=null&&x.endsWith(":::"))){if(U)k+=1;else if(k-=1,k===0){const L=j.slice(0,E);M=L.trim();const B=h.slice(0,A+E+P[0].length);let D=[];if(M)if(l==="block")for(D=p.blockTokens(L),D.forEach($=>{$.text&&(!$.tokens||$.tokens.length===0)&&($.tokens=p.inlineTokens($.text))});D.length>0;){const $=D[D.length-1];if($.type==="paragraph"&&(!$.text||$.text.trim()===""))D.pop();else break}else D=p.inlineTokens(M);return{type:e,raw:B,attributes:N,content:M,tokens:D}}}}}},renderMarkdown:(h,f)=>{const p=d(h.attrs||{}),x=s(p),v=x?` {${x}}`:"",g=f.renderChildren(h.content||[],`
  8229. `);return`:::${u}${v}
  8230. ${g}
  8231. :::`}}}function tWe(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,a,s,o]=r;e[a]=s||o,r=n.exec(t)}return e}function nWe(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function rWe(t){const{nodeName:e,name:n,getContent:r,parseAttributes:a=tWe,serializeAttributes:s=nWe,defaultAttributes:o={},selfClosing:l=!1,allowedAttributes:c}=t,u=n||e,d=f=>{if(!c)return f;const p={};return c.forEach(x=>{const v=typeof x=="string"?x:x.name,g=typeof x=="string"?void 0:x.skipIfDefault;if(v in f){const y=f[v];if(g!==void 0&&y===g)return;p[v]=y}}),p},h=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(f,p)=>{const x={...o,...f.attributes};if(l)return p.createNode(e,x);const v=r?r(f):f.content||"";return v?p.createNode(e,x,[p.createTextNode(v)]):p.createNode(e,x,[])},markdownTokenizer:{name:e,level:"inline",start(f){const p=l?new RegExp(`\\[${h}\\s*[^\\]]*\\]`):new RegExp(`\\[${h}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${h}\\]`),x=f.match(p),v=x?.index;return v!==void 0?v:-1},tokenize(f,p,x){const v=l?new RegExp(`^\\[${h}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${h}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${h}\\]`),g=f.match(v);if(!g)return;let y="",_="";if(l){const[,k]=g;_=k}else{const[,k,A]=g;_=k,y=A||""}const N=a(_.trim());return{type:e,raw:g[0],content:y.trim(),attributes:N}}},renderMarkdown:f=>{let p="";r?p=r(f):f.content&&f.content.length>0&&(p=f.content.filter(y=>y.type==="text").map(y=>y.text).join(""));const x=d(f.attrs||{}),v=s(x),g=v?` ${v}`:"";return l?`[${u}${g}]`:`[${u}${g}]${p}[/${u}]`}}}function zR(t,e,n){var r,a,s,o;const l=t.split(`
  8232. `),c=[];let u="",d=0;const h=e.baseIndentSize||2;for(;d<l.length;){const f=l[d],p=f.match(e.itemPattern);if(!p){if(c.length>0)break;if(f.trim()===""){d+=1,u=`${u}${f}
  8233. `;continue}else return}const x=e.extractItemData(p),{indentLevel:v,mainContent:g}=x;u=`${u}${f}
  8234. `;const y=[g];for(d+=1;d<l.length;){const A=l[d];if(A.trim()===""){const C=l.slice(d+1).findIndex(E=>E.trim()!=="");if(C===-1)break;if((((a=(r=l[d+1+C].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:a.length)||0)>v){y.push(A),u=`${u}${A}
  8235. `,d+=1;continue}else break}if((((o=(s=A.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:o.length)||0)>v)y.push(A),u=`${u}${A}
  8236. `,d+=1;else break}let _;const N=y.slice(1);if(N.length>0){const A=N.map(M=>M.slice(v+h)).join(`
  8237. `);A.trim()&&(e.customNestedParser?_=e.customNestedParser(A):_=n.blockTokens(A))}const k=e.createToken(x,_);c.push(k)}if(c.length!==0)return{items:c,raw:u}}function q4(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const a=typeof n=="function"?n(r):n,[s,...o]=t.content,l=e.renderChildren([s]),c=[`${a}${l}`];return o&&o.length>0&&o.forEach(u=>{const d=e.renderChildren([u]);if(d){const h=d.split(`
  8238. `).map(f=>f?e.indent(f):"").join(`
  8239. `);c.push(h)}}),c.join(`
  8240. `)}function aWe(t,e,n={}){const{state:r}=e,{doc:a,tr:s}=r,o=t;a.descendants((l,c)=>{const u=s.mapping.map(c),d=s.mapping.map(c)+l.nodeSize;let h=null;if(l.marks.forEach(p=>{if(p!==o)return!1;h=p}),!h)return;let f=!1;if(Object.keys(n).forEach(p=>{n[p]!==h.attrs[p]&&(f=!0)}),f){const p=t.type.create({...t.attrs,...n});s.removeMark(u,d,t.type),s.addMark(u,d,p)}}),s.docChanged&&e.view.dispatch(s)}var co=class Eae extends H4{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Eae(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function Jf(t){return new z9e({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:a})=>{const s=Cr(t.getAttributes,void 0,r,a);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],c=r[0];let u=n.to;if(l){const d=c.search(/\S/),h=n.from+c.indexOf(l),f=h+l.length;if(B4(n.from,n.to,e.doc).filter(x=>x.mark.type.excluded.find(g=>g===t.type&&g!==x.mark.type)).filter(x=>x.to>h).length)return null;f<n.to&&o.delete(f,n.to),h>n.from&&o.delete(n.from+d,h),u=n.from+d+l.length,o.addMark(n.from+d,u,t.type.create(s||{})),o.removeStoredMark(t.type)}}})}const{getOwnPropertyNames:iWe,getOwnPropertySymbols:sWe}=Object,{hasOwnProperty:oWe}=Object.prototype;function h2(t,e){return function(r,a,s){return t(r,a,s)&&e(r,a,s)}}function E_(t){return function(n,r,a){if(!n||!r||typeof n!="object"||typeof r!="object")return t(n,r,a);const{cache:s}=a,o=s.get(n),l=s.get(r);if(o&&l)return o===r&&l===n;s.set(n,r),s.set(r,n);const c=t(n,r,a);return s.delete(n),s.delete(r),c}}function lWe(t){return t?.[Symbol.toStringTag]}function xW(t){return iWe(t).concat(sWe(t))}const cWe=Object.hasOwn||((t,e)=>oWe.call(t,e));function op(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const uWe="__v",dWe="__o",hWe="_owner",{getOwnPropertyDescriptor:yW,keys:vW}=Object;function mWe(t,e){return t.byteLength===e.byteLength&&rC(new Uint8Array(t),new Uint8Array(e))}function fWe(t,e,n){let r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(!n.equals(t[r],e[r],r,r,t,e,n))return!1;return!0}function pWe(t,e){return t.byteLength===e.byteLength&&rC(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function gWe(t,e){return op(t.getTime(),e.getTime())}function bWe(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function xWe(t,e){return t===e}function wW(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const a=new Array(r),s=t.entries();let o,l,c=0;for(;(o=s.next())&&!o.done;){const u=e.entries();let d=!1,h=0;for(;(l=u.next())&&!l.done;){if(a[h]){h++;continue}const f=o.value,p=l.value;if(n.equals(f[0],p[0],c,h,t,e,n)&&n.equals(f[1],p[1],f[0],p[0],t,e,n)){d=a[h]=!0;break}h++}if(!d)return!1;c++}return!0}const yWe=op;function vWe(t,e,n){const r=vW(t);let a=r.length;if(vW(e).length!==a)return!1;for(;a-- >0;)if(!jae(t,e,n,r[a]))return!1;return!0}function Ny(t,e,n){const r=xW(t);let a=r.length;if(xW(e).length!==a)return!1;let s,o,l;for(;a-- >0;)if(s=r[a],!jae(t,e,n,s)||(o=yW(t,s),l=yW(e,s),(o||l)&&(!o||!l||o.configurable!==l.configurable||o.enumerable!==l.enumerable||o.writable!==l.writable)))return!1;return!0}function wWe(t,e){return op(t.valueOf(),e.valueOf())}function SWe(t,e){return t.source===e.source&&t.flags===e.flags}function SW(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const a=new Array(r),s=t.values();let o,l;for(;(o=s.next())&&!o.done;){const c=e.values();let u=!1,d=0;for(;(l=c.next())&&!l.done;){if(!a[d]&&n.equals(o.value,l.value,o.value,l.value,t,e,n)){u=a[d]=!0;break}d++}if(!u)return!1}return!0}function rC(t,e){let n=t.byteLength;if(e.byteLength!==n||t.byteOffset!==e.byteOffset)return!1;for(;n-- >0;)if(t[n]!==e[n])return!1;return!0}function _We(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function jae(t,e,n,r){return(r===hWe||r===dWe||r===uWe)&&(t.$$typeof||e.$$typeof)?!0:cWe(e,r)&&n.equals(t[r],e[r],r,r,t,e,n)}const NWe="[object ArrayBuffer]",CWe="[object Arguments]",kWe="[object Boolean]",AWe="[object DataView]",TWe="[object Date]",MWe="[object Error]",PWe="[object Map]",EWe="[object Number]",jWe="[object Object]",DWe="[object RegExp]",RWe="[object Set]",FWe="[object String]",LWe={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},OWe="[object URL]",IWe=Object.prototype.toString;function zWe({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:a,areFunctionsEqual:s,areMapsEqual:o,areNumbersEqual:l,areObjectsEqual:c,arePrimitiveWrappersEqual:u,areRegExpsEqual:d,areSetsEqual:h,areTypedArraysEqual:f,areUrlsEqual:p,unknownTagComparators:x}){return function(g,y,_){if(g===y)return!0;if(g==null||y==null)return!1;const N=typeof g;if(N!==typeof y)return!1;if(N!=="object")return N==="number"?l(g,y,_):N==="function"?s(g,y,_):!1;const k=g.constructor;if(k!==y.constructor)return!1;if(k===Object)return c(g,y,_);if(Array.isArray(g))return e(g,y,_);if(k===Date)return r(g,y,_);if(k===RegExp)return d(g,y,_);if(k===Map)return o(g,y,_);if(k===Set)return h(g,y,_);const A=IWe.call(g);if(A===TWe)return r(g,y,_);if(A===DWe)return d(g,y,_);if(A===PWe)return o(g,y,_);if(A===RWe)return h(g,y,_);if(A===jWe)return typeof g.then!="function"&&typeof y.then!="function"&&c(g,y,_);if(A===OWe)return p(g,y,_);if(A===MWe)return a(g,y,_);if(A===CWe)return c(g,y,_);if(LWe[A])return f(g,y,_);if(A===NWe)return t(g,y,_);if(A===AWe)return n(g,y,_);if(A===kWe||A===EWe||A===FWe)return u(g,y,_);if(x){let M=x[A];if(!M){const C=lWe(g);C&&(M=x[C])}if(M)return M(g,y,_)}return!1}}function UWe({circular:t,createCustomConfig:e,strict:n}){let r={areArrayBuffersEqual:mWe,areArraysEqual:n?Ny:fWe,areDataViewsEqual:pWe,areDatesEqual:gWe,areErrorsEqual:bWe,areFunctionsEqual:xWe,areMapsEqual:n?h2(wW,Ny):wW,areNumbersEqual:yWe,areObjectsEqual:n?Ny:vWe,arePrimitiveWrappersEqual:wWe,areRegExpsEqual:SWe,areSetsEqual:n?h2(SW,Ny):SW,areTypedArraysEqual:n?h2(rC,Ny):rC,areUrlsEqual:_We,unknownTagComparators:void 0};if(e&&(r=Object.assign({},r,e(r))),t){const a=E_(r.areArraysEqual),s=E_(r.areMapsEqual),o=E_(r.areObjectsEqual),l=E_(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:a,areMapsEqual:s,areObjectsEqual:o,areSetsEqual:l})}return r}function BWe(t){return function(e,n,r,a,s,o,l){return t(e,n,l)}}function HWe({circular:t,comparator:e,createState:n,equals:r,strict:a}){if(n)return function(l,c){const{cache:u=t?new WeakMap:void 0,meta:d}=n();return e(l,c,{cache:u,equals:r,meta:d,strict:a})};if(t)return function(l,c){return e(l,c,{cache:new WeakMap,equals:r,meta:void 0,strict:a})};const s={cache:void 0,equals:r,meta:void 0,strict:a};return function(l,c){return e(l,c,s)}}const $We=cm();cm({strict:!0});cm({circular:!0});cm({circular:!0,strict:!0});cm({createInternalComparator:()=>op});cm({strict:!0,createInternalComparator:()=>op});cm({circular:!0,createInternalComparator:()=>op});cm({circular:!0,createInternalComparator:()=>op,strict:!0});function cm(t={}){const{circular:e=!1,createInternalComparator:n,createState:r,strict:a=!1}=t,s=UWe(t),o=zWe(s),l=n?n(o):BWe(o);return HWe({circular:e,comparator:o,createState:r,equals:l,strict:a})}var VWe=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},qWe=({contentComponent:t})=>{const e=oF.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return i.jsx(i.Fragment,{children:Object.values(e)})};function GWe(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,r){e={...e,[n]:Gue.createPortal(r.reactElement,r.element,n)},t.forEach(a=>a())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(a=>a())}}}var WWe=class extends Hr.Component{constructor(t){var e;super(t),this.editorContentRef=Hr.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var t;const e=this.props.editor;if(e&&!e.isDestroyed&&((t=e.view.dom)!=null&&t.parentNode)){if(e.contentComponent)return;const n=this.editorContentRef.current;n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n}),e.contentComponent=GWe(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:VWe(e,this.editorContentRef),...n}),t?.contentComponent&&i.jsx(qWe,{contentComponent:t.contentComponent})]})}},KWe=w.forwardRef((t,e)=>{const n=Hr.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return Hr.createElement(WWe,{key:n,innerRef:e,...t})}),Dae=Hr.memo(KWe),XWe=typeof window<"u"?w.useLayoutEffect:w.useEffect,YWe=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(r=>r())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function QWe(t){var e;const[n]=w.useState(()=>new YWe(t.editor)),r=FQ.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:$We);return XWe(()=>n.watch(t.editor),[t.editor,n]),w.useDebugValue(r),r}var ZWe=!1,UR=typeof window>"u",JWe=UR||!!(typeof window<"u"&&window.next),eKe=class Rae{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?UR||JWe?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...r)=>{var a,s;return(s=(a=this.options.current).onBeforeCreate)==null?void 0:s.call(a,...r)},onBlur:(...r)=>{var a,s;return(s=(a=this.options.current).onBlur)==null?void 0:s.call(a,...r)},onCreate:(...r)=>{var a,s;return(s=(a=this.options.current).onCreate)==null?void 0:s.call(a,...r)},onDestroy:(...r)=>{var a,s;return(s=(a=this.options.current).onDestroy)==null?void 0:s.call(a,...r)},onFocus:(...r)=>{var a,s;return(s=(a=this.options.current).onFocus)==null?void 0:s.call(a,...r)},onSelectionUpdate:(...r)=>{var a,s;return(s=(a=this.options.current).onSelectionUpdate)==null?void 0:s.call(a,...r)},onTransaction:(...r)=>{var a,s;return(s=(a=this.options.current).onTransaction)==null?void 0:s.call(a,...r)},onUpdate:(...r)=>{var a,s;return(s=(a=this.options.current).onUpdate)==null?void 0:s.call(a,...r)},onContentError:(...r)=>{var a,s;return(s=(a=this.options.current).onContentError)==null?void 0:s.call(a,...r)},onDrop:(...r)=>{var a,s;return(s=(a=this.options.current).onDrop)==null?void 0:s.call(a,...r)},onPaste:(...r)=>{var a,s;return(s=(a=this.options.current).onPaste)==null?void 0:s.call(a,...r)},onDelete:(...r)=>{var a,s;return(s=(a=this.options.current).onDelete)==null?void 0:s.call(a,...r)}};return new K9e(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((a,s)=>{var o;return a===((o=n.extensions)==null?void 0:o[s])}):e[r]===n[r])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?Rae.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((r,a)=>r===e[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function tKe(t={},e=[]){const n=w.useRef(t);n.current=t;const[r]=w.useState(()=>new eKe(n)),a=oF.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return w.useDebugValue(a),w.useEffect(r.onRender(e)),QWe({editor:a,selector:({transactionNumber:s})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&s===0?0:s+1}),a}var Fae=w.createContext({editor:null});Fae.Consumer;var nKe=w.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),rKe=()=>w.useContext(nKe);Hr.forwardRef((t,e)=>{const{onDragStart:n}=rKe(),r=t.as||"div";return i.jsx(r,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});Hr.createContext({markViewContentRef:()=>{}});var G4=w.createContext({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}});G4.displayName="TiptapContext";var aKe=()=>w.useContext(G4);function Lae({editor:t,instance:e,children:n}){const r=t??e;if(!r)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const a=w.useMemo(()=>({editor:r}),[r]),s=w.useMemo(()=>({editor:r}),[r]);return i.jsx(Fae.Provider,{value:s,children:i.jsx(G4.Provider,{value:a,children:n})})}Lae.displayName="Tiptap";function Oae({...t}){const{editor:e}=aKe();return i.jsx(Dae,{editor:e,...t})}Oae.displayName="Tiptap.Content";Object.assign(Lae,{Content:Oae});var aC=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},iKe=/^\s*>\s$/,sKe=co.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return aC("blockquote",{...Fa(this.options.HTMLAttributes,t),children:aC("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",r=[];return t.content.forEach(a=>{const l=e.renderChildren([a]).split(`
  8241. `).map(c=>c.trim()===""?n:`${n} ${c}`);r.push(l.join(`
  8242. `))}),r.join(`
  8243. ${n}
  8244. `)},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[Lb({find:iKe,type:this.type})]}}),oKe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,lKe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,cKe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,uKe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,dKe=lm.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return aC("strong",{...Fa(this.options.HTMLAttributes,t),children:aC("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Fb({find:oKe,type:this.type}),Fb({find:cKe,type:this.type})]},addPasteRules(){return[Jf({find:lKe,type:this.type}),Jf({find:uKe,type:this.type})]}}),hKe=/(^|[^`])`([^`]+)`(?!`)$/,mKe=/(^|[^`])`([^`]+)`(?!`)/g,fKe=lm.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",Fa(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Fb({find:hKe,type:this.type})]},addPasteRules(){return[Jf({find:mKe,type:this.type})]}}),m2=4,pKe=/^```([a-z]+)?[\s\n]$/,gKe=/^~~~([a-z]+)?[\s\n]$/,bKe=co.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:m2,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const s=[...((e=t.firstElementChild)==null?void 0:e.classList)||[]].filter(o=>o.startsWith(n)).map(o=>o.replace(n,""))[0];return s||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:e}){return["pre",Fa(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n;return((n=t.raw)==null?void 0:n.startsWith("```"))===!1&&t.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const a=((n=t.attrs)==null?void 0:n.language)||"";return t.content?r=[`\`\`\`${a}`,e.renderChildren(t.content),"```"].join(`
  8245. `):r=`\`\`\`${a}
  8246. \`\`\``,r},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=e.pos===1;return!t||e.parent.type.name!==this.name?!1:n||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:m2,{state:r}=t,{selection:a}=r,{$from:s,empty:o}=a;if(s.parent.type!==this.type)return!1;const l=" ".repeat(n);return o?t.commands.insertContent(l):t.commands.command(({tr:c})=>{const{from:u,to:d}=a,p=r.doc.textBetween(u,d,`
  8247. `,`
  8248. `).split(`
  8249. `).map(x=>l+x).join(`
  8250. `);return c.replaceWith(u,d,r.schema.text(p)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:m2,{state:r}=t,{selection:a}=r,{$from:s,empty:o}=a;return s.parent.type!==this.type?!1:o?t.commands.command(({tr:l})=>{var c;const{pos:u}=s,d=s.start(),h=s.end(),p=r.doc.textBetween(d,h,`
  8251. `,`
  8252. `).split(`
  8253. `);let x=0,v=0;const g=u-d;for(let M=0;M<p.length;M+=1){if(v+p[M].length>=g){x=M;break}v+=p[M].length+1}const _=((c=p[x].match(/^ */))==null?void 0:c[0])||"",N=Math.min(_.length,n);if(N===0)return!0;let k=d;for(let M=0;M<x;M+=1)k+=p[M].length+1;return l.delete(k,k+N),u-k<=N&&l.setSelection(wn.create(l.doc,k)),!0}):t.commands.command(({tr:l})=>{const{from:c,to:u}=a,f=r.doc.textBetween(c,u,`
  8254. `,`
  8255. `).split(`
  8256. `).map(p=>{var x;const v=((x=p.match(/^ */))==null?void 0:x[0])||"",g=Math.min(v.length,n);return p.slice(g)}).join(`
  8257. `);return l.replaceWith(c,u,r.schema.text(f)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const s=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
  8258. `);return!s||!o?!1:t.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:a,empty:s}=n;if(!s||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const l=a.after();return l===void 0?!1:r.nodeAt(l)?t.commands.command(({tr:u})=>(u.setSelection(Bn.near(r.resolve(l))),!0)):t.commands.exitCode()}}},addInputRules(){return[IR({find:pKe,type:this.type,getAttributes:t=>({language:t[1]})}),IR({find:gKe,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new ya({key:new Ni("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),a=r?JSON.parse(r):void 0,s=a?.mode;if(!n||!s)return!1;const{tr:o,schema:l}=t.state,c=l.text(n.replace(/\r\n?/g,`
  8259. `));return o.replaceSelectionWith(this.type.create({language:s},c)),o.selection.$from.parent.type!==this.type&&o.setSelection(wn.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),t.dispatch(o),!0}}})]}}),xKe=co.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8260. `):""}),yKe=co.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",Fa(this.options.HTMLAttributes,t)]},renderText(){return`
  8261. `},renderMarkdown:()=>`
  8262. `,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:a,storedMarks:s}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,c=s||a.$to.parentOffset&&a.$from.marks();return e().insertContent({type:this.name}).command(({tr:u,dispatch:d})=>{if(d&&c&&o){const h=c.filter(f=>l.includes(f.type.name));u.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),vKe=co.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,Fa(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,a="#".repeat(r);return t.content?`${a} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>IR({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),wKe=co.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",Fa(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!Q9e(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,a=t();return mae(n)?a.insertContentAt(r.pos,{type:this.name}):a.insertContent({type:this.name}),a.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:c}=o.selection,u=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?o.setSelection(wn.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(cn.create(o.doc,c.pos)):o.setSelection(wn.create(o.doc,c.pos));else{const d=s.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,h=d?.create();h&&(o.insert(u,h),o.setSelection(wn.create(o.doc,u+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Pae({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),SKe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,_Ke=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,NKe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,CKe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,kKe=lm.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Fa(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Fb({find:SKe,type:this.type}),Fb({find:NKe,type:this.type})]},addPasteRules(){return[Jf({find:_Ke,type:this.type}),Jf({find:CKe,type:this.type})]}});const AKe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",TKe="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",BR="numeric",HR="ascii",$R="alpha",nv="asciinumeric",Iy="alphanumeric",VR="domain",Iae="emoji",MKe="scheme",PKe="slashscheme",f2="whitespace";function EKe(t,e){return t in e||(e[t]=[]),e[t]}function df(t,e,n){e[BR]&&(e[nv]=!0,e[Iy]=!0),e[HR]&&(e[nv]=!0,e[$R]=!0),e[nv]&&(e[Iy]=!0),e[$R]&&(e[Iy]=!0),e[Iy]&&(e[VR]=!0),e[Iae]&&(e[VR]=!0);for(const r in e){const a=EKe(r,n);a.indexOf(t)<0&&a.push(t)}}function jKe(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}function Ys(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Ys.groups={};Ys.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;r<e.jr.length;r++){const a=e.jr[r][0],s=e.jr[r][1];if(s&&a.test(t))return s}return e.jd},has(t,e=!1){return e?t in this.j:!!this.go(t)},ta(t,e,n,r){for(let a=0;a<t.length;a++)this.tt(t[a],e,n,r)},tr(t,e,n,r){r=r||Ys.groups;let a;return e&&e.j?a=e:(a=new Ys(e),n&&r&&df(e,n,r)),this.jr.push([t,a]),a},ts(t,e,n,r){let a=this;const s=t.length;if(!s)return a;for(let o=0;o<s-1;o++)a=a.tt(t[o]);return a.tt(t[s-1],e,n,r)},tt(t,e,n,r){r=r||Ys.groups;const a=this;if(e&&e.j)return a.j[t]=e,e;const s=e;let o,l=a.go(t);if(l?(o=new Ys,Object.assign(o.j,l.j),o.jr.push.apply(o.jr,l.jr),o.jd=l.jd,o.t=l.t):o=new Ys,s){if(r)if(o.t&&typeof o.t=="string"){const c=Object.assign(jKe(o.t,r),n);df(s,c,r)}else n&&df(s,n,r);o.t=s}return a.j[t]=o,o}};const Fn=(t,e,n,r,a)=>t.ta(e,n,r,a),Ca=(t,e,n,r,a)=>t.tr(e,n,r,a),_W=(t,e,n,r,a)=>t.ts(e,n,r,a),jt=(t,e,n,r,a)=>t.tt(e,n,r,a),Pu="WORD",qR="UWORD",zae="ASCIINUMERICAL",Uae="ALPHANUMERICAL",t0="LOCALHOST",GR="TLD",WR="UTLD",u1="SCHEME",Lg="SLASH_SCHEME",W4="NUM",KR="WS",K4="NL",rv="OPENBRACE",av="CLOSEBRACE",iC="OPENBRACKET",sC="CLOSEBRACKET",oC="OPENPAREN",lC="CLOSEPAREN",cC="OPENANGLEBRACKET",uC="CLOSEANGLEBRACKET",dC="FULLWIDTHLEFTPAREN",hC="FULLWIDTHRIGHTPAREN",mC="LEFTCORNERBRACKET",fC="RIGHTCORNERBRACKET",pC="LEFTWHITECORNERBRACKET",gC="RIGHTWHITECORNERBRACKET",bC="FULLWIDTHLESSTHAN",xC="FULLWIDTHGREATERTHAN",yC="AMPERSAND",vC="APOSTROPHE",wC="ASTERISK",uh="AT",SC="BACKSLASH",_C="BACKTICK",NC="CARET",bh="COLON",X4="COMMA",CC="DOLLAR",xc="DOT",kC="EQUALS",Y4="EXCLAMATION",el="HYPHEN",iv="PERCENT",AC="PIPE",TC="PLUS",MC="POUND",sv="QUERY",Q4="QUOTE",Bae="FULLWIDTHMIDDLEDOT",Z4="SEMI",yc="SLASH",ov="TILDE",PC="UNDERSCORE",Hae="EMOJI",EC="SYM";var $ae=Object.freeze({__proto__:null,ALPHANUMERICAL:Uae,AMPERSAND:yC,APOSTROPHE:vC,ASCIINUMERICAL:zae,ASTERISK:wC,AT:uh,BACKSLASH:SC,BACKTICK:_C,CARET:NC,CLOSEANGLEBRACKET:uC,CLOSEBRACE:av,CLOSEBRACKET:sC,CLOSEPAREN:lC,COLON:bh,COMMA:X4,DOLLAR:CC,DOT:xc,EMOJI:Hae,EQUALS:kC,EXCLAMATION:Y4,FULLWIDTHGREATERTHAN:xC,FULLWIDTHLEFTPAREN:dC,FULLWIDTHLESSTHAN:bC,FULLWIDTHMIDDLEDOT:Bae,FULLWIDTHRIGHTPAREN:hC,HYPHEN:el,LEFTCORNERBRACKET:mC,LEFTWHITECORNERBRACKET:pC,LOCALHOST:t0,NL:K4,NUM:W4,OPENANGLEBRACKET:cC,OPENBRACE:rv,OPENBRACKET:iC,OPENPAREN:oC,PERCENT:iv,PIPE:AC,PLUS:TC,POUND:MC,QUERY:sv,QUOTE:Q4,RIGHTCORNERBRACKET:fC,RIGHTWHITECORNERBRACKET:gC,SCHEME:u1,SEMI:Z4,SLASH:yc,SLASH_SCHEME:Lg,SYM:EC,TILDE:ov,TLD:GR,UNDERSCORE:PC,UTLD:WR,UWORD:qR,WORD:Pu,WS:KR});const Cu=/[a-z]/,Cy=new RegExp("\\p{L}","u"),p2=new RegExp("\\p{Emoji}","u"),ku=/\d/,g2=/\s/,NW="\r",b2=`
  8263. `,DKe="️",RKe="‍",x2="";let j_=null,D_=null;function FKe(t=[]){const e={};Ys.groups=e;const n=new Ys;j_==null&&(j_=CW(AKe)),D_==null&&(D_=CW(TKe)),jt(n,"'",vC),jt(n,"{",rv),jt(n,"}",av),jt(n,"[",iC),jt(n,"]",sC),jt(n,"(",oC),jt(n,")",lC),jt(n,"<",cC),jt(n,">",uC),jt(n,"(",dC),jt(n,")",hC),jt(n,"「",mC),jt(n,"」",fC),jt(n,"『",pC),jt(n,"』",gC),jt(n,"<",bC),jt(n,">",xC),jt(n,"&",yC),jt(n,"*",wC),jt(n,"@",uh),jt(n,"`",_C),jt(n,"^",NC),jt(n,":",bh),jt(n,",",X4),jt(n,"$",CC),jt(n,".",xc),jt(n,"=",kC),jt(n,"!",Y4),jt(n,"-",el),jt(n,"%",iv),jt(n,"|",AC),jt(n,"+",TC),jt(n,"#",MC),jt(n,"?",sv),jt(n,'"',Q4),jt(n,"/",yc),jt(n,";",Z4),jt(n,"~",ov),jt(n,"_",PC),jt(n,"\\",SC),jt(n,"・",Bae);const r=Ca(n,ku,W4,{[BR]:!0});Ca(r,ku,r);const a=Ca(r,Cu,zae,{[nv]:!0}),s=Ca(r,Cy,Uae,{[Iy]:!0}),o=Ca(n,Cu,Pu,{[HR]:!0});Ca(o,ku,a),Ca(o,Cu,o),Ca(a,ku,a),Ca(a,Cu,a);const l=Ca(n,Cy,qR,{[$R]:!0});Ca(l,Cu),Ca(l,ku,s),Ca(l,Cy,l),Ca(s,ku,s),Ca(s,Cu),Ca(s,Cy,s);const c=jt(n,b2,K4,{[f2]:!0}),u=jt(n,NW,KR,{[f2]:!0}),d=Ca(n,g2,KR,{[f2]:!0});jt(n,x2,d),jt(u,b2,c),jt(u,x2,d),Ca(u,g2,d),jt(d,NW),jt(d,b2),Ca(d,g2,d),jt(d,x2,d);const h=Ca(n,p2,Hae,{[Iae]:!0});jt(h,"#"),Ca(h,p2,h),jt(h,DKe,h);const f=jt(h,RKe);jt(f,"#"),Ca(f,p2,h);const p=[[Cu,o],[ku,a]],x=[[Cu,null],[Cy,l],[ku,s]];for(let v=0;v<j_.length;v++)nh(n,j_[v],GR,Pu,p);for(let v=0;v<D_.length;v++)nh(n,D_[v],WR,qR,x);df(GR,{tld:!0,ascii:!0},e),df(WR,{utld:!0,alpha:!0},e),nh(n,"file",u1,Pu,p),nh(n,"mailto",u1,Pu,p),nh(n,"http",Lg,Pu,p),nh(n,"https",Lg,Pu,p),nh(n,"ftp",Lg,Pu,p),nh(n,"ftps",Lg,Pu,p),df(u1,{scheme:!0,ascii:!0},e),df(Lg,{slashscheme:!0,ascii:!0},e),t=t.sort((v,g)=>v[0]>g[0]?1:-1);for(let v=0;v<t.length;v++){const g=t[v][0],_=t[v][1]?{[MKe]:!0}:{[PKe]:!0};g.indexOf("-")>=0?_[VR]=!0:Cu.test(g)?ku.test(g)?_[nv]=!0:_[HR]=!0:_[BR]=!0,_W(n,g,g,_)}return _W(n,"localhost",t0,{ascii:!0}),n.jd=new Ys(EC),{start:n,tokens:Object.assign({groups:e},$ae)}}function Vae(t,e){const n=LKe(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=n.length,a=[];let s=0,o=0;for(;o<r;){let l=t,c=null,u=0,d=null,h=-1,f=-1;for(;o<r&&(c=l.go(n[o]));)l=c,l.accepts()?(h=0,f=0,d=l):h>=0&&(h+=n[o].length,f++),u+=n[o].length,s+=n[o].length,o++;s-=h,o-=f,u-=h,a.push({t:d.t,v:e.slice(s-u,s),s:s-u,e:s})}return a}function LKe(t){const e=[],n=t.length;let r=0;for(;r<n;){let a=t.charCodeAt(r),s,o=a<55296||a>56319||r+1===n||(s=t.charCodeAt(r+1))<56320||s>57343?t[r]:t.slice(r,r+2);e.push(o),r+=o.length}return e}function nh(t,e,n,r,a){let s;const o=e.length;for(let l=0;l<o-1;l++){const c=e[l];t.j[c]?s=t.j[c]:(s=new Ys(r),s.jr=a.slice(),t.j[c]=s),t=s}return s=new Ys(n),s.jr=a.slice(),t.j[e[o-1]]=s,s}function CW(t){const e=[],n=[];let r=0,a="0123456789";for(;r<t.length;){let s=0;for(;a.indexOf(t[r+s])>=0;)s++;if(s>0){e.push(n.join(""));for(let o=parseInt(t.substring(r,r+s),10);o>0;o--)n.pop();r+=s}else n.push(t[r]),r++}return e}const n0={defaultProtocol:"http",events:null,format:kW,formatHref:kW,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function J4(t,e=null){let n=Object.assign({},n0);t&&(n=Object.assign(n,t instanceof J4?t.o:t));const r=n.ignoreTags,a=[];for(let s=0;s<r.length;s++)a.push(r[s].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=a}J4.prototype={o:n0,ignoreTags:[],defaultRender(t){return t},check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const r=e!=null;let a=this.o[t];return a&&(typeof a=="object"?(a=n.t in a?a[n.t]:n0[t],typeof a=="function"&&r&&(a=a(e,n))):typeof a=="function"&&r&&(a=a(e,n.t,n)),a)},getObj(t,e,n){let r=this.o[t];return typeof r=="function"&&e!=null&&(r=r(e,n.t,n)),r},render(t){const e=t.render(this);return(this.get("render",null,t)||this.defaultRender)(e,t.t,t)}};function kW(t){return t}function qae(t,e){this.t="token",this.v=t,this.tk=e}qae.prototype={isLink:!1,toString(){return this.v},toHref(t){return this.toString()},toFormattedString(t){const e=this.toString(),n=t.get("truncate",e,this),r=t.get("format",e,this);return n&&r.length>n?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=n0.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),a=t.get("tagName",n,e),s=this.toFormattedString(t),o={},l=t.get("className",n,e),c=t.get("target",n,e),u=t.get("rel",n,e),d=t.getObj("attributes",n,e),h=t.getObj("events",n,e);return o.href=r,l&&(o.class=l),c&&(o.target=c),u&&(o.rel=u),d&&Object.assign(o,d),{tagName:a,attributes:o,content:s,eventListeners:h}}};function SA(t,e){class n extends qae{constructor(a,s){super(a,s),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}const AW=SA("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),TW=SA("text"),OKe=SA("nl"),R_=SA("url",{isLink:!0,toHref(t=n0.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==t0&&t[1].t===bh}}),Qo=t=>new Ys(t);function IKe({groups:t}){const e=t.domain.concat([yC,wC,uh,SC,_C,NC,CC,kC,el,W4,iv,AC,TC,MC,yc,EC,ov,PC]),n=[vC,bh,X4,xc,Y4,iv,sv,Q4,Z4,cC,uC,rv,av,sC,iC,oC,lC,dC,hC,mC,fC,pC,gC,bC,xC],r=[yC,vC,wC,SC,_C,NC,CC,kC,el,rv,av,iv,AC,TC,MC,sv,yc,EC,ov,PC],a=Qo(),s=jt(a,ov);Fn(s,r,s),Fn(s,t.domain,s);const o=Qo(),l=Qo(),c=Qo();Fn(a,t.domain,o),Fn(a,t.scheme,l),Fn(a,t.slashscheme,c),Fn(o,r,s),Fn(o,t.domain,o);const u=jt(o,uh);jt(s,uh,u),jt(l,uh,u),jt(c,uh,u);const d=jt(s,xc);Fn(d,r,s),Fn(d,t.domain,s);const h=Qo();Fn(u,t.domain,h),Fn(h,t.domain,h);const f=jt(h,xc);Fn(f,t.domain,h);const p=Qo(AW);Fn(f,t.tld,p),Fn(f,t.utld,p),jt(u,t0,p);const x=jt(h,el);jt(x,el,x),Fn(x,t.domain,h),Fn(p,t.domain,h),jt(p,xc,f),jt(p,el,x);const v=jt(p,bh);Fn(v,t.numeric,AW);const g=jt(o,el),y=jt(o,xc);jt(g,el,g),Fn(g,t.domain,o),Fn(y,r,s),Fn(y,t.domain,o);const _=Qo(R_);Fn(y,t.tld,_),Fn(y,t.utld,_),Fn(_,t.domain,o),Fn(_,r,s),jt(_,xc,y),jt(_,el,g),jt(_,uh,u);const N=jt(_,bh),k=Qo(R_);Fn(N,t.numeric,k);const A=Qo(R_),M=Qo();Fn(A,e,A),Fn(A,n,M),Fn(M,e,A),Fn(M,n,M),jt(_,yc,A),jt(k,yc,A);const C=jt(l,bh),j=jt(c,bh),P=jt(j,yc),E=jt(P,yc);Fn(l,t.domain,o),jt(l,xc,y),jt(l,el,g),Fn(c,t.domain,o),jt(c,xc,y),jt(c,el,g),Fn(C,t.domain,A),jt(C,yc,A),jt(C,sv,A),Fn(E,t.domain,A),Fn(E,e,A),jt(E,yc,A);const U=[[rv,av],[iC,sC],[oC,lC],[cC,uC],[dC,hC],[mC,fC],[pC,gC],[bC,xC]];for(let L=0;L<U.length;L++){const[B,D]=U[L],$=jt(A,B);jt(M,B,$),jt($,D,A);const G=Qo(R_);Fn($,e,G);const z=Qo();Fn($,n),Fn(G,e,G),Fn(G,n,z),Fn(z,e,G),Fn(z,n,z),jt(G,D,A),jt(z,D,A)}return jt(a,t0,_),jt(a,K4,OKe),{start:a,tokens:$ae}}function zKe(t,e,n){let r=n.length,a=0,s=[],o=[];for(;a<r;){let l=t,c=null,u=null,d=0,h=null,f=-1;for(;a<r&&!(c=l.go(n[a].t));)o.push(n[a++]);for(;a<r&&(u=c||l.go(n[a].t));)c=null,l=u,l.accepts()?(f=0,h=l):f>=0&&f++,a++,d++;if(f<0)a-=d,a<r&&(o.push(n[a]),a++);else{o.length>0&&(s.push(y2(TW,e,o)),o=[]),a-=f,d-=f;const p=h.t,x=n.slice(a-d,a);s.push(y2(p,e,x))}}return o.length>0&&s.push(y2(TW,e,o)),s}function y2(t,e,n){const r=n[0].s,a=n[n.length-1].e,s=e.slice(r,a);return new t(s,n)}const UKe=typeof console<"u"&&console&&console.warn||(()=>{}),BKe="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",ta={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function HKe(){return Ys.groups={},ta.scanner=null,ta.parser=null,ta.tokenQueue=[],ta.pluginQueue=[],ta.customSchemes=[],ta.initialized=!1,ta}function MW(t,e=!1){if(ta.initialized&&UKe(`linkifyjs: already initialized - will not register custom scheme "${t}" ${BKe}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format.
  8264. 1. Must only contain digits, lowercase ASCII letters or "-"
  8265. 2. Cannot start or end with "-"
  8266. 3. "-" cannot repeat`);ta.customSchemes.push([t,e])}function $Ke(){ta.scanner=FKe(ta.customSchemes);for(let t=0;t<ta.tokenQueue.length;t++)ta.tokenQueue[t][1]({scanner:ta.scanner});ta.parser=IKe(ta.scanner.tokens);for(let t=0;t<ta.pluginQueue.length;t++)ta.pluginQueue[t][1]({scanner:ta.scanner,parser:ta.parser});return ta.initialized=!0,ta}function eI(t){return ta.initialized||$Ke(),zKe(ta.parser.start,t,Vae(ta.scanner.start,t))}eI.scan=Vae;function Gae(t,e=null,n=null){if(e&&typeof e=="object"){if(n)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);n=e,e=null}const r=new J4(n),a=eI(t),s=[];for(let o=0;o<a.length;o++){const l=a[o];l.isLink&&(!e||l.t===e)&&r.check(l)&&s.push(l.toFormattedObject(r))}return s}var tI="[\0-   ᠎ -\u2029  ]",VKe=new RegExp(tI),qKe=new RegExp(`${tI}$`),GKe=new RegExp(tI,"g");function WKe(t){return t.length===1?t[0].isLink:t.length===3&&t[1].isLink?["()","[]"].includes(t[0].value+t[2].value):!1}function KKe(t){return new ya({key:new Ni("autolink"),appendTransaction:(e,n,r)=>{const a=e.some(u=>u.docChanged)&&!n.doc.eq(r.doc),s=e.some(u=>u.getMeta("preventAutolink"));if(!a||s)return;const{tr:o}=r,l=iae(n.doc,[...e]);if(hae(l).forEach(({newRange:u})=>{const d=Y7e(r.doc,u,p=>p.isTextblock);let h,f;if(d.length>1)h=d[0],f=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(d.length){const p=r.doc.textBetween(u.from,u.to," "," ");if(!qKe.test(p))return;h=d[0],f=r.doc.textBetween(h.pos,u.to,void 0," ")}if(h&&f){const p=f.split(VKe).filter(Boolean);if(p.length<=0)return!1;const x=p[p.length-1],v=h.pos+f.lastIndexOf(x);if(!x)return!1;const g=eI(x).map(y=>y.toObject(t.defaultProtocol));if(!WKe(g))return!1;g.filter(y=>y.isLink).map(y=>({...y,from:v+y.start+1,to:v+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>t.validate(y.value)).filter(y=>t.shouldAutoLink(y.value)).forEach(y=>{B4(y.from,y.to,r.doc).some(_=>_.mark.type===t.type)||o.addMark(y.from,y.to,t.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function XKe(t){return new ya({key:new Ni("handleClickLink"),props:{handleClick:(e,n,r)=>{var a,s;if(r.button!==0||!e.editable)return!1;let o=null;if(r.target instanceof HTMLAnchorElement)o=r.target;else{const c=r.target;if(!c)return!1;const u=t.editor.view.dom;o=c.closest("a"),o&&!u.contains(o)&&(o=null)}if(!o)return!1;let l=!1;if(t.enableClickSelection&&(l=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const c=dae(e.state,t.type.name),u=(a=o.href)!=null?a:c.href,d=(s=o.target)!=null?s:c.target;u&&(window.open(u,d),l=!0)}return l}}})}function YKe(t){return new ya({key:new Ni("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:a}=t,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let c="";r.content.forEach(d=>{c+=d.textContent});const u=Gae(c,{defaultProtocol:t.defaultProtocol}).find(d=>d.isLink&&d.value===c);return!c||!u||a!==void 0&&!a(u.value)?!1:t.editor.commands.setMark(t.type,{href:u.href})}}})}function Im(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const a=typeof r=="string"?r:r.scheme;a&&n.push(a)}),!t||t.replace(GKe,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var Wae=lm.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){MW(t);return}MW(t.scheme,t.optionalSlashes)})},onDestroy(){HKe()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Im(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(t),n=/^[a-z][a-z0-9+.-]*:/i.test(t);if(e||n&&!t.includes("@"))return!0;const a=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(a)||!/\./.test(a))}}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:n=>!!Im(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!Im(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Fa(this.options.HTMLAttributes,t),0]:["a",Fa(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n,r,a,s;const o=(r=(n=t.attrs)==null?void 0:n.href)!=null?r:"",l=(s=(a=t.attrs)==null?void 0:a.title)!=null?s:"",c=e.renderChildren(t);return l?`[${c}](${o} "${l}")`:`[${c}](${o})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:r=>!!Im(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:r=>!!Im(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[Jf({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,a=Gae(t).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!Im(o,n),protocols:n,defaultProtocol:r}));a.length&&a.forEach(s=>{this.options.shouldAutoLink(s.value)&&e.push({text:s.value,data:{href:s.href},index:s.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push(KKe({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!Im(a,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(XKe({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(YKe({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),QKe=Wae,ZKe=Object.defineProperty,JKe=(t,e)=>{for(var n in e)ZKe(t,n,{get:e[n],enumerable:!0})},eXe="listItem",PW="textStyle",EW=/^\s*([-+*])\s$/,Kae=co.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",Fa(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>t.type!=="list"||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8267. `):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(eXe,this.editor.getAttributes(PW)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=Lb({find:EW,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Lb({find:EW,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(PW),editor:this.editor})),[t]}}),Xae=co.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",Fa(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{if(t.type!=="list_item")return[];let n=[];if(t.tokens&&t.tokens.length>0)if(t.tokens.some(a=>a.type==="paragraph"))n=e.parseChildren(t.tokens);else{const a=t.tokens[0];if(a&&a.type==="text"&&a.tokens&&a.tokens.length>0){if(n=[{type:"paragraph",content:e.parseInline(a.tokens)}],t.tokens.length>1){const o=t.tokens.slice(1),l=e.parseChildren(o);n.push(...l)}}else n=e.parseChildren(t.tokens)}return n.length===0&&(n=[{type:"paragraph",content:[]}]),{type:"listItem",content:n}},renderMarkdown:(t,e,n)=>q4(t,e,r=>{var a,s;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((s=(a=r.meta)==null?void 0:a.parentAttrs)==null?void 0:s.start)||1)+r.index}. `:"- "},n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),tXe={};JKe(tXe,{findListItemPos:()=>G0,getNextListDepth:()=>nI,handleBackspace:()=>XR,handleDelete:()=>YR,hasListBefore:()=>Yae,hasListItemAfter:()=>nXe,hasListItemBefore:()=>Qae,listItemHasSubList:()=>Zae,nextListIsDeeper:()=>Jae,nextListIsHigher:()=>eie});var G0=(t,e)=>{const{$from:n}=e.selection,r=ii(t,e.schema);let a=null,s=n.depth,o=n.pos,l=null;for(;s>0&&l===null;)a=n.node(s),a.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},nI=(t,e)=>{const n=G0(t,e);if(!n)return!1;const[,r]=s9e(e,t,n.$pos.pos+4);return r},Yae=(t,e,n)=>{const{$anchor:r}=t.selection,a=Math.max(0,r.pos-2),s=t.doc.resolve(a).node();return!(!s||!n.includes(s.type.name))},Qae=(t,e)=>{var n;const{$anchor:r}=e.selection,a=e.doc.resolve(r.pos-2);return!(a.index()===0||((n=a.nodeBefore)==null?void 0:n.type.name)!==t)},Zae=(t,e,n)=>{if(!n)return!1;const r=ii(t,e.schema);let a=!1;return n.descendants(s=>{s.type===r&&(a=!0)}),a},XR=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!Jh(t.state,e)&&Yae(t.state,e,n)){const{$anchor:l}=t.state.selection,c=t.state.doc.resolve(l.before()-1),u=[];c.node().descendants((f,p)=>{f.type.name===e&&u.push({node:f,pos:p})});const d=u.at(-1);if(!d)return!1;const h=t.state.doc.resolve(c.start()+d.pos+1);return t.chain().cut({from:l.start()-1,to:l.end()+1},h.end()).joinForward().run()}if(!Jh(t.state,e)||!u9e(t.state))return!1;const r=G0(e,t.state);if(!r)return!1;const s=t.state.doc.resolve(r.$pos.pos-2).node(r.depth),o=Zae(e,t.state,s);return Qae(e,t.state)&&!o?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},Jae=(t,e)=>{const n=nI(t,e),r=G0(t,e);return!r||!n?!1:n>r.depth},eie=(t,e)=>{const n=nI(t,e),r=G0(t,e);return!r||!n?!1:n<r.depth},YR=(t,e)=>{if(!Jh(t.state,e)||!c9e(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:a}=n;return!n.empty&&r.sameParent(a)?!1:Jae(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():eie(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},nXe=(t,e)=>{var n;const{$anchor:r}=e.selection,a=e.doc.resolve(r.pos-r.parentOffset-2);return!(a.index()===a.parent.childCount-1||((n=a.nodeAfter)==null?void 0:n.type.name)!==t)},tie=zr.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&YR(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&YR(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&XR(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{t.state.schema.nodes[n]!==void 0&&XR(t,n,r)&&(e=!0)}),e}}}}),jW=/^(\s*)(\d+)\.\s+(.*)$/,rXe=/^\s/;function aXe(t){const e=[];let n=0,r=0;for(;n<t.length;){const a=t[n],s=a.match(jW);if(!s)break;const[,o,l,c]=s,u=o.length;let d=c,h=n+1;const f=[a];for(;h<t.length;){const p=t[h];if(p.match(jW))break;if(p.trim()==="")f.push(p),d+=`
  8268. `,h+=1;else if(p.match(rXe))f.push(p),d+=`
  8269. ${p.slice(u+2)}`,h+=1;else break}e.push({indent:u,number:parseInt(l,10),content:d.trim(),raw:f.join(`
  8270. `)}),r=h,n=h}return[e,r]}function nie(t,e,n){var r;const a=[];let s=0;for(;s<t.length;){const o=t[s];if(o.indent===e){const l=o.content.split(`
  8271. `),c=((r=l[0])==null?void 0:r.trim())||"",u=[];c&&u.push({type:"paragraph",raw:c,tokens:n.inlineTokens(c)});const d=l.slice(1).join(`
  8272. `).trim();if(d){const p=n.blockTokens(d);u.push(...p)}let h=s+1;const f=[];for(;h<t.length&&t[h].indent>e;)f.push(t[h]),h+=1;if(f.length>0){const p=Math.min(...f.map(v=>v.indent)),x=nie(f,p,n);u.push({type:"list",ordered:!0,start:f[0].number,items:x,raw:f.map(v=>v.raw).join(`
  8273. `)})}a.push({type:"list_item",raw:o.raw,tokens:u}),s=h}else s+=1}return a}function iXe(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const r=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(a=>{if(a.type==="paragraph"||a.type==="list"||a.type==="blockquote"||a.type==="code")r.push(...e.parseChildren([a]));else if(a.type==="text"&&a.tokens){const s=e.parseChildren([a]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([a]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}var sXe="listItem",DW="textStyle",RW=/^(\d+)\.\s$/,rie=co.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>t.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:t}){const{start:e,...n}=t;return e===1?["ol",Fa(this.options.HTMLAttributes,n),0]:["ol",Fa(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,r=t.items?iXe(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:r}:{type:"orderedList",content:r}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8274. `):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(/^(\s*)(\d+)\.\s+/),n=e?.index;return n!==void 0?n:-1},tokenize:(t,e,n)=>{var r;const a=t.split(`
  8275. `),[s,o]=aXe(a);if(s.length===0)return;const l=nie(s,0,n);return l.length===0?void 0:{type:"list",ordered:!0,start:((r=s[0])==null?void 0:r.number)||1,items:l,raw:a.slice(0,o).join(`
  8276. `)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(sXe,this.editor.getAttributes(DW)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=Lb({find:RW,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Lb({find:RW,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(DW)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),oXe=/^\s*(\[([( |x])?\])\s$/,lXe=co.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return e===""||e==="true"},renderHTML:t=>({"data-checked":t.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",Fa(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const a=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return q4(t,e,a)},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const a=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),c=document.createElement("div"),u=h=>{var f,p;l.ariaLabel=((p=(f=this.options.a11y)==null?void 0:f.checkboxLabel)==null?void 0:p.call(f,h,l.checked))||`Task item checkbox for ${h.textContent||"empty task item"}`};u(t),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",h=>h.preventDefault()),l.addEventListener("change",h=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:f}=h.target;r.isEditable&&typeof n=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:p})=>{const x=n();if(typeof x!="number")return!1;const v=p.doc.nodeAt(x);return p.setNodeMarkup(x,void 0,{...v?.attrs,checked:f}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,f)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([h,f])=>{a.setAttribute(h,f)}),a.dataset.checked=t.attrs.checked,l.checked=t.attrs.checked,s.append(l,o),a.append(s,c),Object.entries(e).forEach(([h,f])=>{a.setAttribute(h,f)});let d=new Set(Object.keys(e));return{dom:a,contentDOM:c,update:h=>{if(h.type!==this.type)return!1;a.dataset.checked=h.attrs.checked,l.checked=h.attrs.checked,u(h);const f=r.extensionManager.attributes,p=e0(h,f),x=new Set(Object.keys(p)),v=this.options.HTMLAttributes;return d.forEach(g=>{x.has(g)||(g in v?a.setAttribute(g,v[g]):a.removeAttribute(g))}),Object.entries(p).forEach(([g,y])=>{y==null?g in v?a.setAttribute(g,v[g]):a.removeAttribute(g):a.setAttribute(g,y)}),d=x,!0}}}},addInputRules(){return[Lb({find:oXe,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),cXe=co.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",Fa(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
  8277. `):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return n!==void 0?n:-1},tokenize(t,e,n){const r=s=>{const o=zR(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,c)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:n.inlineTokens(l.mainContent),nestedTokens:c}),customNestedParser:r},n);return o?[{type:"taskList",raw:o.raw,items:o.items}]:n.blockTokens(s)},a=zR(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:n.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},n);if(a)return{type:"taskList",raw:a.raw,items:a.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});zr.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(Kae.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(Xae.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(tie.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(rie.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(lXe.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(cXe.configure(this.options.taskList)),t}});var FW="&nbsp;",uXe=" ",dXe=co.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Fa(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(n.length===1&&n[0].type==="image")return e.parseChildren([n[0]]);const r=e.parseInline(n);return r.length===1&&r[0].type==="text"&&(r[0].text===FW||r[0].text===uXe)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(t,e)=>{if(!t)return"";const n=Array.isArray(t.content)?t.content:[];return n.length===0?FW:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),hXe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,mXe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,fXe=lm.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["s",Fa(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Fb({find:hXe,type:this.type})]},addPasteRules(){return[Jf({find:mXe,type:this.type})]}}),pXe=co.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),aie=lm.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",Fa(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const a=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!a)return;const s=a[2].trim();return{type:"underline",raw:a[0],text:s,tokens:n.inlineTokens(s)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),gXe=aie;function bXe(t={}){return new ya({view(e){return new xXe(e,t)}})}class xXe{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let s=o=>{this[a](o)};return e.dom.addEventListener(a,s),{name:a,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,a=this.editorView.dom,s=a.getBoundingClientRect(),o=s.width/a.offsetWidth,l=s.height/a.offsetHeight;if(n){let h=e.nodeBefore,f=e.nodeAfter;if(h||f){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let x=p.getBoundingClientRect(),v=h?x.bottom:x.top;h&&f&&(v=(v+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:x.left,right:x.right,top:v-g,bottom:v+g}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*o;r={left:h.left-f,right:h.left+f,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let u,d;if(!c||c==document.body&&getComputedStyle(c).position=="static")u=-pageXOffset,d=-pageYOffset;else{let h=c.getBoundingClientRect(),f=h.width/c.offsetWidth,p=h.height/c.offsetHeight;u=h.left-c.scrollLeft*f,d=h.top-c.scrollTop*p}this.element.style.left=(r.left-u)/o+"px",this.element.style.top=(r.top-d)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,s=typeof a=="function"?a(this.editorView,n,e):a;if(n&&!s){let o=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=Yne(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}this.setCursor(o),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class Pa extends Bn{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return Pa.valid(r)?new Pa(r):Bn.near(r)}content(){return Wt.empty}eq(e){return e instanceof Pa&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Pa(e.resolve(n.pos))}getBookmark(){return new rI(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!yXe(e)||!vXe(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let a=n.contentMatchAt(e.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&Pa.valid(e))return e;let a=e.pos,s=null;for(let o=e.depth;;o--){let l=e.node(o);if(n>0?e.indexAfter(o)<l.childCount:e.index(o)>0){s=l.child(n>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;a+=n;let c=e.doc.resolve(a);if(Pa.valid(c))return c}for(;;){let o=n>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!cn.isSelectable(s)){e=e.doc.resolve(a+s.nodeSize*n),r=!1;continue e}break}s=o,a+=n;let l=e.doc.resolve(a);if(Pa.valid(l))return l}return null}}}Pa.prototype.visible=!1;Pa.findFrom=Pa.findGapCursorFrom;Bn.jsonID("gapcursor",Pa);class rI{constructor(e){this.pos=e}map(e){return new rI(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return Pa.valid(n)?new Pa(n):Bn.near(n)}}function iie(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function yXe(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||iie(a.type))return!0;if(a.inlineContent)return!1}}return!0}function vXe(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||iie(a.type))return!0;if(a.inlineContent)return!1}}return!0}function wXe(){return new ya({props:{decorations:CXe,createSelectionBetween(t,e,n){return e.pos==n.pos&&Pa.valid(n)?new Pa(n):null},handleClick:_Xe,handleKeyDown:SXe,handleDOMEvents:{beforeinput:NXe}}})}const SXe=Qre({ArrowLeft:F_("horiz",-1),ArrowRight:F_("horiz",1),ArrowUp:F_("vert",-1),ArrowDown:F_("vert",1)});function F_(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,a,s){let o=r.selection,l=e>0?o.$to:o.$from,c=o.empty;if(o instanceof wn){if(!s.endOfTextblock(n)||l.depth==0)return!1;c=!1,l=r.doc.resolve(e>0?l.after():l.before())}let u=Pa.findGapCursorFrom(l,e,c);return u?(a&&a(r.tr.setSelection(new Pa(u))),!0):!1}}function _Xe(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!Pa.valid(r))return!1;let a=t.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&cn.isSelectable(t.state.doc.nodeAt(a.inside))?!1:(t.dispatch(t.state.tr.setSelection(new Pa(r))),!0)}function NXe(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof Pa))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let a=Mt.empty;for(let o=r.length-1;o>=0;o--)a=Mt.from(r[o].createAndFill(null,a));let s=t.state.tr.replace(n.pos,n.pos,new Wt(a,0,0));return s.setSelection(wn.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function CXe(t){if(!(t.selection instanceof Pa))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",pa.create(t.doc,[Es.widget(t.selection.head,e,{key:"gapcursor"})])}var jC=200,Li=function(){};Li.prototype.append=function(e){return e.length?(e=Li.from(e),!this.length&&e||e.length<jC&&this.leafAppend(e)||this.length<jC&&e.leafPrepend(this)||this.appendInner(e)):this};Li.prototype.prepend=function(e){return e.length?Li.from(e).append(this):this};Li.prototype.appendInner=function(e){return new kXe(this,e)};Li.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?Li.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};Li.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Li.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)};Li.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var a=[];return this.forEach(function(s,o){return a.push(e(s,o))},n,r),a};Li.from=function(e){return e instanceof Li?e:e&&e.length?new sie(e):Li.empty};var sie=(function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(a,s){return a==0&&s==this.length?this:new e(this.values.slice(a,s))},e.prototype.getInner=function(a){return this.values[a]},e.prototype.forEachInner=function(a,s,o,l){for(var c=s;c<o;c++)if(a(this.values[c],l+c)===!1)return!1},e.prototype.forEachInvertedInner=function(a,s,o,l){for(var c=s-1;c>=o;c--)if(a(this.values[c],l+c)===!1)return!1},e.prototype.leafAppend=function(a){if(this.length+a.length<=jC)return new e(this.values.concat(a.flatten()))},e.prototype.leafPrepend=function(a){if(this.length+a.length<=jC)return new e(a.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e})(Li);Li.empty=new sie([]);var kXe=(function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,a,s,o){var l=this.left.length;if(a<l&&this.left.forEachInner(r,a,Math.min(s,l),o)===!1||s>l&&this.right.forEachInner(r,Math.max(a-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,a,s,o){var l=this.left.length;if(a>l&&this.right.forEachInvertedInner(r,a-l,Math.max(s,l)-l,o+l)===!1||s<l&&this.left.forEachInvertedInner(r,Math.min(a,l),s,o)===!1)return!1},e.prototype.sliceInner=function(r,a){if(r==0&&a==this.length)return this;var s=this.left.length;return a<=s?this.left.slice(r,a):r>=s?this.right.slice(r-s,a-s):this.left.slice(r,s).append(this.right.slice(0,a-s))},e.prototype.leafAppend=function(r){var a=this.right.leafAppend(r);if(a)return new e(this.left,a)},e.prototype.leafPrepend=function(r){var a=this.left.leafPrepend(r);if(a)return new e(a,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(Li);const AXe=500;class Vl{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,s;n&&(a=this.remapping(r,this.items.length),s=a.maps.length);let o=e.tr,l,c,u=[],d=[];return this.items.forEach((h,f)=>{if(!h.step){a||(a=this.remapping(r,f+1),s=a.maps.length),s--,d.push(h);return}if(a){d.push(new vc(h.map));let p=h.step.map(a.slice(s)),x;p&&o.maybeStep(p).doc&&(x=o.mapping.maps[o.mapping.maps.length-1],u.push(new vc(x,void 0,void 0,u.length+d.length))),s--,x&&a.appendMap(x,s)}else o.maybeStep(h.step);if(h.selection)return l=a?h.selection.map(a.slice(s)):h.selection,c=new Vl(this.items.slice(0,r).append(d.reverse().concat(u)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:o,selection:l}}addTransform(e,n,r,a){let s=[],o=this.eventCount,l=this.items,c=!a&&l.length?l.get(l.length-1):null;for(let d=0;d<e.steps.length;d++){let h=e.steps[d].invert(e.docs[d]),f=new vc(e.mapping.maps[d],h,n),p;(p=c&&c.merge(f))&&(f=p,d?s.pop():l=l.slice(0,l.length-1)),s.push(f),n&&(o++,n=void 0),a||(c=f)}let u=o-r.depth;return u>MXe&&(l=TXe(l,u),o-=u),new Vl(l.append(s),o)}remapping(e,n){let r=new Kv;return this.items.forEach((a,s)=>{let o=a.mirrorOffset!=null&&s-a.mirrorOffset>=e?r.maps.length-a.mirrorOffset:void 0;r.appendMap(a.map,o)},e,n),r}addMaps(e){return this.eventCount==0?this:new Vl(this.items.append(e.map(n=>new vc(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(f=>{f.selection&&l--},a);let c=n;this.items.forEach(f=>{let p=s.getMirror(--c);if(p==null)return;o=Math.min(o,p);let x=s.maps[p];if(f.step){let v=e.steps[p].invert(e.docs[p]),g=f.selection&&f.selection.map(s.slice(c+1,p));g&&l++,r.push(new vc(x,v,g))}else r.push(new vc(x))},a);let u=[];for(let f=n;f<o;f++)u.push(new vc(s.maps[f]));let d=this.items.slice(0,a).append(u).append(r),h=new Vl(d,l);return h.emptyItemCount()>AXe&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,a=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)a.push(o),o.selection&&s++;else if(o.step){let c=o.step.map(n.slice(r)),u=c&&c.getMap();if(r--,u&&n.appendMap(u,r),c){let d=o.selection&&o.selection.map(n.slice(r));d&&s++;let h=new vc(u.invert(),c,d),f,p=a.length-1;(f=a.length&&a[p].merge(h))?a[p]=f:a.push(h)}}else o.map&&r--},this.items.length,0),new Vl(Li.from(a.reverse()),s)}}Vl.empty=new Vl(Li.empty,0);function TXe(t,e){let n;return t.forEach((r,a)=>{if(r.selection&&e--==0)return n=a,!1}),t.slice(n)}class vc{constructor(e,n,r,a){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=a}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new vc(n.getMap().invert(),n,this.selection)}}}class dh{constructor(e,n,r,a,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=s}}const MXe=20;function PXe(t,e,n,r){let a=n.getMeta(Cf),s;if(a)return a.historyState;n.getMeta(DXe)&&(t=new dh(t.done,t.undone,null,0,-1));let o=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(o&&o.getMeta(Cf))return o.getMeta(Cf).redo?new dh(t.done.addTransform(n,void 0,r,d1(e)),t.undone,LW(n.mapping.maps),t.prevTime,t.prevComposition):new dh(t.done,t.undone.addTransform(n,void 0,r,d1(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=n.getMeta("composition"),c=t.prevTime==0||!o&&t.prevComposition!=l&&(t.prevTime<(n.time||0)-r.newGroupDelay||!EXe(n,t.prevRanges)),u=o?v2(t.prevRanges,n.mapping):LW(n.mapping.maps);return new dh(t.done.addTransform(n,c?e.selection.getBookmark():void 0,r,d1(e)),Vl.empty,u,n.time,l??t.prevComposition)}else return(s=n.getMeta("rebased"))?new dh(t.done.rebased(n,s),t.undone.rebased(n,s),v2(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new dh(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),v2(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function EXe(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,a)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&a>=e[s]&&(n=!0)}),n}function LW(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,a,s,o)=>e.push(s,o));return e}function v2(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let a=e.map(t[r],1),s=e.map(t[r+1],-1);a<=s&&n.push(a,s)}return n}function jXe(t,e,n){let r=d1(e),a=Cf.get(e).spec.config,s=(n?t.undone:t.done).popEvent(e,r);if(!s)return null;let o=s.selection.resolve(s.transform.doc),l=(n?t.done:t.undone).addTransform(s.transform,e.selection.getBookmark(),a,r),c=new dh(n?l:s.remaining,n?s.remaining:l,null,0,-1);return s.transform.setSelection(o).setMeta(Cf,{redo:n,historyState:c})}let w2=!1,OW=null;function d1(t){let e=t.plugins;if(OW!=e){w2=!1,OW=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){w2=!0;break}}return w2}const Cf=new Ni("history"),DXe=new Ni("closeHistory");function RXe(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new ya({key:Cf,state:{init(){return new dh(Vl.empty,Vl.empty,null,0,-1)},apply(e,n,r){return PXe(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,a=r=="historyUndo"?lie:r=="historyRedo"?cie:null;return!a||!e.editable?!1:(n.preventDefault(),a(e.state,e.dispatch))}}}})}function oie(t,e){return(n,r)=>{let a=Cf.getState(n);if(!a||(t?a.undone:a.done).eventCount==0)return!1;if(r){let s=jXe(a,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const lie=oie(!1,!0),cie=oie(!0,!0);zr.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new ya({key:new Ni("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const a=this.options.limit;if(a==null||a===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>a){const o=s-a,l=0,c=o;console.warn(`[CharacterCount] Initial content exceeded limit of ${a} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(l,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const a=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||a>r&&s>r&&s<=a)return!0;if(a>r&&s>r&&s>a||!e.getMeta("paste"))return!1;const l=e.selection.$head.pos,c=s-r,u=l-c,d=l;return e.deleteRange(u,d),!(this.storage.characters({node:e.doc})>r)}})]}});var FXe=zr.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[bXe(this.options)]}});zr.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new ya({key:new Ni("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:a}=e,s=[];if(!n||!r)return pa.create(t,[]);let o=0;this.options.mode==="deepest"&&t.descendants((c,u)=>{if(c.isText)return;if(!(a>=u&&a<=u+c.nodeSize-1))return!1;o+=1});let l=0;return t.descendants((c,u)=>{if(c.isText||!(a>=u&&a<=u+c.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";s.push(Es.node(u,u+c.nodeSize,{class:this.options.className}))}),pa.create(t,s)}}})]}});var LXe=zr.create({name:"gapCursor",addProseMirrorPlugins(){return[wXe()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Cr(rn(t,"allowGapCursor",n)))!=null?e:null}}}),IW="placeholder";function OXe(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}zr.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:IW,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${OXe(this.options.dataAttribute)}`:`data-${IW}`;return[new ya({key:new Ni("placeholder"),props:{decorations:({doc:e,selection:n})=>{const r=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:a}=n,s=[];if(!r)return null;const o=this.editor.isEmpty;return e.descendants((l,c)=>{const u=a>=c&&a<=c+l.nodeSize,d=!l.isLeaf&&yA(l);if((u||!this.options.showOnlyCurrent)&&d){const h=[this.options.emptyNodeClass];o&&h.push(this.options.emptyEditorClass);const f=Es.node(c,c+l.nodeSize,{class:h.join(" "),[t]:typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:l,pos:c,hasAnchor:u}):this.options.placeholder});s.push(f)}return this.options.includeChildren}),pa.create(e,s)}}})]}});zr.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new ya({key:new Ni("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||mae(n.selection)||t.view.dragging?null:pa.create(n.doc,[Es.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function zW({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var IXe=zr.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Ni(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,a])=>a).filter(a=>(this.options.notAfter||[]).concat(n).includes(a.name));return[new ya({key:e,appendTransaction:(a,s,o)=>{const{doc:l,tr:c,schema:u}=o,d=e.getState(o),h=l.content.size,f=u.nodes[n];if(d)return c.insert(h,f.create())},state:{init:(a,s)=>{const o=s.tr.doc.lastChild;return!zW({node:o,types:r})},apply:(a,s)=>{if(!a.docChanged||a.getMeta("__uniqueIDTransaction"))return s;const o=a.doc.lastChild;return!zW({node:o,types:r})}}})]}}),zXe=zr.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>lie(t,e),redo:()=>({state:t,dispatch:e})=>cie(t,e)}},addProseMirrorPlugins(){return[RXe(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),UXe=zr.create({name:"starterKit",addExtensions(){var t,e,n,r;const a=[];return this.options.bold!==!1&&a.push(dKe.configure(this.options.bold)),this.options.blockquote!==!1&&a.push(sKe.configure(this.options.blockquote)),this.options.bulletList!==!1&&a.push(Kae.configure(this.options.bulletList)),this.options.code!==!1&&a.push(fKe.configure(this.options.code)),this.options.codeBlock!==!1&&a.push(bKe.configure(this.options.codeBlock)),this.options.document!==!1&&a.push(xKe.configure(this.options.document)),this.options.dropcursor!==!1&&a.push(FXe.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&a.push(LXe.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&a.push(yKe.configure(this.options.hardBreak)),this.options.heading!==!1&&a.push(vKe.configure(this.options.heading)),this.options.undoRedo!==!1&&a.push(zXe.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&a.push(wKe.configure(this.options.horizontalRule)),this.options.italic!==!1&&a.push(kKe.configure(this.options.italic)),this.options.listItem!==!1&&a.push(Xae.configure(this.options.listItem)),this.options.listKeymap!==!1&&a.push(tie.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&a.push(Wae.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&a.push(rie.configure(this.options.orderedList)),this.options.paragraph!==!1&&a.push(dXe.configure(this.options.paragraph)),this.options.strike!==!1&&a.push(fXe.configure(this.options.strike)),this.options.text!==!1&&a.push(pXe.configure(this.options.text)),this.options.underline!==!1&&a.push(aie.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&a.push(IXe.configure((r=this.options)==null?void 0:r.trailingNode)),a}}),BXe=UXe,HXe=zr.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),$Xe=HXe,VXe=20,uie=(t,e=0)=>{const n=[];return!t.children.length||e>VXe||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...uie(r,e+1))}),n},qXe=t=>{if(!t.children.length)return;const e=uie(t);e&&e.forEach(n=>{var r,a;const s=n.getAttribute("style"),o=(a=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:a.getAttribute("style");n.setAttribute("style",`${o};${s}`)})},die=lm.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&qXe(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Fa(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),GXe=zr.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(a=>a.trim()).filter(Boolean);for(let a=r.length-1;a>=0;a-=1){const s=r[a].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="background-color")return l.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),hie=zr.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(a=>a.trim()).filter(Boolean);for(let a=r.length-1;a>=0;a-=1){const s=r[a].split(":");if(s.length>=2){const o=s[0].trim().toLowerCase(),l=s.slice(1).join(":").trim();if(o==="color")return l.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),WXe=zr.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>t.style.fontFamily,renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),KXe=zr.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),XXe=zr.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>t.style.lineHeight,renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});zr.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(GXe.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(hie.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(WXe.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(KXe.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(XXe.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(die.configure(this.options.textStyle)),t}});var YXe=hie,QXe=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,ZXe=co.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:t}){return["img",Fa(this.options.HTMLAttributes,t)]},parseMarkdown:(t,e)=>e.createNode("image",{src:t.href,title:t.title,alt:t.text}),renderMarkdown:t=>{var e,n,r,a,s,o;const l=(n=(e=t.attrs)==null?void 0:e.src)!=null?n:"",c=(a=(r=t.attrs)==null?void 0:r.alt)!=null?a:"",u=(o=(s=t.attrs)==null?void 0:s.title)!=null?o:"";return u?`![${c}](${l} "${u}")`:`![${c}](${l})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u")return null;const{directions:t,minWidth:e,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize;return({node:a,getPos:s,HTMLAttributes:o,editor:l})=>{const c=document.createElement("img");Object.entries(o).forEach(([h,f])=>{if(f!=null)switch(h){case"width":case"height":break;default:c.setAttribute(h,f);break}}),c.src=o.src;const u=new Y9e({element:c,editor:l,node:a,getPos:s,onResize:(h,f)=>{c.style.width=`${h}px`,c.style.height=`${f}px`},onCommit:(h,f)=>{const p=s();p!==void 0&&this.editor.chain().setNodeSelection(p).updateAttributes(this.name,{width:h,height:f}).run()},onUpdate:(h,f,p)=>h.type===a.type,options:{directions:t,min:{width:e,height:n},preserveAspectRatio:r===!0}}),d=u.dom;return d.style.visibility="hidden",d.style.pointerEvents="none",c.onload=()=>{d.style.visibility="",d.style.pointerEvents=""},u}},addCommands(){return{setImage:t=>({commands:e})=>e.insertContent({type:this.name,attrs:t})}},addInputRules(){return[Pae({find:QXe,type:this.type,getAttributes:t=>{const[,,e,n,r]=t;return{src:n,alt:e,title:r}}})]}}),JXe=ZXe;function QR({content:t,onChange:e,placeholder:n}){const{t:r}=Ot(),a=tKe({extensions:[BXe.configure({heading:!1,codeBlock:!1,code:!1}),gXe,QKe.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),$Xe.configure({types:["paragraph"]}),die,YXe,JXe.configure({HTMLAttributes:{style:"max-width: 100%; height: auto;"}})],content:t,onUpdate:({editor:l})=>{e(l.getHTML())},editorProps:{attributes:{class:"prose prose-invert prose-sm max-w-none focus:outline-none min-h-[120px] px-3 py-2",placeholder:n||""}}});if(!a)return null;const s=({onClick:l,isActive:c=!1,children:u,title:d})=>i.jsx("button",{type:"button",onClick:l,title:d,className:`p-1.5 rounded hover:bg-bambu-dark-tertiary transition-colors ${c?"bg-bambu-dark-tertiary text-bambu-green":"text-bambu-gray"}`,children:u}),o=()=>{const l=window.prompt("Enter URL:");l&&a.chain().focus().setLink({href:l}).run()};return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden bg-bambu-dark",children:[i.jsxs("div",{className:"flex items-center gap-0.5 p-1.5 border-b border-bambu-dark-tertiary bg-bambu-dark-secondary",children:[i.jsx(s,{onClick:()=>a.chain().focus().toggleBold().run(),isActive:a.isActive("bold"),title:r("richTextEditor.bold"),children:i.jsx(Vde,{className:"w-4 h-4"})}),i.jsx(s,{onClick:()=>a.chain().focus().toggleItalic().run(),isActive:a.isActive("italic"),title:r("richTextEditor.italic"),children:i.jsx(Xme,{className:"w-4 h-4"})}),i.jsx(s,{onClick:()=>a.chain().focus().toggleUnderline().run(),isActive:a.isActive("underline"),title:r("richTextEditor.underline"),children:i.jsx(Gpe,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),i.jsx(s,{onClick:()=>a.chain().focus().toggleBulletList().run(),isActive:a.isActive("bulletList"),title:r("richTextEditor.bulletList"),children:i.jsx(WC,{className:"w-4 h-4"})}),i.jsx(s,{onClick:()=>a.chain().focus().toggleOrderedList().run(),isActive:a.isActive("orderedList"),title:r("richTextEditor.numberedList"),children:i.jsx(bX,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),i.jsx(s,{onClick:()=>a.chain().focus().setTextAlign("left").run(),isActive:a.isActive({textAlign:"left"}),title:r("richTextEditor.alignLeft"),children:i.jsx(Ipe,{className:"w-4 h-4"})}),i.jsx(s,{onClick:()=>a.chain().focus().setTextAlign("center").run(),isActive:a.isActive({textAlign:"center"}),title:r("richTextEditor.alignCenter"),children:i.jsx(Rpe,{className:"w-4 h-4"})}),i.jsx(s,{onClick:()=>a.chain().focus().setTextAlign("right").run(),isActive:a.isActive({textAlign:"right"}),title:r("richTextEditor.alignRight"),children:i.jsx(Lpe,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary mx-1"}),i.jsx(s,{onClick:o,isActive:a.isActive("link"),title:r("richTextEditor.addLink"),children:i.jsx(qb,{className:"w-4 h-4"})}),a.isActive("link")&&i.jsx(s,{onClick:()=>a.chain().focus().unsetLink().run(),title:r("richTextEditor.removeLink"),children:i.jsx(ek,{className:"w-4 h-4"})})]}),i.jsx(Dae,{editor:a})]})}function mie({archiveId:t,archiveName:e,onClose:n}){const r=en(),[a,s]=w.useState(!1),[o,l]=w.useState(null),[c,u]=w.useState({}),{data:d,isLoading:h,error:f}=Je({queryKey:["archive-project-page",t],queryFn:()=>ne.getArchiveProjectPage(t)}),p=st({mutationFn:A=>ne.updateArchiveProjectPage(t,A),onSuccess:()=>{r.invalidateQueries({queryKey:["archive-project-page",t]}),s(!1),u({})}});w.useEffect(()=>{const A=M=>{M.key==="Escape"&&(o!==null?l(null):a?y():n())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[o,a,n]);const x=[...d?.model_pictures||[],...d?.profile_pictures||[]],v=()=>{u({title:d?.title||"",description:d?.description||"",designer:d?.designer||"",license:d?.license||"",profile_title:d?.profile_title||"",profile_description:d?.profile_description||""}),s(!0)},g=()=>{p.mutate(c)},y=()=>{s(!1),u({})},_=A=>{const M=["p","br","b","strong","i","em","u","a","ul","ol","li","figure","img"],C=new DOMParser().parseFromString(A,"text/html"),j=P=>{if(P.nodeType===Node.TEXT_NODE)return P.textContent||"";if(P.nodeType===Node.ELEMENT_NODE){const E=P,U=E.tagName.toLowerCase();if(!M.includes(U))return Array.from(E.childNodes).map(j).join("");let L="";if(U==="a"&&E.getAttribute("href")){const D=E.getAttribute("href");D?.toLowerCase().startsWith("http")&&(L=` href="${D}" target="_blank" rel="noopener noreferrer"`)}if(U==="img"){const D=E.getAttribute("src");if(!D?.toLowerCase().startsWith("http"))return"";L=` src="${D}" style="max-width: 100%; height: auto;"`}const B=Array.from(E.childNodes).map(j).join("");return["br","img"].includes(U)?`<${U}${L} />`:`<${U}${L}>${B}</${U}>`}return""};return Array.from(C.body.childNodes).map(j).join("")},N=d&&(d.title||d.description||d.designer||d.profile_title||x.length>0),k=A=>{A.target===A.currentTarget&&n()};return i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:k,children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Project Page",e&&i.jsxs("span",{className:"text-bambu-gray ml-2",children:["- ",e]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[!a&&N&&i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:v,children:[i.jsx(Pf,{className:"w-4 h-4 mr-1"}),"Edit"]}),a&&i.jsxs(i.Fragment,{children:[i.jsx(Ce,{variant:"ghost",size:"sm",onClick:y,children:"Cancel"}),i.jsxs(Ce,{variant:"primary",size:"sm",onClick:g,disabled:p.isPending,children:[i.jsx(ps,{className:"w-4 h-4 mr-1"}),"Save"]})]}),i.jsx("button",{onClick:n,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[h&&i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-bambu-green border-t-transparent"})}),f&&i.jsx("div",{className:"text-red-400 text-center py-12",children:"Failed to load project page data"}),d&&!N&&i.jsxs("div",{className:"text-bambu-gray text-center py-12",children:[i.jsx(Ms,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),i.jsx("p",{children:"No project page data found in this 3MF file."}),i.jsx("p",{className:"text-sm mt-2",children:"Project pages are typically included in files downloaded from MakerWorld."})]}),d&&N&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"space-y-4",children:[a?i.jsx("input",{type:"text",value:c.title||"",onChange:A=>u({...c,title:A.target.value}),placeholder:"Title",className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-4 py-2 text-white text-xl font-semibold"}):d.title&&i.jsx("h3",{className:"text-xl font-semibold text-white",children:d.title}),i.jsxs("div",{className:"flex flex-wrap gap-4 text-sm",children:[a?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(td,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c.designer||"",onChange:A=>u({...c,designer:A.target.value}),placeholder:"Designer",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.designer&&i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx(td,{className:"w-4 h-4"}),i.jsx("span",{children:d.designer}),d.designer_user_id&&i.jsx("a",{href:`https://makerworld.com/en/@${d.designer_user_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline",children:i.jsx(Xr,{className:"w-3 h-3"})})]}),d.creation_date&&i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx(ra,{className:"w-4 h-4"}),i.jsx("span",{children:d.creation_date})]}),a?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ms,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c.license||"",onChange:A=>u({...c,license:A.target.value}),placeholder:"License",className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1 text-white"})]}):d.license&&i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx(Ms,{className:"w-4 h-4"}),i.jsx("span",{children:d.license})]}),d.origin&&i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark rounded text-bambu-gray",children:d.origin})]})]}),(d.description||a)&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Description"}),a?i.jsx(QR,{content:c.description||"",onChange:A=>u({...c,description:A}),placeholder:"Enter description..."}):i.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(d.description||"")}})]}),(d.profile_title||d.profile_description||a)&&i.jsxs("div",{className:"space-y-2 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide",children:"Print Profile"}),a?i.jsxs("div",{className:"space-y-2",children:[i.jsx("input",{type:"text",value:c.profile_title||"",onChange:A=>u({...c,profile_title:A.target.value}),placeholder:"Profile Title",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-white"}),i.jsx(QR,{content:c.profile_description||"",onChange:A=>u({...c,profile_description:A}),placeholder:"Profile description..."})]}):i.jsxs(i.Fragment,{children:[d.profile_title&&i.jsx("p",{className:"text-white font-medium",children:d.profile_title}),d.profile_description&&i.jsx("div",{className:"prose prose-invert prose-sm max-w-none text-bambu-gray-light",dangerouslySetInnerHTML:{__html:_(d.profile_description)}}),d.profile_user_name&&i.jsxs("p",{className:"text-sm text-bambu-gray",children:["by ",d.profile_user_name]})]})]}),x.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("h4",{className:"text-sm font-medium text-bambu-gray uppercase tracking-wide flex items-center gap-2",children:[i.jsx(Ju,{className:"w-4 h-4"}),"Images (",x.length,")"]}),i.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:x.map((A,M)=>i.jsx("button",{onClick:()=>l(M),className:"aspect-square rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",children:i.jsx("img",{src:A.url,alt:A.name,className:"w-full h-full object-cover"})},A.path))})]}),d.design_model_id&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("a",{href:`https://makerworld.com/en/models/${d.design_model_id}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-bambu-green hover:underline",children:[i.jsx(Xr,{className:"w-4 h-4"}),"View on MakerWorld"]})})]})]})]}),o!==null&&x[o]&&i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-60",onClick:()=>l(null),children:[i.jsx("button",{onClick:A=>{A.stopPropagation(),l(Math.max(0,o-1))},disabled:o===0,className:"absolute left-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:i.jsx(Xl,{className:"w-6 h-6 text-white"})}),i.jsx("img",{src:x[o].url,alt:x[o].name,className:"max-w-[90vw] max-h-[90vh] object-contain",onClick:A=>A.stopPropagation()}),i.jsx("button",{onClick:A=>{A.stopPropagation(),l(Math.min(x.length-1,o+1))},disabled:o===x.length-1,className:"absolute right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary disabled:opacity-30",children:i.jsx(pi,{className:"w-6 h-6 text-white"})}),i.jsx("button",{onClick:()=>l(null),className:"absolute top-4 right-4 p-2 bg-bambu-dark-secondary rounded-full hover:bg-bambu-dark-tertiary",children:i.jsx(Lt,{className:"w-6 h-6 text-white"})}),i.jsxs("div",{className:"absolute bottom-4 text-white text-sm",children:[o+1," / ",x.length]})]})]})}const eYe=[.25,.5,.75,1,1.5,2,3,4];function Tg(t){const e=Math.floor(t/60),n=Math.floor(t%60);return`${e}:${n.toString().padStart(2,"0")}`}function tYe({archiveId:t,timelapseSrc:e,onClose:n,onSave:r}){const{showToast:a}=an(),s=w.useRef(null),o=w.useRef(null),[l,c]=w.useState(!1),[u,d]=w.useState(0),[h,f]=w.useState(0),[p,x]=w.useState(0),[v,g]=w.useState(0),[y,_]=w.useState(1),[N,k]=w.useState(null),[A,M]=w.useState(null),[C,j]=w.useState(.8),[P,E]=w.useState(!1),{data:U,isLoading:L}=Je({queryKey:["timelapse-info",t],queryFn:()=>ne.getTimelapseInfo(t)}),{data:B}=Je({queryKey:["timelapse-thumbnails",t],queryFn:()=>ne.getTimelapseThumbnails(t,15)}),D=st({mutationFn:()=>ne.processTimelapse(t,{trimStart:p,trimEnd:v,speed:y,saveMode:"replace"},N||void 0),onSuccess:H=>{a(H.message,"success"),r?.(),n()},onError:H=>{a(H.message||"Processing failed","error")}});w.useEffect(()=>{U?.duration&&v===0&&g(U.duration)},[U?.duration,v]),w.useEffect(()=>{const H=K=>{K.key==="Escape"&&n()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[n]),w.useEffect(()=>{const H=s.current;if(!H)return;const K=()=>{const ce=H.currentTime;d(ce),ce>=v&&(H.currentTime=p)},te=()=>{f(H.duration),v===0&&g(H.duration)},Z=()=>c(!0),ve=()=>c(!1);return H.addEventListener("timeupdate",K),H.addEventListener("durationchange",te),H.addEventListener("play",Z),H.addEventListener("pause",ve),()=>{H.removeEventListener("timeupdate",K),H.removeEventListener("durationchange",te),H.removeEventListener("play",Z),H.removeEventListener("pause",ve)}},[p,v]),w.useEffect(()=>{const H=o.current,K=s.current;!H||!K||!A||(H.currentTime=K.currentTime,H.playbackRate=K.playbackRate,l&&!P?H.play().catch(()=>{}):H.pause())},[l,A,P]),w.useEffect(()=>{o.current&&(o.current.volume=P?0:C)},[C,P]),w.useEffect(()=>{s.current&&(s.current.playbackRate=y),o.current&&(o.current.playbackRate=y)},[y]);const $=w.useCallback(()=>{const H=s.current;H&&(l?H.pause():(H.currentTime<p&&(H.currentTime=p),H.play()))},[l,p]),G=H=>{const K=s.current;K&&(K.currentTime=Math.max(p,Math.min(v,H)))},z=H=>{const K=H.target.files?.[0];K&&(A&&URL.revokeObjectURL(A),k(K),M(URL.createObjectURL(K)))},W=()=>{A&&URL.revokeObjectURL(A),k(null),M(null)};w.useEffect(()=>()=>{A&&URL.revokeObjectURL(A)},[A]);const X=v-p,ae=X/y;return L?i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:i.jsxs("div",{className:"flex items-center gap-3 text-white",children:[i.jsx(it,{className:"w-6 h-6 animate-spin"}),"Loading video info..."]})}):i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:i.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-5xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-bambu-green"}),"Edit Timelapse"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"primary",size:"sm",onClick:()=>D.mutate(),disabled:D.isPending,children:D.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]})}),i.jsx("button",{onClick:n,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[i.jsxs("div",{className:"relative",children:[i.jsx("video",{ref:s,src:e,className:"w-full rounded-lg bg-black",onClick:$,muted:!!A}),!l&&i.jsx("button",{onClick:$,className:"absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors",children:i.jsx("div",{className:"p-4 bg-bambu-green rounded-full",children:i.jsx(io,{className:"w-8 h-8 text-white"})})}),A&&i.jsx("audio",{ref:o,src:A,loop:!0})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(npe,{className:"w-4 h-4"}),i.jsx("span",{children:"Trim"}),i.jsxs("span",{className:"ml-auto",children:[Tg(p)," - ",Tg(v)," (",Tg(X),")"]})]}),i.jsxs("div",{className:"relative h-16 bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsx("div",{className:"absolute inset-0 flex",children:B?.thumbnails.map((H,K)=>i.jsx("div",{className:"flex-1 bg-cover bg-center",style:{backgroundImage:`url(data:image/jpeg;base64,${H})`}},K))}),i.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/60",style:{width:`${p/h*100}%`}}),i.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/60",style:{width:`${(h-v)/h*100}%`}}),i.jsx("div",{className:"absolute inset-y-0 border-2 border-bambu-green",style:{left:`${p/h*100}%`,right:`${(h-v)/h*100}%`}}),i.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-white shadow-lg",style:{left:`${u/h*100}%`}}),i.jsx("input",{type:"range",min:0,max:h,step:.1,value:p,onChange:H=>{const K=parseFloat(H.target.value);K<v-1&&(x(K),s.current&&s.current.currentTime<K&&(s.current.currentTime=K))},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 50% 0 0)"}}),i.jsx("input",{type:"range",min:0,max:h,step:.1,value:v,onChange:H=>{const K=parseFloat(H.target.value);K>p+1&&g(K)},className:"absolute inset-0 w-full opacity-0 cursor-ew-resize",style:{clipPath:"inset(0 0 0 50%)"}})]}),i.jsx("input",{type:"range",min:0,max:h,step:.1,value:u,onChange:H=>G(parseFloat(H.target.value)),className:`w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8278. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8279. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8280. [&::-webkit-slider-thumb]:cursor-pointer`}),i.jsx("div",{className:"flex items-center justify-center gap-2",children:i.jsx("button",{onClick:$,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?i.jsx(YC,{className:"w-5 h-5 text-white"}):i.jsx(io,{className:"w-5 h-5 text-white"})})})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(GC,{className:"w-4 h-4"}),i.jsx("span",{children:"Speed"}),i.jsxs("span",{className:"ml-auto",children:[y,"x (output: ",Tg(ae),")"]})]}),i.jsx("div",{className:"flex gap-1",children:eYe.map(H=>i.jsxs("button",{onClick:()=>_(H),className:`flex-1 px-2 py-2 text-sm rounded transition-colors ${y===H?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[H,"x"]},H))})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(o3,{className:"w-4 h-4"}),i.jsx("span",{children:"Music Overlay"})]}),N?i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(o3,{className:"w-5 h-5 text-bambu-green"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:N.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(N.size/1024/1024).toFixed(1)," MB"]})]}),i.jsx("button",{onClick:()=>E(!P),className:"p-2 hover:bg-bambu-dark-tertiary rounded transition-colors",children:P?i.jsx(tge,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Jpe,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("input",{type:"range",min:0,max:1,step:.1,value:C,onChange:H=>j(parseFloat(H.target.value)),className:`w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8281. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8282. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full`}),i.jsx("button",{onClick:W,className:"p-2 hover:bg-red-500/20 rounded transition-colors",children:i.jsx(Jt,{className:"w-4 h-4 text-red-400"})})]}):i.jsxs("label",{className:"flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green/50 transition-colors",children:[i.jsx(Ra,{className:"w-8 h-8 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:"Drop audio file or click to upload"}),i.jsx("span",{className:"text-xs text-bambu-gray/60",children:"MP3, WAV, M4A, AAC, OGG"}),i.jsx("input",{type:"file",accept:".mp3,.wav,.m4a,.aac,.ogg,audio/*",onChange:z,className:"hidden"})]})]}),i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg text-sm space-y-1",children:[i.jsxs("p",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white",children:"Original:"})," ",Tg(h)," @ ",U?.width,"x",U?.height]}),i.jsxs("p",{className:"text-bambu-gray",children:[i.jsx("span",{className:"text-white",children:"Output:"})," ",Tg(ae)," @ ",y,"x speed",N&&" + music overlay"]})]})]}),D.isPending&&i.jsxs("div",{className:"absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4",children:[i.jsx(it,{className:"w-12 h-12 text-bambu-green animate-spin"}),i.jsx("p",{className:"text-white text-lg",children:"Processing timelapse..."}),i.jsx("p",{className:"text-bambu-gray text-sm",children:"This may take a few moments"})]})]})})}const nYe=[.25,.5,.75,1,1.5,2,3,4];function fie({src:t,title:e,downloadFilename:n,archiveId:r,onClose:a,onEdit:s}){const o=w.useRef(null),[l,c]=w.useState(!0),[u,d]=w.useState(1),[h,f]=w.useState(0),[p,x]=w.useState(0),[v,g]=w.useState(!1);w.useEffect(()=>{const C=o.current;C&&(C.playbackRate=u)},[u]),w.useEffect(()=>{const C=j=>{j.key==="Escape"&&a()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[a]),w.useEffect(()=>{const C=o.current;if(!C)return;const j=()=>f(C.currentTime),P=()=>x(C.duration),E=()=>c(!0),U=()=>c(!1);return C.addEventListener("timeupdate",j),C.addEventListener("durationchange",P),C.addEventListener("play",E),C.addEventListener("pause",U),()=>{C.removeEventListener("timeupdate",j),C.removeEventListener("durationchange",P),C.removeEventListener("play",E),C.removeEventListener("pause",U)}},[]);const y=()=>{const C=o.current;C&&(l?C.pause():C.play())},_=C=>{const j=o.current;j&&(j.currentTime=parseFloat(C.target.value))},N=()=>{const C=o.current;C&&(C.currentTime=Math.max(0,C.currentTime-5))},k=()=>{const C=o.current;C&&(C.currentTime=Math.min(p,C.currentTime+5))},A=C=>{const j=Math.floor(C/60),P=Math.floor(C%60);return`${j}:${P.toString().padStart(2,"0")}`},M=()=>{const C=document.createElement("a");C.href=t,C.download=n,C.click()};return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80",children:[i.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl max-w-4xl w-full mx-4 overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-bambu-green"}),e]}),i.jsxs("div",{className:"flex items-center gap-2",children:[r&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>g(!0),children:[i.jsx($a,{className:"w-4 h-4"}),"Edit"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:M,children:[i.jsx(da,{className:"w-4 h-4"}),"Download"]}),i.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]})]}),i.jsxs("div",{className:"p-4",children:[i.jsx("video",{ref:o,src:t,autoPlay:!0,className:"w-full rounded-lg",onClick:y}),i.jsxs("div",{className:"mt-4 space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-xs text-bambu-gray w-12 text-right",children:A(h)}),i.jsx("input",{type:"range",min:0,max:p||100,value:h,onChange:_,className:`flex-1 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  8283. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  8284. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  8285. [&::-webkit-slider-thumb]:cursor-pointer`}),i.jsx("span",{className:"text-xs text-bambu-gray w-12",children:A(p)})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:N,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip back 5s",children:i.jsx(ppe,{className:"w-5 h-5 text-bambu-gray"})}),i.jsx("button",{onClick:y,className:"p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors",children:l?i.jsx(YC,{className:"w-5 h-5 text-white"}):i.jsx(io,{className:"w-5 h-5 text-white"})}),i.jsx("button",{onClick:k,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Skip forward 5s",children:i.jsx(TF,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:"Speed:"}),i.jsx("div",{className:"flex gap-1",children:nYe.map(C=>i.jsxs("button",{onClick:()=>d(C),className:`px-2 py-1 text-xs rounded transition-colors ${u===C?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary/80"}`,children:[C,"x"]},C))})]})]})]})]})]}),v&&r&&i.jsx(tYe,{archiveId:r,timelapseSrc:t,onClose:()=>g(!1),onSave:s})]})}function rYe({archiveIds:t,onClose:e}){w.useEffect(()=>{const s=o=>{o.key==="Escape"&&e()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e]);const{data:n,isLoading:r,error:a}=Je({queryKey:["archive-comparison",t],queryFn:()=>ne.compareArchives(t)});return i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg max-w-4xl w-full max-h-[90vh] flex flex-col border border-bambu-dark-tertiary",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white",children:["Compare Archives (",t.length,")"]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white p-1",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 overflow-auto p-4 bg-bambu-dark-secondary",children:r?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a?i.jsxs("div",{className:"text-center py-12 text-red-400",children:[i.jsx(Tn,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),i.jsx("p",{children:"Failed to load comparison"}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:a instanceof Error?a.message:"Unknown error"})]}):n?i.jsx(aYe,{comparison:n}):null}),i.jsx("div",{className:"p-4 border-t border-bambu-dark-tertiary",children:i.jsx(Ce,{variant:"secondary",onClick:e,className:"w-full",children:"Close"})})]})})}function aYe({comparison:t}){return i.jsxs("div",{className:"space-y-6",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{className:"text-left text-sm text-bambu-gray font-medium pb-2 pr-4 min-w-[150px]",children:"Setting"}),t.archives.map(e=>i.jsxs("th",{className:"text-left text-sm font-medium pb-2 px-2 min-w-[120px]",children:[i.jsx("div",{className:"text-white truncate max-w-[150px]",title:e.print_name,children:e.print_name}),i.jsx("div",{className:`text-xs ${e.status==="completed"?"text-status-ok":e.status==="failed"?"text-status-error":"text-bambu-gray"}`,children:e.status})]},e.id))]})}),i.jsx("tbody",{className:"divide-y divide-bambu-gray/20",children:t.comparison.map(e=>i.jsxs("tr",{className:e.has_difference?"bg-yellow-500/5":"",children:[i.jsx("td",{className:"py-2 pr-4 text-sm",children:i.jsxs("div",{className:"flex items-center gap-2",children:[e.has_difference&&i.jsx(Tn,{className:"w-3 h-3 text-yellow-400 flex-shrink-0"}),i.jsx("span",{className:e.has_difference?"text-yellow-400":"text-bambu-gray",children:e.label})]})}),e.values.map((n,r)=>i.jsxs("td",{className:"py-2 px-2 text-sm text-white",children:[n??i.jsx("span",{className:"text-bambu-gray/50",children:"-"}),e.unit&&n!==null&&i.jsx("span",{className:"text-bambu-gray ml-1",children:e.unit})]},r))]},e.field))})]})}),t.differences.length>0&&i.jsxs("div",{className:"p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsxs("h4",{className:"text-sm font-medium text-yellow-400 mb-2 flex items-center gap-2",children:[i.jsx(Tn,{className:"w-4 h-4"}),t.differences.length," Difference",t.differences.length>1?"s":""," Found"]}),i.jsxs("ul",{className:"text-sm text-white/80 space-y-1",children:[t.differences.slice(0,5).map(e=>i.jsxs("li",{children:[i.jsx("span",{className:"text-yellow-400",children:e.label}),": ",e.values.join(" vs ")," ",e.unit||""]},e.field)),t.differences.length>5&&i.jsxs("li",{className:"text-bambu-gray",children:["...and ",t.differences.length-5," more"]})]})]}),t.success_correlation.has_both_outcomes?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("h4",{className:"text-sm font-medium text-white mb-3 flex items-center gap-2",children:[i.jsx(aa,{className:"w-4 h-4 text-bambu-green"}),"Success/Failure Analysis"]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm mb-3",children:[i.jsxs("span",{className:"text-bambu-green",children:[t.success_correlation.successful_count," successful"]}),i.jsxs("span",{className:"text-red-400",children:[t.success_correlation.failed_count," failed"]})]}),t.success_correlation.insights&&t.success_correlation.insights.length>0?i.jsx("div",{className:"space-y-2",children:t.success_correlation.insights.map(e=>i.jsxs("div",{className:"text-sm p-2 bg-bambu-dark-secondary rounded",children:[i.jsxs("span",{className:"text-white font-medium",children:[e.label,":"]})," ",i.jsx("span",{className:"text-white/80",children:e.insight})]},e.field))}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No clear correlations found between settings and outcomes."})]}):i.jsx("div",{className:"p-4 bg-bambu-dark rounded-lg text-sm text-bambu-gray",children:i.jsx("p",{children:t.success_correlation.message||"Need both successful and failed prints for correlation analysis."})})]})}function iYe(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),a=Math.floor(r/6e4);if(a<1)return"Just now";if(a<60)return`${a}m ago`;const s=Math.floor(a/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function sYe({upload:t,projects:e,onArchive:n,onDiscard:r,isArchiving:a,isDiscarding:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(t.tags||""),[d,h]=w.useState(t.notes||""),[f,p]=w.useState(t.project_id),[x,v]=w.useState(!1);return i.jsx(wt,{children:i.jsxs(_t,{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(hf,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:t.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[i.jsx("span",{children:ul(t.file_size)}),i.jsx("span",{children:"·"}),i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),iYe(t.uploaded_at)]}),t.source_ip&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"·"}),i.jsxs("span",{children:["from ",t.source_ip]})]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{onClick:()=>l(!o),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:o?i.jsx(yl,{className:"w-5 h-5"}):i.jsx(Pn,{className:"w-5 h-5"})}),i.jsx(Ce,{variant:"primary",size:"sm",onClick:()=>n(t.id,{tags:c,notes:d,project_id:f||void 0}),disabled:a,children:a?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(js,{className:"w-4 h-4"}),"Archive"]})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>v(!0),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4 text-red-400"})})]})]}),x&&i.jsx(gn,{title:"Discard Upload",message:`Are you sure you want to discard "${t.filename}"? This cannot be undone.`,confirmText:"Discard",variant:"danger",onConfirm:()=>{r(t.id),v(!1)},onCancel:()=>v(!1)}),o&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),i.jsx("input",{type:"text",value:c,onChange:g=>u(g.target.value),placeholder:"e.g., functional, prototype, gift",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),i.jsx("textarea",{value:d,onChange:g=>h(g.target.value),placeholder:"Add notes about this print...",rows:2,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray text-sm resize-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Project"}),i.jsxs("select",{value:f||"",onChange:g=>p(g.target.value?Number(g.target.value):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm",children:[i.jsx("option",{value:"",children:"No project"}),e.map(g=>i.jsx("option",{value:g.id,children:g.name},g.id))]})]})]})]})})}function oYe(){const t=en(),{showToast:e}=an(),[n,r]=w.useState(!1),[a,s]=w.useState(!1),[o,l]=w.useState(new Set),[c,u]=w.useState(new Set),{data:d,isLoading:h}=Je({queryKey:["pending-uploads"],queryFn:Eg.list,refetchInterval:1e4}),{data:f}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),p=st({mutationFn:({id:y,data:_})=>Eg.archive(y,_),onMutate:({id:y})=>{l(_=>new Set(_).add(y))},onSettled:(y,_,{id:N})=>{l(k=>{const A=new Set(k);return A.delete(N),A})},onSuccess:y=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived: ${y.print_name}`)},onError:y=>{e(y.message||"Failed to archive","error")}}),x=st({mutationFn:y=>Eg.discard(y),onMutate:y=>{u(_=>new Set(_).add(y))},onSettled:(y,_,N)=>{u(k=>{const A=new Set(k);return A.delete(N),A})},onSuccess:()=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e("Upload discarded")},onError:y=>{e(y.message||"Failed to discard","error")}}),v=st({mutationFn:Eg.archiveAll,onSuccess:y=>{t.invalidateQueries({queryKey:["pending-uploads"]}),t.invalidateQueries({queryKey:["archives"]}),e(`Archived ${y.archived} files${y.failed>0?`, ${y.failed} failed`:""}`)},onError:y=>{e(y.message||"Failed to archive all","error")}}),g=st({mutationFn:Eg.discardAll,onSuccess:y=>{t.invalidateQueries({queryKey:["pending-uploads"]}),e(`Discarded ${y.discarded} files`)},onError:y=>{e(y.message||"Failed to discard all","error")}});return h?i.jsx(wt,{children:i.jsx(_t,{className:"py-8 flex justify-center",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})})}):!d||d.length===0?null:i.jsxs("div",{className:"mb-6",children:[i.jsxs(wt,{className:"border-l-4 border-l-yellow-500",children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ra,{className:"w-5 h-5 text-yellow-500"}),i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Pending Uploads (",d.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"primary",size:"sm",onClick:()=>r(!0),disabled:v.isPending,children:v.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(js,{className:"w-4 h-4"}),"Archive All"]})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>s(!0),disabled:g.isPending,children:g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsxs(i.Fragment,{children:[i.jsx(Jt,{className:"w-4 h-4"}),"Discard All"]})})]})]})}),i.jsxs(_t,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"These files were uploaded via the virtual printer. Review and archive them to add to your collection."}),i.jsx("div",{className:"space-y-3",children:d.map(y=>i.jsx(sYe,{upload:y,projects:f||[],onArchive:(_,N)=>p.mutate({id:_,data:N}),onDiscard:_=>x.mutate(_),isArchiving:o.has(y.id),isDiscarding:c.has(y.id)},y.id))})]})]}),n&&i.jsx(gn,{title:"Archive All Uploads",message:`Are you sure you want to archive all ${d.length} pending uploads?`,confirmText:"Archive All",onConfirm:()=>{v.mutate(),r(!1)},onCancel:()=>r(!1)}),a&&i.jsx(gn,{title:"Discard All Uploads",message:`Are you sure you want to discard all ${d.length} pending uploads? This cannot be undone.`,confirmText:"Discard All",variant:"danger",onConfirm:()=>{g.mutate(),s(!1)},onCancel:()=>s(!1)})]})}function lYe({onClose:t}){const e=en(),{showToast:n}=an(),[r,a]=w.useState(""),[s,o]=w.useState(null),[l,c]=w.useState(""),[u,d]=w.useState(null),[h,f]=w.useState("count");w.useEffect(()=>{const P=E=>{E.key==="Escape"&&(s?o(null):u?d(null):t())};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,s,u]);const{data:p,isLoading:x}=Je({queryKey:["tags"],queryFn:ne.getTags}),v=st({mutationFn:({oldName:P,newName:E})=>ne.renameTag(P,E),onSuccess:(P,{oldName:E,newName:U})=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Renamed "${E}" to "${U}" in ${P.affected} archive${P.affected!==1?"s":""}`),o(null)},onError:P=>{n(P.message||"Failed to rename tag","error")}}),g=st({mutationFn:P=>ne.deleteTag(P),onSuccess:(P,E)=>{e.invalidateQueries({queryKey:["tags"]}),e.invalidateQueries({queryKey:["archives"]}),n(`Deleted "${E}" from ${P.affected} archive${P.affected!==1?"s":""}`),d(null)},onError:P=>{n(P.message||"Failed to delete tag","error")}}),y=P=>{o(P.name),c(P.name),d(null)},_=()=>{o(null),c("")},N=()=>{if(!s||!l.trim())return;const P=l.trim();if(P===s){_();return}v.mutate({oldName:s,newName:P})},k=P=>{P.key==="Enter"?(P.preventDefault(),N()):P.key==="Escape"&&(P.preventDefault(),_())},A=P=>{d(P),o(null)},M=()=>{u&&g.mutate(u)},C=p?.filter(P=>P.name.toLowerCase().includes(r.toLowerCase())).sort((P,E)=>h==="count"&&E.count-P.count||P.name.localeCompare(E.name)),j=p?.reduce((P,E)=>P+E.count,0)||0;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-lg max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Manage Tags"})]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search tags...",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:r,onChange:P=>a(P.target.value)})]}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:h,onChange:P=>f(P.target.value),children:[i.jsx("option",{value:"count",children:"Sort by Count"}),i.jsx("option",{value:"name",children:"Sort by Name"})]})]}),p&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[p.length," tag",p.length!==1?"s":""," across ",j," usage",j!==1?"s":""]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 p-4",children:x?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):C?.length?i.jsx("div",{className:"space-y-2",children:C.map(P=>i.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors group",children:s===P.name?i.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[i.jsx("input",{type:"text",className:"flex-1 px-2 py-1 bg-bambu-dark-tertiary border border-bambu-green rounded text-white text-sm focus:outline-none",value:l,onChange:E=>c(E.target.value),onKeyDown:k,autoFocus:!0}),i.jsx(Ce,{size:"sm",variant:"primary",onClick:N,disabled:!l.trim()||v.isPending,className:"p-1.5",children:v.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(aa,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:_,className:"p-1.5",children:i.jsx(Lt,{className:"w-4 h-4"})})]}):u===P.name?i.jsxs("div",{className:"flex-1 flex items-center gap-2",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),i.jsxs("span",{className:"text-sm text-bambu-gray-light flex-1",children:['Delete "',P.name,'" from ',P.count," archive",P.count!==1?"s":"","?"]}),i.jsx(Ce,{size:"sm",variant:"danger",onClick:M,disabled:g.isPending,className:"p-1.5",children:g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>d(null),className:"p-1.5",children:i.jsx(Lt,{className:"w-4 h-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(Vh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-white flex-1 truncate",children:P.name}),i.jsx("span",{className:"px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-xs",children:P.count}),i.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[i.jsx("button",{onClick:()=>y(P),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",title:"Rename tag",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>A(P.name),className:"p-1.5 rounded hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",title:"Delete tag",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})},P.name))}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:r?"No tags match your search":"No tags found"})}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:"Close"})})]})})})}function xh(t){if(!t)return!1;const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function pie(t){if(!t)return;const e=t.toLowerCase();return e.endsWith(".3mf")?"3mf":e.endsWith(".stl")?"stl":e.endsWith(".gcode")||e.includes(".gcode.")?"gcode":e.split(".").pop()}async function yh(t,e,n,r){try{if(n==="source"){const{token:a}=await ne.createSourceSlicerToken(t),s=ne.getSourceSlicerDownloadUrl(t,a,e);of(`${window.location.origin}${s}`,r)}else{const{token:a}=await ne.createArchiveSlicerToken(t),s=ne.getArchiveSlicerDownloadUrl(t,a,e);of(`${window.location.origin}${s}`,r)}}catch{const a=n==="source"?ne.getSource3mfForSlicer(t,e):ne.getArchiveForSlicer(t,e);of(`${window.location.origin}${a}`,r)}}function cYe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:a,projects:s,isHighlighted:o,timeFormat:l="system",preferredSlicer:c="bambu_studio",currency:u,t:d}){o&&console.log("ArchiveCard isHighlighted=true for archive:",t.id);const h=en(),{showToast:f}=an(),{hasPermission:p,canModify:x}=Ir(),v=xne(),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(!1),[M,C]=w.useState(!1),[j,P]=w.useState(!1),[E,U]=w.useState(!1),[L,B]=w.useState([]),[D,$]=w.useState(!1),[G,z]=w.useState(!1),[W,X]=w.useState(!1),[ae,H]=w.useState(!1),[K,te]=w.useState(!1),[Z,ve]=w.useState(!1),[ce,ee]=w.useState(!1),[je,he]=w.useState(null),[oe,_e]=w.useState(null),[ie,ze]=w.useState(!1),V=w.useRef(null),Y=w.useRef(null),me=w.useRef(null),{data:Q}=Je({queryKey:["archive-plates",t.id],queryFn:()=>ne.getArchivePlates(t.id),enabled:ie,staleTime:300*1e3}),se=Q?.plates??[],de=Q?.is_multi_plate??!1,Le=oe??0,Ne=st({mutationFn:()=>ne.deleteArchiveTimelapse(t.id),onSuccess:()=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseRemoved"))},onError:ge=>{f(ge.message||d("archives.toast.failedRemoveTimelapse"),"error")}}),be=st({mutationFn:ge=>ne.uploadArchiveTimelapse(t.id,ge),onSuccess:ge=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseUploaded",{filename:ge.filename}))},onError:ge=>{f(ge.message||d("archives.toast.failedUploadTimelapse"),"error")}}),O=st({mutationFn:ge=>ne.uploadSource3mf(t.id,ge),onSuccess:ge=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.source3mfAttached",{filename:ge.filename}))},onError:ge=>{f(ge.message||d("archives.toast.failedUploadSource3mf"),"error")}}),R=st({mutationFn:()=>ne.deleteSource3mf(t.id),onSuccess:()=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.source3mfRemoved"))},onError:ge=>{f(ge.message||d("archives.toast.failedRemoveSource3mf"),"error")}}),q=st({mutationFn:ge=>ne.uploadF3d(t.id,ge),onSuccess:ge=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.f3dAttached",{filename:ge.filename}))},onError:ge=>{f(ge.message||d("archives.toast.failedUploadF3d"),"error")}}),J=st({mutationFn:()=>ne.deleteF3d(t.id),onSuccess:()=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.f3dRemoved"))},onError:ge=>{f(ge.message||d("archives.toast.failedRemoveF3d"),"error")}}),fe=st({mutationFn:()=>ne.scanArchiveTimelapse(t.id),onSuccess:ge=>{ge.status==="attached"?(h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseAttached",{filename:ge.filename}))):ge.status==="exists"?f(d("archives.toast.timelapseAlreadyAttached")):ge.status==="not_found"&&ge.available_files&&ge.available_files.length>0?(B(ge.available_files),U(!0)):f(ge.message||d("archives.toast.noMatchingTimelapse"),"warning")},onError:ge=>{f(ge.message||d("archives.toast.failedScanTimelapse"),"error")}}),le=st({mutationFn:ge=>ne.selectArchiveTimelapse(t.id,ge),onSuccess:ge=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.timelapseAttached",{filename:ge.filename})),U(!1),B([])},onError:ge=>{f(ge.message||d("archives.toast.failedAttachTimelapse"),"error")}}),Be=st({mutationFn:()=>ne.deleteArchive(t.id),onSuccess:()=>{h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.archiveDeleted"))},onError:()=>{f(d("archives.toast.failedDeleteArchive"),"error")}}),Ie=st({mutationFn:()=>ne.toggleFavorite(t.id),onSuccess:ge=>{h.invalidateQueries({queryKey:["archives"]}),f(ge.is_favorite?d("archives.toast.addedToFavorites"):d("archives.toast.removedFromFavorites"))}}),{data:Ke}=Je({queryKey:["archive-folders",t.id],queryFn:()=>ne.getLibraryFoldersByArchive(t.id)}),Oe=st({mutationFn:ge=>ne.updateArchive(t.id,{project_id:ge}),onSuccess:()=>{h.invalidateQueries({queryKey:["archives"]}),h.invalidateQueries({queryKey:["projects"]}),f(d("archives.toast.projectUpdated"))},onError:()=>{f(d("archives.toast.failedUpdateProject"),"error")}}),pe=ge=>{ge.preventDefault(),he({x:ge.clientX,y:ge.clientY})},ke=[...xh(t.filename)?[{label:d("archives.menu.print"),icon:i.jsx(gr,{className:"w-4 h-4"}),onClick:()=>N(!0),disabled:!t.file_path||!x("archives","reprint",t.created_by_id),title:t.file_path?x("archives","reprint",t.created_by_id)?void 0:d("archives.permission.noReprint"):d("archives.card.noFileForReprint")},{label:d("archives.menu.schedule"),icon:i.jsx(ra,{className:"w-4 h-4"}),onClick:()=>H(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?void 0:d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint")},{label:d("archives.menu.openInBambuStudio"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const ge=t.print_name||t.filename||"model";yh(t.id,ge,"file",c)},disabled:!t.file_path,title:t.file_path?void 0:d("archives.card.noFileForReprint")}]:[{label:d("archives.menu.slice"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const ge=t.print_name||t.filename||"model";yh(t.id,ge,"file",c)}}],{label:t.external_url?d("archives.menu.externalLink"):d("archives.menu.viewOnMakerWorld"),icon:i.jsx(Ph,{className:"w-4 h-4"}),onClick:()=>{const ge=t.external_url||t.makerworld_url;ge&&window.open(ge,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.preview3d"),icon:i.jsx(Ja,{className:"w-4 h-4"}),onClick:()=>y(!0)},{label:d("archives.menu.viewTimelapse"),icon:i.jsx(Mh,{className:"w-4 h-4"}),onClick:()=>P(!0),disabled:!t.timelapse_path},{label:d("archives.menu.scanForTimelapse"),icon:i.jsx(C1,{className:"w-4 h-4"}),onClick:()=>fe.mutate(),disabled:!t.printer_id||!!t.timelapse_path||fe.isPending||!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.uploadTimelapse"),icon:i.jsx(Ra,{className:"w-4 h-4"}),onClick:()=>me.current?.click(),disabled:!!t.timelapse_path||!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:d("archives.menu.removeTimelapse"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>ee(!0),danger:!0,disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?d("archives.menu.downloadSource3mf"):d("archives.menu.uploadSource3mf"),icon:i.jsx(w1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ne.downloadSource3mf(t.id).catch(ge=>{console.error("Source 3MF download failed:",ge)}):V.current?.click()},disabled:!t.source_3mf_path&&!x("archives","update",t.created_by_id),title:!t.source_3mf_path&&!x("archives","update",t.created_by_id)?d("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:d("archives.menu.replaceSource3mf"),icon:i.jsx(Ra,{className:"w-4 h-4"}),onClick:()=>V.current?.click(),disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.removeSource3mf"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>te(!0),danger:!0,disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?d("archives.menu.replaceF3d"):d("archives.menu.uploadF3d"),icon:i.jsx(Ja,{className:"w-4 h-4"}),onClick:()=>Y.current?.click(),disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:d("archives.menu.downloadF3d"),icon:i.jsx(da,{className:"w-4 h-4"}),onClick:()=>{ne.downloadF3d(t.id).catch(ge=>{console.error("F3D download failed:",ge)})}},{label:d("archives.menu.removeF3d"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>ve(!0),danger:!0,disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.download"),icon:i.jsx(da,{className:"w-4 h-4"}),onClick:()=>{ne.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ge=>{console.error("Archive download failed:",ge)})},disabled:!p("archives:read"),title:p("archives:read")?void 0:d("archives.permission.noDownload")},{label:d("archives.menu.copyDownloadLink"),icon:i.jsx(Yl,{className:"w-4 h-4"}),onClick:()=>{const ge=`${window.location.origin}${ne.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(ge).then(()=>{f(d("archives.toast.linkCopied"))}).catch(()=>{f(d("archives.toast.failedCopyLink"),"error")})},disabled:!p("archives:read"),title:p("archives:read")?void 0:d("archives.permission.noCopyLink")},{label:d("archives.menu.qrCode"),icon:i.jsx(vX,{className:"w-4 h-4"}),onClick:()=>$(!0)},{label:t.photos?.length?d("archives.menu.viewPhotosCount",{count:t.photos.length}):d("archives.menu.viewPhotos"),icon:i.jsx(cb,{className:"w-4 h-4"}),onClick:()=>z(!0),disabled:!t.photos?.length},{label:d("archives.menu.projectPage"),icon:i.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>X(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?d("archives.menu.removeFromFavorites"):d("archives.menu.addToFavorites"),icon:i.jsx(Ef,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>Ie.mutate(),disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},{label:d("archives.menu.edit"),icon:i.jsx($a,{className:"w-4 h-4"}),onClick:()=>C(!0),disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:d("archives.menu.goToProject",{name:t.project_name}),icon:i.jsx(gs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:d("archives.menu.addToProject"),icon:i.jsx(gs,{className:"w-4 h-4"}),onClick:()=>{},disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?void 0:d("archives.permission.noUpdateArchives"),submenu:(()=>{const ge=[];if(t.project_id&&ge.push({label:d("archives.menu.removeFromProject"),icon:i.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>Oe.mutate(null),disabled:!x("archives","update",t.created_by_id)}),!s)ge.push({label:d("archives.menu.loading"),icon:i.jsx(it,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const we=s.filter(qe=>qe.status==="active");we.length===0?ge.push({label:d("archives.menu.noProjectsAvailable"),icon:i.jsx(gs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):we.forEach(qe=>{ge.push({label:qe.name,icon:i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:qe.color||"#888"}}),onClick:()=>Oe.mutate(qe.id),disabled:t.project_id===qe.id||!x("archives","update",t.created_by_id)})})}return ge})()},{label:d(n?"archives.menu.deselect":"archives.menu.select"),icon:n?i.jsx(oo,{className:"w-4 h-4"}):i.jsx(vl,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:d("archives.menu.delete"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>A(!0),danger:!0,disabled:!x("archives","delete",t.created_by_id),title:x("archives","delete",t.created_by_id)?void 0:d("archives.permission.noDelete")}];return i.jsxs(wt,{"data-archive-id":t.id,className:`relative flex flex-col group ${n?"ring-2 ring-bambu-green":""} ${a?"cursor-pointer":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,onContextMenu:pe,onClick:a?()=>r(t.id):void 0,children:[a&&i.jsx("button",{className:"absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors",onClick:ge=>{ge.stopPropagation(),r(t.id)},children:n?i.jsx(oo,{className:"w-5 h-5 text-bambu-green"}):i.jsx(vl,{className:"w-5 h-5 text-white"})}),i.jsxs("div",{className:"aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl",onMouseEnter:()=>ze(!0),onMouseLeave:()=>ze(!1),children:[t.thumbnail_path?i.jsx("img",{src:oe!==null&&se.length>0?ne.getArchivePlateThumbnail(t.id,se[Le]?.index??0):ne.getArchiveThumbnail(t.id),alt:t.print_name||t.filename,className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(Ju,{className:"w-12 h-12 text-bambu-dark-tertiary"})}),de&&se.length>1&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${v?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:ge=>{ge.stopPropagation(),_e(we=>{const qe=we??0;return qe>0?qe-1:se.length-1})},title:d("archives.card.previousPlate"),children:i.jsx(Xl,{className:"w-4 h-4 text-white"})}),i.jsx("button",{className:`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${v?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:ge=>{ge.stopPropagation(),_e(we=>{const qe=we??0;return qe<se.length-1?qe+1:0})},title:d("archives.card.nextPlate"),children:i.jsx(pi,{className:"w-4 h-4 text-white"})}),i.jsx("div",{className:`absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-1 px-2 py-1 rounded-full bg-black/50 transition-all ${v?"opacity-100":"opacity-0 group-hover:opacity-100"}`,children:se.map((ge,we)=>i.jsx("button",{className:`w-2 h-2 rounded-full transition-colors ${we===Le?"bg-bambu-green":"bg-white/50 hover:bg-white/80"}`,onClick:qe=>{qe.stopPropagation(),_e(we)},title:ge.name||d("archives.card.plateNumber",{index:ge.index})},ge.index))})]}),i.jsx("button",{className:`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${v?"opacity-100":"opacity-0 group-hover:opacity-100"} ${a?"left-10":""}`,onClick:ge=>{ge.stopPropagation();const we=ge.currentTarget.getBoundingClientRect();he({x:we.left,y:we.bottom+4})},title:d("archives.card.moreOptions"),children:i.jsx(Th,{className:"w-5 h-5 text-white"})}),i.jsx("button",{className:`absolute top-2 right-2 p-1 rounded transition-colors ${x("archives","update",t.created_by_id)?"bg-black/50 hover:bg-black/70":"bg-black/30 cursor-not-allowed"}`,onClick:ge=>{ge.stopPropagation(),x("archives","update",t.created_by_id)&&Ie.mutate()},disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?t.is_favorite?d("archives.card.removeFromFavorites"):d("archives.card.addToFavorites"):d("archives.permission.noUpdateArchives"),children:i.jsx(Ef,{className:`w-5 h-5 ${t.is_favorite?"text-yellow-400 fill-yellow-400":"text-white"} ${x("archives","update",t.created_by_id)?"":"opacity-50"}`})}),(t.status==="failed"||t.status==="aborted")&&i.jsx("div",{className:"absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white",children:t.status==="aborted"?d("archives.card.cancelled"):d("archives.card.failed")}),t.duplicate_count>0&&i.jsxs("div",{className:"absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1",title:d("archives.card.duplicateTitle"),children:[i.jsx(Yl,{className:"w-3 h-3"}),d("archives.card.duplicate")]}),t.source_3mf_path&&i.jsx("button",{className:"absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ge=>{ge.stopPropagation();const we=(t.print_name||t.filename||"source").replace(/\.gcode\.3mf$/i,"")+"_source";yh(t.id,we,"source",c)},title:d("archives.card.openSource3mf"),children:i.jsx(w1,{className:"w-4 h-4 text-orange-400"})}),t.f3d_path&&i.jsx("button",{className:`absolute bottom-2 ${t.source_3mf_path?"left-12":"left-2"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:ge=>{ge.stopPropagation(),ne.downloadF3d(t.id).catch(we=>{console.error("F3D download failed:",we)})},title:d("archives.card.downloadF3d"),children:i.jsx(Ja,{className:"w-4 h-4 text-cyan-400"})}),i.jsx("button",{className:"absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ge=>{ge.stopPropagation(),y(!0)},title:d("archives.card.preview3d"),children:i.jsx(fi,{className:"w-4 h-4 text-white"})}),t.timelapse_path&&i.jsx("button",{className:"absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ge=>{ge.stopPropagation(),P(!0)},title:d("archives.card.viewTimelapse"),children:i.jsx(Mh,{className:"w-4 h-4 text-bambu-green"})}),t.photos&&t.photos.length>0&&i.jsxs("button",{className:`absolute bottom-2 ${t.timelapse_path?"right-[5.5rem]":"right-12"} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`,onClick:ge=>{ge.stopPropagation(),z(!0)},title:t.photos.length===1?d("archives.card.viewPhoto"):d("archives.card.viewPhotos",{count:t.photos.length}),children:[i.jsx(cb,{className:"w-4 h-4 text-blue-400"}),t.photos.length>1&&i.jsx("span",{className:"absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center",children:t.photos.length})]}),Ke&&Ke.length>0&&i.jsx(Ks,{to:`/files?folder=${Ke[0].id}`,className:"absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors",onClick:ge=>ge.stopPropagation(),title:d("archives.card.openFolder",{name:Ke[0].name}),style:{left:t.source_3mf_path?t.f3d_path?"5.5rem":"3rem":t.f3d_path?"3rem":"0.5rem"},children:i.jsx(Zl,{className:"w-4 h-4 text-yellow-400"})})]}),i.jsxs(_t,{className:"p-4 flex-1 flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[i.jsx("h3",{className:"min-w-0 font-medium text-white truncate",children:t.print_name||t.filename}),i.jsx(Ce,{variant:"ghost",size:"sm",className:"p-1 sm:p-1.5 shrink-0",onClick:()=>C(!0),disabled:!x("archives","update",t.created_by_id),title:x("archives","update",t.created_by_id)?d("archives.card.edit"):d("archives.card.noPermissionEdit"),children:i.jsx($a,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2 mb-3 flex-wrap",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:e}),i.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${xh(t.filename)?"bg-bambu-green/20 text-bambu-green":"bg-orange-500/20 text-orange-400"}`,title:xh(t.filename)?d("archives.card.slicedFile"):d("archives.card.sourceFile"),children:xh(t.filename)?d("archives.card.gcode"):d("archives.card.source")}),t.project_name&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]",style:{backgroundColor:`${s?.find(ge=>ge.id===t.project_id)?.color||"#6b7280"}20`,color:s?.find(ge=>ge.id===t.project_id)?.color||"#6b7280"},title:d("archives.card.project",{name:t.project_name}),children:t.project_name})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]",children:[(t.print_time_seconds||t.actual_time_seconds)&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.time_accuracy?`Estimated: ${Qs(t.print_time_seconds||0)}
  8286. Actual: ${Qs(t.actual_time_seconds||0)}
  8287. Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Qs(t.actual_time_seconds)}`:`Estimated: ${Qs(t.print_time_seconds||0)}`,children:[i.jsx(Wn,{className:"w-3 h-3"}),Qs(t.actual_time_seconds||t.print_time_seconds||0),t.time_accuracy&&i.jsxs("span",{className:`text-[10px] px-1 rounded ${t.time_accuracy>=95&&t.time_accuracy<=105?"bg-bambu-green/20 text-bambu-green":t.time_accuracy>105?"bg-blue-500/20 text-blue-400":"bg-orange-500/20 text-orange-400"}`,children:[t.time_accuracy>100?"+":"",(t.time_accuracy-100).toFixed(0),"%"]})]}),t.filament_used_grams&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(ni,{className:"w-3 h-3"}),t.filament_used_grams.toFixed(1),"g"]}),t.cost!=null&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(Ohe,{className:"w-3 h-3"}),u,t.cost.toFixed(2)]}),(t.layer_height||t.total_layers)&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(fi,{className:"w-3 h-3"}),t.total_layers&&i.jsx("span",{children:t.total_layers===1?d("archives.card.layer",{count:t.total_layers}):d("archives.card.layers",{count:t.total_layers})}),t.total_layers&&t.layer_height&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.layer_height&&i.jsxs("span",{children:[t.layer_height,"mm"]})]}),t.object_count!=null&&t.object_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count}),children:[i.jsx(Ja,{className:"w-3 h-3"}),t.object_count===1?d("archives.card.object",{count:t.object_count}):d("archives.card.objects",{count:t.object_count})]}),t.sliced_for_model&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",title:d("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(gr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.filament_type&&i.jsxs("div",{className:"flex items-center gap-1.5 col-span-2",children:[i.jsx("span",{className:"text-bambu-gray text-xs",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((ge,we)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:ge},title:ge},we))})]})]}),(t.tags||t.notes)&&i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[t.notes&&i.jsx("div",{className:"flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs",title:t.notes,children:i.jsx(SX,{className:"w-3 h-3"})}),t.tags?.split(",").map((ge,we)=>i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs",children:ge.trim()},we))]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3",children:[i.jsx("span",{children:Rf(t.created_at,l)}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.created_by_username&&i.jsxs("span",{className:"flex items-center gap-1",title:d("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]}),i.jsx("span",{children:ul(t.file_size)})]})]}),i.jsxs("div",{className:"flex gap-1 mt-3",children:[xh(t.filename)?i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>N(!0),disabled:!t.file_path||!x("archives","reprint",t.created_by_id),title:t.file_path?x("archives","reprint",t.created_by_id)?void 0:d("archives.card.noPermissionReprint"):d("archives.card.noFileForReprint"),children:[i.jsx(gr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline",children:d("archives.card.reprint")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",className:"flex-1 min-w-0",onClick:()=>H(!0),disabled:!t.file_path||!p("queue:create"),title:t.file_path?p("queue:create")?d("archives.card.schedulePrint"):d("archives.permission.noAddToQueue"):d("archives.card.noFileForReprint"),children:[i.jsx(ra,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline",children:d("archives.card.schedule")})]}),i.jsx(Ce,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ge=t.print_name||t.filename||"model";yh(t.id,ge,"file",c)},title:d("archives.card.openInBambuStudio"),children:i.jsx(Xr,{className:"w-3 h-3 sm:w-4 sm:h-4"})})]}):i.jsxs(Ce,{variant:"primary",size:"sm",className:"flex-1 min-w-0",onClick:()=>{const ge=t.print_name||t.filename||"model";yh(t.id,ge,"file",c)},title:d("archives.card.openInBambuStudioToSlice"),children:[i.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"hidden sm:inline",children:d("archives.card.slice")})]}),i.jsx(Ce,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{const ge=t.external_url||t.makerworld_url;ge&&window.open(ge,"_blank")},disabled:!t.external_url&&!t.makerworld_url,title:t.external_url?d("archives.card.externalLink"):t.makerworld_url?d("archives.card.makerWorld",{designer:t.designer||d("archives.card.viewProject")}):d("archives.card.noExternalLink"),children:i.jsx(Ph,{className:`w-3 h-3 sm:w-4 sm:h-4 ${!t.external_url&&!t.makerworld_url?"opacity-20":""}`})}),i.jsx(Ce,{variant:"secondary",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>{ne.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(ge=>{console.error("Archive download failed:",ge)})},title:d("archives.card.download"),children:i.jsx(da,{className:"w-3 h-3 sm:w-4 sm:h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",className:"min-w-0 p-1 sm:p-1.5",onClick:()=>A(!0),disabled:!x("archives","delete",t.created_by_id),title:x("archives","delete",t.created_by_id)?d("archives.card.delete"):d("archives.card.noPermissionDelete"),children:i.jsx(Jt,{className:"w-3 h-3 sm:w-4 sm:h-4 text-red-400"})})]})]}),M&&i.jsx(vne,{archive:t,onClose:()=>C(!1)}),g&&i.jsx(g4,{archiveId:t.id,title:t.print_name||t.filename,fileType:pie(t.filename),onClose:()=>y(!1)}),_&&i.jsx(Xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>N(!1)}),k&&i.jsx(gn,{title:d("archives.modal.deleteArchive"),message:d("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{Be.mutate(),A(!1)},onCancel:()=>A(!1)}),K&&i.jsx(gn,{title:d("archives.modal.removeSource3mf"),message:d("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{R.mutate(),te(!1)},onCancel:()=>te(!1)}),Z&&i.jsx(gn,{title:d("archives.modal.removeF3d"),message:d("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{J.mutate(),ve(!1)},onCancel:()=>ve(!1)}),ce&&i.jsx(gn,{title:d("archives.modal.removeTimelapse"),message:d("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:d("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Ne.mutate(),ee(!1)},onCancel:()=>ee(!1)}),je&&i.jsx(wne,{x:je.x,y:je.y,items:ke,onClose:()=>he(null)}),j&&t.timelapse_path&&i.jsx(fie,{src:ne.getArchiveTimelapse(t.id),title:d("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>P(!1),onEdit:()=>{h.invalidateQueries({queryKey:["archives"]}),P(!1)}}),E&&L.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:d("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:d("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{U(!1),B([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:L.map(ge=>i.jsxs("button",{onClick:()=>le.mutate(ge.name),disabled:le.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50",children:[i.jsx(Mh,{className:"w-8 h-8 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ge.name}),i.jsxs("p",{className:"text-sm text-gray-400",children:[ul(ge.size),ge.mtime&&` • ${Rf(ge.mtime,l)}`]})]})]},ge.name))}),i.jsx("div",{className:"p-4 border-t border-gray-700",children:i.jsx(Ce,{variant:"secondary",onClick:()=>{U(!1),B([])},className:"w-full",children:"Cancel"})})]})}),D&&i.jsx(Sne,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>$(!1)}),G&&t.photos&&t.photos.length>0&&i.jsx(_ne,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>z(!1),onDelete:async ge=>{try{await ne.deleteArchivePhoto(t.id,ge),h.invalidateQueries({queryKey:["archives"]}),f(d("archives.toast.photoDeleted"))}catch{f(d("archives.toast.failedDeletePhoto"),"error")}}}),W&&i.jsx(mie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>X(!1)}),ae&&i.jsx(Xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>H(!1)}),i.jsx("input",{ref:V,type:"file",accept:".3mf",className:"hidden",onChange:ge=>{const we=ge.target.files?.[0];we&&O.mutate(we),ge.target.value=""}}),i.jsx("input",{ref:Y,type:"file",accept:".f3d",className:"hidden",onChange:ge=>{const we=ge.target.files?.[0];we&&q.mutate(we),ge.target.value=""}}),i.jsx("input",{ref:me,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:ge=>{const we=ge.target.files?.[0];we&&be.mutate(we),ge.target.value=""}})]})}function uYe({archive:t,printerName:e,isSelected:n,onSelect:r,selectionMode:a,projects:s,isHighlighted:o,preferredSlicer:l="bambu_studio",t:c}){const u=en(),{showToast:d}=an(),{hasPermission:h,canModify:f}=Ir(),[p,x]=w.useState(!1),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[U,L]=w.useState([]),[B,D]=w.useState(!1),[$,G]=w.useState(!1),[z,W]=w.useState(!1),[X,ae]=w.useState(!1),[H,K]=w.useState(!1),[te,Z]=w.useState(!1),[ve,ce]=w.useState(null),ee=w.useRef(null),je=w.useRef(null),he=w.useRef(null),oe=st({mutationFn:()=>ne.deleteArchiveTimelapse(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseRemoved"))},onError:q=>{d(q.message||c("archives.toast.failedRemoveTimelapse"),"error")}}),_e=st({mutationFn:q=>ne.uploadArchiveTimelapse(t.id,q),onSuccess:q=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseUploaded",{filename:q.filename}))},onError:q=>{d(q.message||c("archives.toast.failedUploadTimelapse"),"error")}}),ie=st({mutationFn:q=>ne.uploadSource3mf(t.id,q),onSuccess:q=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfAttached",{filename:q.filename}))},onError:q=>{d(q.message||c("archives.toast.failedUploadSource3mf"),"error")}}),ze=st({mutationFn:()=>ne.deleteSource3mf(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.source3mfRemoved"))},onError:q=>{d(q.message||c("archives.toast.failedRemoveSource3mf"),"error")}}),V=st({mutationFn:q=>ne.uploadF3d(t.id,q),onSuccess:q=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dAttached",{filename:q.filename}))},onError:q=>{d(q.message||c("archives.toast.failedUploadF3d"),"error")}}),Y=st({mutationFn:()=>ne.deleteF3d(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.f3dRemoved"))},onError:q=>{d(q.message||c("archives.toast.failedRemoveF3d"),"error")}}),me=st({mutationFn:()=>ne.scanArchiveTimelapse(t.id),onSuccess:q=>{q.status==="attached"?(u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:q.filename}))):q.status==="exists"?d(c("archives.toast.timelapseAlreadyAttached")):q.status==="not_found"&&q.available_files&&q.available_files.length>0?(L(q.available_files),E(!0)):d(q.message||c("archives.toast.noMatchingTimelapse"),"warning")},onError:q=>{d(q.message||c("archives.toast.failedScanTimelapse"),"error")}}),Q=st({mutationFn:q=>ne.selectArchiveTimelapse(t.id,q),onSuccess:q=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.timelapseAttached",{filename:q.filename})),E(!1),L([])},onError:q=>{d(q.message||c("archives.toast.failedAttachTimelapse"),"error")}}),se=st({mutationFn:()=>ne.deleteArchive(t.id),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.archiveDeleted"))},onError:()=>{d(c("archives.toast.failedDeleteArchive"),"error")}}),de=st({mutationFn:()=>ne.toggleFavorite(t.id),onSuccess:q=>{u.invalidateQueries({queryKey:["archives"]}),d(q.is_favorite?c("archives.toast.addedToFavorites"):c("archives.toast.removedFromFavorites"))}}),{data:Le}=Je({queryKey:["archive-folders",t.id],queryFn:()=>ne.getLibraryFoldersByArchive(t.id)}),Ne=st({mutationFn:q=>ne.updateArchive(t.id,{project_id:q}),onSuccess:()=>{u.invalidateQueries({queryKey:["archives"]}),u.invalidateQueries({queryKey:["projects"]}),d(c("archives.toast.projectUpdated"))},onError:()=>{d(c("archives.toast.failedUpdateProject"),"error")}}),be=q=>{q.preventDefault(),ce({x:q.clientX,y:q.clientY})},R=[...xh(t.filename)?[{label:c("archives.menu.print"),icon:i.jsx(gr,{className:"w-4 h-4"}),onClick:()=>_(!0),disabled:!t.file_path||!f("archives","reprint",t.created_by_id),title:t.file_path?f("archives","reprint",t.created_by_id)?void 0:c("archives.permission.noReprint"):c("archives.card.noFileForReprint")},{label:c("archives.menu.schedule"),icon:i.jsx(ra,{className:"w-4 h-4"}),onClick:()=>k(!0),disabled:!t.file_path||!h("queue:create"),title:t.file_path?h("queue:create")?void 0:c("archives.permission.noAddToQueue"):c("archives.card.noFileForReprint")},{label:c("archives.menu.openInBambuStudio"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const q=t.print_name||t.filename||"model";yh(t.id,q,"file",l)},disabled:!t.file_path,title:t.file_path?void 0:c("archives.card.noFileForReprint")}]:[{label:c("archives.menu.slice"),icon:i.jsx(Xr,{className:"w-4 h-4"}),onClick:()=>{const q=t.print_name||t.filename||"model";yh(t.id,q,"file",l)}}],{label:t.external_url?c("archives.menu.externalLink"):c("archives.menu.viewOnMakerWorld"),icon:i.jsx(Ph,{className:"w-4 h-4"}),onClick:()=>{const q=t.external_url||t.makerworld_url;q&&window.open(q,"_blank")},disabled:!t.external_url&&!t.makerworld_url},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.preview3d"),icon:i.jsx(Ja,{className:"w-4 h-4"}),onClick:()=>M(!0)},{label:c("archives.menu.viewTimelapse"),icon:i.jsx(Mh,{className:"w-4 h-4"}),onClick:()=>j(!0),disabled:!t.timelapse_path},{label:c("archives.menu.scanForTimelapse"),icon:i.jsx(C1,{className:"w-4 h-4"}),onClick:()=>me.mutate(),disabled:!t.printer_id||!!t.timelapse_path||me.isPending||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.uploadTimelapse"),icon:i.jsx(Ra,{className:"w-4 h-4"}),onClick:()=>he.current?.click(),disabled:!!t.timelapse_path||!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.timelapse_path?[{label:c("archives.menu.removeTimelapse"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>Z(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:t.source_3mf_path?c("archives.menu.downloadSource3mf"):c("archives.menu.uploadSource3mf"),icon:i.jsx(w1,{className:"w-4 h-4"}),onClick:()=>{t.source_3mf_path?ne.downloadSource3mf(t.id).catch(q=>{console.error("Source 3MF download failed:",q)}):ee.current?.click()},disabled:!t.source_3mf_path&&!f("archives","update",t.created_by_id),title:!t.source_3mf_path&&!f("archives","update",t.created_by_id)?c("archives.permission.noUploadFiles"):void 0},...t.source_3mf_path?[{label:c("archives.menu.replaceSource3mf"),icon:i.jsx(Ra,{className:"w-4 h-4"}),onClick:()=>ee.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.removeSource3mf"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>ae(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:t.f3d_path?c("archives.menu.replaceF3d"):c("archives.menu.uploadF3d"),icon:i.jsx(Ja,{className:"w-4 h-4"}),onClick:()=>je.current?.click(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.f3d_path?[{label:c("archives.menu.downloadF3d"),icon:i.jsx(da,{className:"w-4 h-4"}),onClick:()=>{ne.downloadF3d(t.id).catch(q=>{console.error("F3D download failed:",q)})}},{label:c("archives.menu.removeF3d"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>K(!0),danger:!0,disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")}]:[],{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.download"),icon:i.jsx(da,{className:"w-4 h-4"}),onClick:()=>{ne.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(q=>{console.error("Archive download failed:",q)})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noDownload")},{label:c("archives.menu.copyDownloadLink"),icon:i.jsx(Yl,{className:"w-4 h-4"}),onClick:()=>{const q=`${window.location.origin}${ne.getArchiveDownload(t.id)}`;navigator.clipboard.writeText(q).then(()=>{d(c("archives.toast.linkCopied"))}).catch(()=>{d(c("archives.toast.failedCopyLink"),"error")})},disabled:!h("archives:read"),title:h("archives:read")?void 0:c("archives.permission.noCopyLink")},{label:c("archives.menu.qrCode"),icon:i.jsx(vX,{className:"w-4 h-4"}),onClick:()=>D(!0)},{label:t.photos?.length?c("archives.menu.viewPhotosCount",{count:t.photos.length}):c("archives.menu.viewPhotos"),icon:i.jsx(cb,{className:"w-4 h-4"}),onClick:()=>G(!0),disabled:!t.photos?.length},{label:c("archives.menu.projectPage"),icon:i.jsx(Ms,{className:"w-4 h-4"}),onClick:()=>W(!0)},{label:"",divider:!0,onClick:()=>{}},{label:t.is_favorite?c("archives.menu.removeFromFavorites"):c("archives.menu.addToFavorites"),icon:i.jsx(Ef,{className:`w-4 h-4 ${t.is_favorite?"fill-yellow-400 text-yellow-400":""}`}),onClick:()=>de.mutate(),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},{label:c("archives.menu.edit"),icon:i.jsx($a,{className:"w-4 h-4"}),onClick:()=>x(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?void 0:c("archives.permission.noUpdateArchives")},...t.project_id&&t.project_name?[{label:c("archives.menu.goToProject",{name:t.project_name}),icon:i.jsx(gs,{className:"w-4 h-4 text-bambu-green"}),onClick:()=>window.location.href="/projects"}]:[],{label:c("archives.menu.addToProject"),icon:i.jsx(gs,{className:"w-4 h-4"}),onClick:()=>{},submenu:(()=>{const q=[];if(t.project_id&&q.push({label:c("archives.menu.removeFromProject"),icon:i.jsx(Lt,{className:"w-4 h-4"}),onClick:()=>Ne.mutate(null)}),!s)q.push({label:c("archives.menu.loading"),icon:i.jsx(it,{className:"w-4 h-4 animate-spin"}),onClick:()=>{},disabled:!0});else{const J=s.filter(fe=>fe.status==="active");J.length===0?q.push({label:c("archives.menu.noProjectsAvailable"),icon:i.jsx(gs,{className:"w-4 h-4 opacity-50"}),onClick:()=>{},disabled:!0}):J.forEach(fe=>{q.push({label:fe.name,icon:i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:fe.color||"#888"}}),onClick:()=>Ne.mutate(fe.id),disabled:t.project_id===fe.id})})}return q})()},{label:c(n?"archives.menu.deselect":"archives.menu.select"),icon:n?i.jsx(oo,{className:"w-4 h-4"}):i.jsx(vl,{className:"w-4 h-4"}),onClick:()=>r(t.id)},{label:"",divider:!0,onClick:()=>{}},{label:c("archives.menu.delete"),icon:i.jsx(Jt,{className:"w-4 h-4"}),onClick:()=>g(!0),danger:!0,disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?void 0:c("archives.permission.noDelete")}];return i.jsxs(i.Fragment,{children:[i.jsxs("div",{"data-archive-id":t.id,className:`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${n?"bg-bambu-green/10":""}`,style:o?{outline:"4px solid #facc15",outlineOffset:"-4px"}:void 0,onContextMenu:be,children:[i.jsxs("div",{className:"col-span-1 flex items-center gap-2",children:[a&&i.jsx("button",{onClick:()=>r(t.id),children:n?i.jsx(oo,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4 text-bambu-gray"})}),t.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(t.id),alt:"",className:"w-10 h-10 object-cover rounded"}):i.jsx("div",{className:"w-10 h-10 bg-bambu-dark rounded flex items-center justify-center",children:i.jsx(Ju,{className:"w-5 h-5 text-bambu-dark-tertiary"})})]}),i.jsxs("div",{className:"col-span-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("p",{className:"text-white text-sm truncate",children:t.print_name||t.filename}),(t.status==="failed"||t.status==="aborted")&&i.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0",children:t.status==="aborted"?c("archives.card.cancelled"):c("archives.card.failed")}),t.timelapse_path&&i.jsx("span",{title:c("archives.list.hasTimelapse"),children:i.jsx(Mh,{className:"w-3.5 h-3.5 text-bambu-green flex-shrink-0"})}),Le&&Le.length>0&&i.jsx(Ks,{to:`/files?folder=${Le[0].id}`,className:"flex-shrink-0",title:c("archives.card.openFolder",{name:Le[0].name}),onClick:q=>q.stopPropagation(),children:i.jsx(Zl,{className:"w-3.5 h-3.5 text-yellow-400"})})]}),(t.filament_type||t.sliced_for_model)&&i.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[t.sliced_for_model&&i.jsxs("span",{className:"text-xs text-bambu-gray flex items-center gap-1",title:c("archives.card.slicedFor",{model:t.sliced_for_model}),children:[i.jsx(gr,{className:"w-2.5 h-2.5"}),t.sliced_for_model]}),t.sliced_for_model&&t.filament_type&&i.jsx("span",{className:"text-bambu-gray/50",children:"·"}),t.filament_type&&i.jsx("span",{className:"text-xs text-bambu-gray",children:t.filament_type}),t.filament_color&&i.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.filament_color.split(",").map((q,J)=>i.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-white/20",style:{backgroundColor:q},title:q},J))})]})]}),i.jsx("div",{className:"col-span-2 text-sm text-bambu-gray truncate",children:e}),i.jsxs("div",{className:"col-span-2 text-sm text-bambu-gray",children:[i.jsx("div",{children:mb(t.created_at)}),t.created_by_username&&i.jsxs("div",{className:"flex items-center gap-1 text-xs opacity-75",title:c("archives.card.uploadedBy",{name:t.created_by_username}),children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsx("div",{className:"col-span-1 text-sm text-bambu-gray",children:ul(t.file_size)}),i.jsxs("div",{className:"col-span-2 flex justify-end gap-1",children:[xh(t.filename)&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>_(!0),disabled:!f("archives","reprint",t.created_by_id),title:f("archives","reprint",t.created_by_id)?c("archives.card.reprint"):c("archives.card.noPermissionReprint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:i.jsx(io,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{const q=t.print_name||t.filename||"model";yh(t.id,q,"file",l)},title:c("archives.card.openInBambuStudio"),children:i.jsx(Xr,{className:"w-4 h-4"})}),(t.external_url||t.makerworld_url)&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>window.open(t.external_url||t.makerworld_url,"_blank"),title:t.external_url?c("archives.card.externalLink"):"MakerWorld",children:i.jsx(Ph,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{ne.downloadArchive(t.id,`${t.print_name||t.filename}.3mf`).catch(q=>{console.error("Archive download failed:",q)})},title:c("archives.card.download"),children:i.jsx(da,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>x(!0),disabled:!f("archives","update",t.created_by_id),title:f("archives","update",t.created_by_id)?c("archives.card.edit"):c("archives.card.noPermissionEdit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>g(!0),disabled:!f("archives","delete",t.created_by_id),title:f("archives","delete",t.created_by_id)?c("archives.card.delete"):c("archives.card.noPermissionDelete"),children:i.jsx(Jt,{className:"w-4 h-4 text-red-400"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:q=>{const J=q.currentTarget.getBoundingClientRect();ce({x:J.left,y:J.bottom+4})},title:c("archives.card.moreOptions"),children:i.jsx(Th,{className:"w-4 h-4"})})]})]}),p&&i.jsx(vne,{archive:t,onClose:()=>x(!1)}),A&&i.jsx(g4,{archiveId:t.id,title:t.print_name||t.filename,fileType:pie(t.filename),onClose:()=>M(!1)}),y&&i.jsx(Xu,{mode:"reprint",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>_(!1)}),v&&i.jsx(gn,{title:c("archives.modal.deleteArchive"),message:c("archives.modal.deleteConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.deleteButton"),variant:"danger",onConfirm:()=>{se.mutate(),g(!1)},onCancel:()=>g(!1)}),X&&i.jsx(gn,{title:c("archives.modal.removeSource3mf"),message:c("archives.modal.removeSource3mfConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{ze.mutate(),ae(!1)},onCancel:()=>ae(!1)}),H&&i.jsx(gn,{title:c("archives.modal.removeF3d"),message:c("archives.modal.removeF3dConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{Y.mutate(),K(!1)},onCancel:()=>K(!1)}),te&&i.jsx(gn,{title:c("archives.modal.removeTimelapse"),message:c("archives.modal.removeTimelapseConfirm",{name:t.print_name||t.filename}),confirmText:c("archives.modal.removeButton"),variant:"danger",onConfirm:()=>{oe.mutate(),Z(!1)},onCancel:()=>Z(!1)}),ve&&i.jsx(wne,{x:ve.x,y:ve.y,items:R,onClose:()=>ce(null)}),C&&t.timelapse_path&&i.jsx(fie,{src:ne.getArchiveTimelapse(t.id),title:c("archives.modal.timelapse",{name:t.print_name||t.filename}),downloadFilename:`${t.print_name||t.filename}_timelapse.mp4`,archiveId:t.id,onClose:()=>j(!1),onEdit:()=>{u.invalidateQueries({queryKey:["archives"]}),j(!1)}}),P&&U.length>0&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:c("archives.modal.selectTimelapse")}),i.jsx("p",{className:"text-sm text-gray-400 mt-1",children:c("archives.modal.selectTimelapseDesc")})]}),i.jsx("button",{onClick:()=>{E(!1),L([])},className:"text-gray-400 hover:text-white p-1",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"overflow-y-auto flex-1 p-2",children:U.map(q=>i.jsxs("button",{onClick:()=>Q.mutate(q.name),disabled:Q.isPending,className:"w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1",children:[i.jsx("div",{className:"font-medium text-white",children:q.name}),i.jsxs("div",{className:"text-sm text-gray-400 flex gap-3",children:[i.jsx("span",{children:ul(q.size)}),q.mtime&&i.jsx("span",{children:mb(q.mtime)})]})]},q.name))})]})}),B&&i.jsx(Sne,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>D(!1)}),$&&t.photos&&i.jsx(_ne,{archiveId:t.id,archiveName:t.print_name||t.filename,photos:t.photos,onClose:()=>G(!1),onDelete:async q=>{try{await ne.deleteArchivePhoto(t.id,q),u.invalidateQueries({queryKey:["archives"]}),d(c("archives.toast.photoDeleted"))}catch{d(c("archives.toast.failedDeletePhoto"),"error")}}}),z&&i.jsx(mie,{archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>W(!1)}),N&&i.jsx(Xu,{mode:"add-to-queue",archiveId:t.id,archiveName:t.print_name||t.filename,onClose:()=>k(!1)}),i.jsx("input",{ref:ee,type:"file",accept:".3mf",className:"hidden",onChange:q=>{const J=q.target.files?.[0];J&&ie.mutate(J),q.target.value=""}}),i.jsx("input",{ref:je,type:"file",accept:".f3d",className:"hidden",onChange:q=>{const J=q.target.files?.[0];J&&V.mutate(J),q.target.value=""}}),i.jsx("input",{ref:he,type:"file",accept:".mp4,.avi,.mkv",className:"hidden",onChange:q=>{const J=q.target.files?.[0];J&&_e.mutate(J),q.target.value=""}})]})}const dYe=[{id:"all",label:"All Archives",icon:i.jsx(Zl,{className:"w-4 h-4"})},{id:"recent",label:"Last 24 Hours",icon:i.jsx(Wn,{className:"w-4 h-4"})},{id:"this-week",label:"This Week",icon:i.jsx(ra,{className:"w-4 h-4"})},{id:"this-month",label:"This Month",icon:i.jsx(ra,{className:"w-4 h-4"})},{id:"favorites",label:"Favorites",icon:i.jsx(Ef,{className:"w-4 h-4"})},{id:"failed",label:"Failed Prints",icon:i.jsx(Ba,{className:"w-4 h-4"})},{id:"duplicates",label:"Duplicates",icon:i.jsx(Yl,{className:"w-4 h-4"})}];function hYe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r,hasAnyPermission:a}=Ir(),s=w.useRef(null),[o,l]=w.useState(""),[c,u]=w.useState(()=>{const Se=localStorage.getItem("archiveFilterPrinter");return Se?Number(Se):null}),[d,h]=w.useState(()=>localStorage.getItem("archiveFilterMaterial")),[f,p]=w.useState(()=>{const Se=localStorage.getItem("archiveFilterColors");return Se?new Set(JSON.parse(Se)):new Set}),[x,v]=w.useState(()=>localStorage.getItem("archiveColorFilterMode")||"or"),[g,y]=w.useState(()=>localStorage.getItem("archiveFilterFavorites")==="true"),[_,N]=w.useState(()=>localStorage.getItem("archiveHideFailed")==="true"),[k,A]=w.useState(()=>localStorage.getItem("archiveFilterTag")),[M,C]=w.useState(()=>localStorage.getItem("archiveFilterFileType")||"all"),[j,P]=w.useState(!1),[E,U]=w.useState([]),[L,B]=w.useState(!1),[D,$]=w.useState(new Set),[G,z]=w.useState(!1),[W,X]=w.useState(!1),[ae,H]=w.useState(!1),[K,te]=w.useState(!1),[Z,ve]=w.useState(()=>localStorage.getItem("archiveViewMode")||"grid"),[ce,ee]=w.useState(()=>localStorage.getItem("archiveSortBy")||"date-desc"),[je,he]=w.useState(()=>localStorage.getItem("archiveCollection")||"all"),[oe,_e]=w.useState(!1),[ie,ze]=w.useState(!1),[V,Y]=w.useState(!1),[me,Q]=w.useState(!1),[se,de]=w.useState(null),[Le,Ne]=w.useState(()=>localStorage.getItem("logFilterUser")||null),[be,O]=w.useState(()=>localStorage.getItem("logFilterStatus")),[R,q]=w.useState(()=>localStorage.getItem("logFilterDateFrom")||""),[J,fe]=w.useState(()=>localStorage.getItem("logFilterDateTo")||""),[le,Be]=w.useState(()=>{const Se=localStorage.getItem("logOffset");return Se?Number(Se):0}),[Ie,Ke]=w.useState(!1),[Oe,pe]=w.useState(()=>{const Se=localStorage.getItem("logPageSize");return Se?Number(Se):25});w.useEffect(()=>{if(se){const Se=setTimeout(()=>{const ot=document.querySelector(`[data-archive-id="${se}"]`);ot&&ot.scrollIntoView({behavior:"smooth",block:"center"})},100),nt=setTimeout(()=>de(null),5e3);return()=>{clearTimeout(Se),clearTimeout(nt)}}},[se]);const{data:xe,isLoading:ke}=Je({queryKey:["archives",c],queryFn:()=>ne.getArchives(c||void 0)}),{data:ge}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:we}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:qe}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:Ee}=Je({queryKey:["users"],queryFn:ne.getUsers,enabled:Z==="log"}),{data:tt,isLoading:De}=Je({queryKey:["print-log",c,Le,be,R,J,o,le,Oe],queryFn:()=>ne.getPrintLog({search:o||void 0,printerId:c||void 0,username:Le||void 0,status:be||void 0,dateFrom:R||void 0,dateTo:J||void 0,limit:Oe,offset:le}),enabled:Z==="log"}),We=qe?.time_format||"system",Ae=qe?.preferred_slicer||"bambu_studio",Re=rl(qe?.currency||"USD"),$e=st({mutationFn:async Se=>(await Promise.all(Se.map(nt=>ne.deleteArchive(nt))),Se.length),onSuccess:Se=>{e.invalidateQueries({queryKey:["archives"]}),$(new Set),n(`${Se} archive${Se!==1?"s":""} deleted`)},onError:()=>{n(t("archives.toast.failedDeleteArchives"),"error")}}),ht=st({mutationFn:()=>ne.clearPrintLog(),onSuccess:Se=>{e.invalidateQueries({queryKey:["print-log"]}),Be(0),n(t("archives.log.cleared",{count:Se.deleted}))},onError:()=>{n(t("archives.log.clearFailed"),"error")}});w.useEffect(()=>{c!==null?localStorage.setItem("archiveFilterPrinter",c.toString()):localStorage.removeItem("archiveFilterPrinter")},[c]),w.useEffect(()=>{d?localStorage.setItem("archiveFilterMaterial",d):localStorage.removeItem("archiveFilterMaterial")},[d]),w.useEffect(()=>{localStorage.setItem("archiveFilterColors",JSON.stringify([...f]))},[f]),w.useEffect(()=>{localStorage.setItem("archiveColorFilterMode",x)},[x]),w.useEffect(()=>{localStorage.setItem("archiveFilterFavorites",g.toString())},[g]),w.useEffect(()=>{localStorage.setItem("archiveHideFailed",_.toString())},[_]),w.useEffect(()=>{k?localStorage.setItem("archiveFilterTag",k):localStorage.removeItem("archiveFilterTag")},[k]),w.useEffect(()=>{localStorage.setItem("archiveFilterFileType",M)},[M]),w.useEffect(()=>{localStorage.setItem("archiveViewMode",Z)},[Z]),w.useEffect(()=>{localStorage.setItem("archiveSortBy",ce)},[ce]),w.useEffect(()=>{localStorage.setItem("archiveCollection",je)},[je]),w.useEffect(()=>{Le?localStorage.setItem("logFilterUser",Le):localStorage.removeItem("logFilterUser")},[Le]),w.useEffect(()=>{be?localStorage.setItem("logFilterStatus",be):localStorage.removeItem("logFilterStatus")},[be]),w.useEffect(()=>{R?localStorage.setItem("logFilterDateFrom",R):localStorage.removeItem("logFilterDateFrom")},[R]),w.useEffect(()=>{J?localStorage.setItem("logFilterDateTo",J):localStorage.removeItem("logFilterDateTo")},[J]),w.useEffect(()=>{localStorage.setItem("logOffset",le.toString())},[le]),w.useEffect(()=>{localStorage.setItem("logPageSize",Oe.toString())},[Oe]);const At=new Map(ge?.map(Se=>[Se.id,Se.name])||[]),Dt=[...new Set(xe?.flatMap(Se=>Se.filament_type?.split(", ")||[]).filter(Boolean)||[])].sort(),It=[...new Set(xe?.flatMap(Se=>Se.filament_color?.split(",")||[]).filter(Boolean)||[])],kt=[...new Set(xe?.flatMap(Se=>Se.tags?.split(",").map(nt=>nt.trim())||[]).filter(Boolean)||[])].sort(),Ue=xe?.filter(Se=>{const nt=new Date,ot=hi(Se.created_at)||new Date(0);let Ge=!0;switch(je){case"recent":Ge=nt.getTime()-ot.getTime()<1440*60*1e3;break;case"this-week":Ge=nt.getTime()-ot.getTime()<10080*60*1e3;break;case"this-month":Ge=ot.getMonth()===nt.getMonth()&&ot.getFullYear()===nt.getFullYear();break;case"favorites":Ge=Se.is_favorite===!0;break;case"failed":Ge=Se.status==="failed"||Se.status==="aborted";break;case"duplicates":Ge=Se.duplicate_count>0;break}const zt=(Se.print_name||Se.filename).toLowerCase().includes(o.toLowerCase()),ye=!d||Se.filament_type?.split(", ").includes(d),He=Se.filament_color?.split(",")||[],Ye=f.size===0||(x==="or"?He.some($t=>f.has($t)):[...f].every($t=>He.includes($t))),Xe=je==="favorites"||!g||Se.is_favorite,Te=je==="failed"||!_||Se.status!=="failed"&&Se.status!=="aborted",lt=Se.tags?.split(",").map($t=>$t.trim())||[],pt=!k||lt.includes(k),at=xh(Se.filename);return Ge&&zt&&ye&&Ye&&Xe&&Te&&pt&&(M==="all"||M==="gcode"&&at||M==="source"&&!at)}).sort((Se,nt)=>{switch(ce){case"date-desc":return(hi(nt.created_at)?.getTime()||0)-(hi(Se.created_at)?.getTime()||0);case"date-asc":return(hi(Se.created_at)?.getTime()||0)-(hi(nt.created_at)?.getTime()||0);case"name-asc":return(Se.print_name||Se.filename).localeCompare(nt.print_name||nt.filename);case"name-desc":return(nt.print_name||nt.filename).localeCompare(Se.print_name||Se.filename);case"size-desc":return nt.file_size-Se.file_size;case"size-asc":return Se.file_size-nt.file_size;default:return 0}}),bt=G||D.size>0,yt=Se=>{$(nt=>{const ot=new Set(nt);return ot.has(Se)?ot.delete(Se):ot.add(Se),ot})},Gt=()=>{Ue&&$(new Set(Ue.map(Se=>Se.id)))},Cn=()=>{$(new Set),z(!1)},vr=Se=>{p(nt=>{const ot=new Set(nt);return ot.has(Se)?ot.delete(Se):ot.add(Se),ot})},Qn=()=>{p(new Set)},tr=()=>{l(""),u(null),h(null),y(!1),N(!1),A(null),C("all")},En=o||c||d||g||_||k||M!=="all",dr=w.useCallback(Se=>{Se.preventDefault(),Se.dataTransfer.types.includes("Files")&&B(!0)},[]),Tr=w.useCallback(Se=>{Se.preventDefault(),Se.currentTarget===Se.target&&B(!1)},[]),si=w.useCallback(Se=>{Se.preventDefault(),B(!1);const nt=Array.from(Se.dataTransfer.files).filter(ot=>ot.name.endsWith(".3mf"));nt.length>0?(U(nt),P(!0)):Se.dataTransfer.files.length>0&&n(t("archives.page.only3mfSupported"),"warning")},[n,t]),Fe=w.useCallback(Se=>{const nt=Se.target;if(nt.tagName==="INPUT"||nt.tagName==="TEXTAREA"||nt.isContentEditable){Se.key==="Escape"&&nt.blur();return}switch(Se.key){case"/":Se.preventDefault(),s.current?.focus();break;case"u":case"U":!Se.metaKey&&!Se.ctrlKey&&(Se.preventDefault(),P(!0));break;case"Escape":bt&&Cn();break}},[bt]);return w.useEffect(()=>(document.addEventListener("keydown",Fe),()=>document.removeEventListener("keydown",Fe)),[Fe]),i.jsxs("div",{className:"p-4 md:p-8 relative min-h-full",onDragOver:dr,onDragLeave:Tr,onDrop:si,children:[L&&i.jsx("div",{className:"fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none",children:i.jsxs("div",{className:"border-4 border-dashed border-bambu-green rounded-xl p-12 text-center",children:[i.jsx(Ra,{className:"w-16 h-16 mx-auto mb-4 text-bambu-green"}),i.jsx("p",{className:"text-2xl font-semibold text-white mb-2",children:"Drop .3mf files here"}),i.jsx("p",{className:"text-bambu-gray",children:t("archives.releaseToUpload")})]})}),bt&&i.jsxs("div",{className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Cn,children:[i.jsx(Lt,{className:"w-4 h-4"}),"Close"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("span",{className:"text-white font-medium",children:[D.size," selected"]}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:Gt,children:"Select All"}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>H(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(Vh,{className:"w-4 h-4"}),"Tags"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>te(!0),disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),children:[i.jsx(gs,{className:"w-4 h-4"}),"Project"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:!a("archives:update_own","archives:update_all"),title:a("archives:update_own","archives:update_all")?void 0:t("archives.permission.noUpdateArchives"),onClick:()=>{const Se=Array.from(D);Promise.all(Se.map(nt=>ne.toggleFavorite(nt))).then(()=>{e.invalidateQueries({queryKey:["archives"]}),n(`Toggled favorites for ${Se.length} archive${Se.length!==1?"s":""}`)}).catch(()=>{n(t("archives.toast.failedUpdateFavorites"),"error")})},children:[i.jsx(Ef,{className:"w-4 h-4"}),"Favorite"]}),i.jsxs(Ce,{size:"sm",className:"bg-red-500 hover:bg-red-600",onClick:()=>X(!0),disabled:!a("archives:delete_own","archives:delete_all"),title:a("archives:delete_own","archives:delete_all")?void 0:t("archives.permission.noDelete"),children:[i.jsx(Jt,{className:"w-4 h-4"}),"Delete"]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:"Archives"}),i.jsx("select",{className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none",value:je,onChange:Se=>he(Se.target.value),children:dYe.map(Se=>i.jsx("option",{value:Se.id,children:Se.label},Se.id))})]}),i.jsxs("p",{className:"text-bambu-gray",children:[Ue?.length||0," of ",xe?.length||0," prints"]})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"relative",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>_e(!oe),disabled:ie,children:[ie?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(S1,{className:"w-4 h-4"}),"Export"]}),oe&&i.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[i.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:async()=>{_e(!1),ze(!0);try{const{blob:Se,filename:nt}=await ne.exportArchives({format:"csv",printerId:c||void 0,status:je==="failed"?"failed":void 0,search:o||void 0}),ot=URL.createObjectURL(Se),Ge=document.createElement("a");Ge.href=ot,Ge.download=nt,Ge.click(),URL.revokeObjectURL(ot),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{ze(!1)}},children:[i.jsx(Ms,{className:"w-4 h-4"}),"Export as CSV"]}),i.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:async()=>{_e(!1),ze(!0);try{const{blob:Se,filename:nt}=await ne.exportArchives({format:"xlsx",printerId:c||void 0,status:je==="failed"?"failed":void 0,search:o||void 0}),ot=URL.createObjectURL(Se),Ge=document.createElement("a");Ge.href=ot,Ge.download=nt,Ge.click(),URL.revokeObjectURL(ot),n(t("archives.toast.exportDownloaded"))}catch{n(t("archives.toast.exportFailed"),"error")}finally{ze(!1)}},children:[i.jsx(S1,{className:"w-4 h-4"}),"Export as Excel"]})]})]}),D.size>=2&&D.size<=5&&i.jsxs(Ce,{variant:"secondary",onClick:()=>Y(!0),children:[i.jsx(Gg,{className:"w-4 h-4"}),"Compare (",D.size,")"]}),!bt&&i.jsxs(Ce,{variant:"secondary",onClick:()=>z(!0),children:[i.jsx(oo,{className:"w-4 h-4"}),"Select"]}),i.jsxs(Ce,{onClick:()=>P(!0),disabled:!r("archives:create"),title:r("archives:create")?void 0:t("archives.permission.noCreate"),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Upload 3MF"]})]})]}),i.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4",children:[i.jsx("button",{className:`p-2 ${Z==="grid"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ve("grid"),title:t("archives.gridView"),children:i.jsx(h0,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${Z==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ve("list"),title:t("archives.listView"),children:i.jsx(WC,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${Z==="calendar"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ve("calendar"),title:t("archives.calendarView"),children:i.jsx(rhe,{className:"w-4 h-4"})}),i.jsx("button",{className:`p-2 ${Z==="log"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>ve("log"),title:t("archives.logView"),children:i.jsx(khe,{className:"w-4 h-4"})})]}),Z!=="log"&&i.jsx(wt,{className:"mb-6",children:i.jsxs(_t,{className:"py-4",children:[i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"w-full md:flex-1 relative md:min-w-[200px]",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{ref:s,type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o,onChange:Se=>l(Se.target.value)})]}),i.jsxs("div",{className:"flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(qC,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c||"",onChange:Se=>u(Se.target.value?Number(Se.target.value):null),children:[i.jsx("option",{value:"",children:"All Printers"}),ge?.map(Se=>i.jsx("option",{value:Se.id,children:Se.name},Se.id))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(ni,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d||"",onChange:Se=>h(Se.target.value||null),children:[i.jsx("option",{value:"",children:"All Materials"}),Dt.map(Se=>i.jsx("option",{value:Se,children:Se},Se))]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(w1,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:M,onChange:Se=>C(Se.target.value),children:[i.jsx("option",{value:"all",children:"All Files"}),i.jsx("option",{value:"gcode",children:"Sliced (GCODE)"}),i.jsx("option",{value:"source",children:"Source Only"})]})]}),i.jsxs("button",{onClick:()=>y(!g),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${g?"bg-yellow-500/20 border-yellow-500 text-yellow-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(g?"archives.showAll":"archives.showFavoritesOnly"),children:[i.jsx(Ef,{className:`w-4 h-4 ${g?"fill-yellow-400":""}`}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Favorites"})]}),i.jsxs("button",{onClick:()=>N(!_),className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${_?"bg-red-500/20 border-red-500 text-red-400":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t(_?"archives.showFailedPrints":"archives.hideFailedPrints"),children:[i.jsx(Ba,{className:"w-4 h-4 "}),i.jsx("span",{className:"text-sm hidden md:inline",children:"Hide Failed"})]}),kt.length>0&&i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(Vh,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:k||"",onChange:Se=>A(Se.target.value||null),children:[i.jsx("option",{value:"",children:"All Tags"}),kt.map(Se=>i.jsx("option",{value:Se,children:Se},Se))]}),i.jsx("button",{onClick:()=>Q(!0),className:"p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",title:t("archives.manageTags"),children:i.jsx(f0,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx(NF,{className:"w-4 h-4 text-bambu-gray hidden md:block"}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:ce,onChange:Se=>ee(Se.target.value),children:[i.jsx("option",{value:"date-desc",children:t("archives.sortNewest")}),i.jsx("option",{value:"date-asc",children:t("archives.sortOldest")}),i.jsxs("option",{value:"name-asc",children:[t("archives.sortName")," A-Z"]}),i.jsxs("option",{value:"name-desc",children:[t("archives.sortName")," Z-A"]}),i.jsx("option",{value:"size-desc",children:t("archives.sortLargest")}),i.jsx("option",{value:"size-asc",children:t("archives.sortSmallest")})]})]})]}),En&&i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:tr,className:"text-bambu-gray hover:text-white",children:[i.jsx(Lt,{className:"w-4 h-4"}),"Reset"]})]}),It.length>0&&i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Colors:"}),f.size>1&&i.jsx("button",{onClick:()=>v(Se=>Se==="or"?"and":"or"),className:`px-2 py-0.5 text-xs rounded transition-colors ${x==="and"?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:x==="or"?"Match ANY selected color":"Match ALL selected colors",children:x.toUpperCase()}),i.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:It.map(Se=>i.jsx("button",{onClick:()=>vr(Se),className:`w-6 h-6 rounded-full border-2 transition-all ${f.has(Se)?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:Se},title:Se},Se))}),f.size>0&&i.jsxs("button",{onClick:Qn,className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1",children:[i.jsx(Lt,{className:"w-3 h-3"}),"Clear"]})]})]})}),i.jsx(oYe,{}),ke?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.loadingArchives")}):Ue?.length===0?i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray",children:t(o?"archives.noArchivesSearch":"archives.noArchivesYet")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:"Archives are created automatically when prints complete"})]})}):Z==="calendar"?i.jsx(wt,{className:"p-6",children:i.jsx(Z$e,{archives:Ue||[],onArchiveClick:Se=>{l(""),ve("grid"),de(Se.id)},highlightedArchiveId:se})}):Z==="grid"?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:Ue?.map(Se=>i.jsx(cYe,{archive:Se,printerName:Se.printer_id?At.get(Se.printer_id)||"Unknown":Se.sliced_for_model?`Sliced for ${Se.sliced_for_model}`:"No Printer",isSelected:D.has(Se.id),onSelect:yt,selectionMode:bt,projects:we,isHighlighted:Se.id===se,timeFormat:We,preferredSlicer:Ae,currency:Re,t},Se.id))}):Z==="list"?i.jsx(wt,{children:i.jsxs("div",{className:"divide-y divide-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium",children:[i.jsx("div",{className:"col-span-1"}),i.jsx("div",{className:"col-span-4",children:"Name"}),i.jsx("div",{className:"col-span-2",children:"Printer"}),i.jsx("div",{className:"col-span-2",children:"Date"}),i.jsx("div",{className:"col-span-1",children:"Size"}),i.jsx("div",{className:"col-span-2 text-right",children:"Actions"})]}),Ue?.map(Se=>i.jsx(uYe,{archive:Se,printerName:Se.printer_id?At.get(Se.printer_id)||"Unknown":Se.sliced_for_model?`Sliced for ${Se.sliced_for_model}`:"No Printer",isSelected:D.has(Se.id),onSelect:yt,selectionMode:bt,projects:we,isHighlighted:Se.id===se,preferredSlicer:Ae,t},Se.id))]})}):Z==="log"?i.jsxs("div",{className:"space-y-4",children:[i.jsx(wt,{children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap",children:[i.jsxs("div",{className:"flex-1 relative md:min-w-[200px]",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("archives.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:o,onChange:Se=>{l(Se.target.value),Be(0)}})]}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:c||"",onChange:Se=>{u(Se.target.value?Number(Se.target.value):null),Be(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allPrinters")}),ge?.map(Se=>i.jsx("option",{value:Se.id,children:Se.name},Se.id))]}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:Le||"",onChange:Se=>{Ne(Se.target.value||null),Be(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allUsers")}),Ee?.map(Se=>i.jsx("option",{value:Se.username,children:Se.username},Se.id))]}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:be||"",onChange:Se=>{O(Se.target.value||null),Be(0)},children:[i.jsx("option",{value:"",children:t("archives.log.allStatuses")}),i.jsx("option",{value:"completed",children:t("archives.status.completed")}),i.jsx("option",{value:"failed",children:t("archives.status.failed")}),i.jsx("option",{value:"stopped",children:t("archives.status.stopped")}),i.jsx("option",{value:"cancelled",children:t("archives.log.cancelled")}),i.jsx("option",{value:"skipped",children:t("archives.log.skipped")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateFrom")}),i.jsx("input",{type:"date",className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:R,onChange:Se=>{q(Se.target.value),Be(0)}})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:t("archives.log.dateTo")}),i.jsx("input",{type:"date",className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:J,onChange:Se=>{fe(Se.target.value),Be(0)}})]}),i.jsx("div",{className:"ml-auto",children:i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>Ke(!0),disabled:!r("archives:delete_all")||ht.isPending,children:[i.jsx(Jt,{className:"w-4 h-4"}),t("archives.log.clearLog")]})})]})})}),i.jsx(wt,{children:De?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):tt?.items.length?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary text-bambu-gray text-left",children:[i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.date")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printName")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.printer")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.user")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.status")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.duration")}),i.jsx("th",{className:"px-4 py-3 font-medium",children:t("archives.log.filament")})]})}),i.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:tt.items.map(Se=>i.jsxs("tr",{className:"hover:bg-bambu-dark-secondary/50",children:[i.jsx("td",{className:"px-4 py-3 text-white whitespace-nowrap",children:Rf(Se.started_at||Se.created_at,We)}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[Se.thumbnail_path&&i.jsx("img",{src:ne.getPrintLogThumbnail(Se.id),alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0",onError:nt=>{nt.target.style.display="none"}}),i.jsx("span",{className:"text-white truncate max-w-[200px]",children:Se.print_name||"—"})]})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Se.printer_name||"—"}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light",children:Se.created_by_username||"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${Se.status==="completed"?"bg-green-500/20 text-green-400":Se.status==="failed"?"bg-red-500/20 text-red-400":Se.status==="stopped"?"bg-yellow-500/20 text-yellow-400":Se.status==="cancelled"?"bg-orange-500/20 text-orange-400":Se.status==="skipped"?"bg-blue-500/20 text-blue-400":"bg-gray-500/20 text-gray-400"}`,children:Se.status})}),i.jsx("td",{className:"px-4 py-3 text-bambu-gray-light whitespace-nowrap",children:Se.duration_seconds?Qs(Se.duration_seconds):"—"}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-1.5",children:[Se.filament_color&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:Se.filament_color.startsWith("#")?Se.filament_color:void 0}}),i.jsx("span",{className:"text-bambu-gray-light text-xs",children:Se.filament_type||"—"})]})})]},Se.id))})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:t("archives.log.showing",{count:Math.min(le+Oe,tt.total),total:tt.total})}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:t("archives.log.rowsPerPage")}),i.jsxs("select",{className:"px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-xs focus:border-bambu-green focus:outline-none",value:Oe,onChange:Se=>{pe(Number(Se.target.value)),Be(0)},children:[i.jsx("option",{value:10,children:"10"}),i.jsx("option",{value:25,children:"25"}),i.jsx("option",{value:50,children:"50"}),i.jsx("option",{value:100,children:"100"})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("archives.log.page")," ",Math.floor(le/Oe)+1," / ",Math.max(1,Math.ceil(tt.total/Oe))]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Be(Math.max(0,le-Oe)),disabled:le===0,children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Be(le+Oe),disabled:le+Oe>=tt.total,children:i.jsx(pi,{className:"w-4 h-4"})})]})]})]}):i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("archives.log.noEntries")})})]}):null,j&&i.jsx($$e,{onClose:()=>{P(!1),U([])},initialFiles:E}),W&&i.jsx(gn,{title:t("archives.modal.deleteArchives"),message:t("archives.modal.deleteArchivesConfirm",{count:D.size}),confirmText:t("archives.modal.deleteCount",{count:D.size}),variant:"danger",onConfirm:()=>{$e.mutate(Array.from(D)),X(!1)},onCancel:()=>X(!1)}),ae&&i.jsx(G$e,{selectedIds:Array.from(D),existingTags:kt,onClose:()=>H(!1)}),K&&i.jsx(W$e,{selectedIds:Array.from(D),onClose:()=>te(!1)}),V&&D.size>=2&&D.size<=5&&i.jsx(rYe,{archiveIds:Array.from(D),onClose:()=>{Y(!1),$(new Set),z(!1)}}),me&&i.jsx(lYe,{onClose:()=>Q(!1)}),Ie&&i.jsx(gn,{title:t("archives.log.clearLogTitle"),message:t("archives.log.clearLogConfirm"),confirmText:t("archives.log.clearLogButton"),variant:"danger",onConfirm:()=>{ht.mutate(),Ke(!1)},onCancel:()=>Ke(!1)})]})}function mYe(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return w.useMemo(()=>r=>{e.forEach(a=>a(r))},e)}const _A=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function cx(t){const e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function aI(t){return"nodeType"in t}function uo(t){var e,n;return t?cx(t)?t:aI(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function iI(t){const{Document:e}=uo(t);return t instanceof e}function W0(t){return cx(t)?!1:t instanceof uo(t).HTMLElement}function gie(t){return t instanceof uo(t).SVGElement}function ux(t){return t?cx(t)?t.document:aI(t)?iI(t)?t:W0(t)||gie(t)?t.ownerDocument:document:document:document}const $c=_A?w.useLayoutEffect:w.useEffect;function sI(t){const e=w.useRef(t);return $c(()=>{e.current=t}),w.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return e.current==null?void 0:e.current(...r)},[])}function fYe(){const t=w.useRef(null),e=w.useCallback((r,a)=>{t.current=setInterval(r,a)},[]),n=w.useCallback(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function r0(t,e){e===void 0&&(e=[t]);const n=w.useRef(t);return $c(()=>{n.current!==t&&(n.current=t)},e),n}function K0(t,e){const n=w.useRef();return w.useMemo(()=>{const r=t(n.current);return n.current=r,r},[...e])}function DC(t){const e=sI(t),n=w.useRef(null),r=w.useCallback(a=>{a!==n.current&&e?.(a,n.current),n.current=a},[]);return[n,r]}function ZR(t){const e=w.useRef();return w.useEffect(()=>{e.current=t},[t]),e.current}let S2={};function X0(t,e){return w.useMemo(()=>{if(e)return e;const n=S2[t]==null?0:S2[t]+1;return S2[t]=n,t+"-"+n},[t,e])}function bie(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return r.reduce((s,o)=>{const l=Object.entries(o);for(const[c,u]of l){const d=s[c];d!=null&&(s[c]=d+t*u)}return s},{...e})}}const sb=bie(1),a0=bie(-1);function pYe(t){return"clientX"in t&&"clientY"in t}function oI(t){if(!t)return!1;const{KeyboardEvent:e}=uo(t.target);return e&&t instanceof e}function gYe(t){if(!t)return!1;const{TouchEvent:e}=uo(t.target);return e&&t instanceof e}function JR(t){if(gYe(t)){if(t.touches&&t.touches.length){const{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){const{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return pYe(t)?{x:t.clientX,y:t.clientY}:null}const Ob=Object.freeze({Translate:{toString(t){if(!t)return;const{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;const{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[Ob.Translate.toString(t),Ob.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),UW="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function bYe(t){return t.matches(UW)?t:t.querySelector(UW)}const xYe={display:"none"};function yYe(t){let{id:e,value:n}=t;return Hr.createElement("div",{id:e,style:xYe},n)}function vYe(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Hr.createElement("div",{id:e,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function wYe(){const[t,e]=w.useState("");return{announce:w.useCallback(r=>{r!=null&&e(r)},[]),announcement:t}}const xie=w.createContext(null);function SYe(t){const e=w.useContext(xie);w.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function _Ye(){const[t]=w.useState(()=>new Set),e=w.useCallback(r=>(t.add(r),()=>t.delete(r)),[t]);return[w.useCallback(r=>{let{type:a,event:s}=r;t.forEach(o=>{var l;return(l=o[a])==null?void 0:l.call(o,s)})},[t]),e]}const NYe={draggable:`
  8288. To pick up a draggable item, press the space bar.
  8289. While dragging, use the arrow keys to move the item.
  8290. Press space again to drop the item in its new position, or press escape to cancel.
  8291. `},CYe={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function kYe(t){let{announcements:e=CYe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=NYe}=t;const{announce:s,announcement:o}=wYe(),l=X0("DndLiveRegion"),[c,u]=w.useState(!1);if(w.useEffect(()=>{u(!0)},[]),SYe(w.useMemo(()=>({onDragStart(h){let{active:f}=h;s(e.onDragStart({active:f}))},onDragMove(h){let{active:f,over:p}=h;e.onDragMove&&s(e.onDragMove({active:f,over:p}))},onDragOver(h){let{active:f,over:p}=h;s(e.onDragOver({active:f,over:p}))},onDragEnd(h){let{active:f,over:p}=h;s(e.onDragEnd({active:f,over:p}))},onDragCancel(h){let{active:f,over:p}=h;s(e.onDragCancel({active:f,over:p}))}}),[s,e])),!c)return null;const d=Hr.createElement(Hr.Fragment,null,Hr.createElement(yYe,{id:r,value:a.draggable}),Hr.createElement(vYe,{id:l,announcement:o}));return n?Fu.createPortal(d,n):d}var di;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(di||(di={}));function RC(){}function FC(t,e){return w.useMemo(()=>({sensor:t,options:e??{}}),[t,e])}function yie(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return w.useMemo(()=>[...e].filter(r=>r!=null),[...e])}const tc=Object.freeze({x:0,y:0});function vie(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function wie(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function AYe(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function BW(t){let{left:e,top:n,height:r,width:a}=t;return[{x:e,y:n},{x:e+a,y:n},{x:e,y:n+r},{x:e+a,y:n+r}]}function Sie(t,e){if(!t||t.length===0)return null;const[n]=t;return n[e]}function HW(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}const _ie=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const a=HW(e,e.left,e.top),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=vie(HW(c),a);s.push({id:l,data:{droppableContainer:o,value:u}})}}return s.sort(wie)},TYe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const a=BW(e),s=[];for(const o of r){const{id:l}=o,c=n.get(l);if(c){const u=BW(c),d=a.reduce((f,p,x)=>f+vie(u[x],p),0),h=Number((d/4).toFixed(4));s.push({id:l,data:{droppableContainer:o,value:h}})}}return s.sort(wie)};function MYe(t,e){const n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),a=Math.min(e.left+e.width,t.left+t.width),s=Math.min(e.top+e.height,t.top+t.height),o=a-r,l=s-n;if(r<a&&n<s){const c=e.width*e.height,u=t.width*t.height,d=o*l,h=d/(c+u-d);return Number(h.toFixed(4))}return 0}const PYe=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t;const a=[];for(const s of r){const{id:o}=s,l=n.get(o);if(l){const c=MYe(l,e);c>0&&a.push({id:o,data:{droppableContainer:s,value:c}})}}return a.sort(AYe)};function EYe(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Nie(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:tc}function jYe(t){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),s=1;s<r;s++)a[s-1]=arguments[s];return a.reduce((o,l)=>({...o,top:o.top+t*l.y,bottom:o.bottom+t*l.y,left:o.left+t*l.x,right:o.right+t*l.x}),{...n})}}const DYe=jYe(1);function RYe(t){if(t.startsWith("matrix3d(")){const e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){const e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function FYe(t,e,n){const r=RYe(e);if(!r)return t;const{scaleX:a,scaleY:s,x:o,y:l}=r,c=t.left-o-(1-a)*parseFloat(n),u=t.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=a?t.width/a:t.width,h=s?t.height/s:t.height;return{width:d,height:h,top:u,right:c+d,bottom:u+h,left:c}}const LYe={ignoreTransform:!1};function dx(t,e){e===void 0&&(e=LYe);let n=t.getBoundingClientRect();if(e.ignoreTransform){const{transform:u,transformOrigin:d}=uo(t).getComputedStyle(t);u&&(n=FYe(n,u,d))}const{top:r,left:a,width:s,height:o,bottom:l,right:c}=n;return{top:r,left:a,width:s,height:o,bottom:l,right:c}}function $W(t){return dx(t,{ignoreTransform:!0})}function OYe(t){const e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function IYe(t,e){return e===void 0&&(e=uo(t).getComputedStyle(t)),e.position==="fixed"}function zYe(t,e){e===void 0&&(e=uo(t).getComputedStyle(t));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const s=e[a];return typeof s=="string"?n.test(s):!1})}function NA(t,e){const n=[];function r(a){if(e!=null&&n.length>=e||!a)return n;if(iI(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!W0(a)||gie(a)||n.includes(a))return n;const s=uo(t).getComputedStyle(a);return a!==t&&zYe(a,s)&&n.push(a),IYe(a,s)?n:r(a.parentNode)}return t?r(t):n}function Cie(t){const[e]=NA(t,1);return e??null}function _2(t){return!_A||!t?null:cx(t)?t:aI(t)?iI(t)||t===ux(t).scrollingElement?window:W0(t)?t:null:null}function kie(t){return cx(t)?t.scrollX:t.scrollLeft}function Aie(t){return cx(t)?t.scrollY:t.scrollTop}function eF(t){return{x:kie(t),y:Aie(t)}}var ji;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(ji||(ji={}));function Tie(t){return!_A||!t?!1:t===document.scrollingElement}function Mie(t){const e={x:0,y:0},n=Tie(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},a=t.scrollTop<=e.y,s=t.scrollLeft<=e.x,o=t.scrollTop>=r.y,l=t.scrollLeft>=r.x;return{isTop:a,isLeft:s,isBottom:o,isRight:l,maxScroll:r,minScroll:e}}const UYe={x:.2,y:.2};function BYe(t,e,n,r,a){let{top:s,left:o,right:l,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=UYe);const{isTop:u,isBottom:d,isLeft:h,isRight:f}=Mie(t),p={x:0,y:0},x={x:0,y:0},v={height:e.height*a.y,width:e.width*a.x};return!u&&s<=e.top+v.height?(p.y=ji.Backward,x.y=r*Math.abs((e.top+v.height-s)/v.height)):!d&&c>=e.bottom-v.height&&(p.y=ji.Forward,x.y=r*Math.abs((e.bottom-v.height-c)/v.height)),!f&&l>=e.right-v.width?(p.x=ji.Forward,x.x=r*Math.abs((e.right-v.width-l)/v.width)):!h&&o<=e.left+v.width&&(p.x=ji.Backward,x.x=r*Math.abs((e.left+v.width-o)/v.width)),{direction:p,speed:x}}function HYe(t){if(t===document.scrollingElement){const{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}const{top:e,left:n,right:r,bottom:a}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:a,width:t.clientWidth,height:t.clientHeight}}function Pie(t){return t.reduce((e,n)=>sb(e,eF(n)),tc)}function $Ye(t){return t.reduce((e,n)=>e+kie(n),0)}function VYe(t){return t.reduce((e,n)=>e+Aie(n),0)}function qYe(t,e){if(e===void 0&&(e=dx),!t)return;const{top:n,left:r,bottom:a,right:s}=e(t);Cie(t)&&(a<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}const GYe=[["x",["left","right"],$Ye],["y",["top","bottom"],VYe]];class lI{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=NA(n),a=Pie(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[s,o,l]of GYe)for(const c of o)Object.defineProperty(this,c,{get:()=>{const u=l(r),d=a[s]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class lv{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var a;(a=this.target)==null||a.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function WYe(t){const{EventTarget:e}=uo(t);return t instanceof e?t:ux(t)}function N2(t,e){const n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var il;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(il||(il={}));function VW(t){t.preventDefault()}function KYe(t){t.stopPropagation()}var rr;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(rr||(rr={}));const Eie={start:[rr.Space,rr.Enter],cancel:[rr.Esc],end:[rr.Space,rr.Enter,rr.Tab]},XYe=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case rr.Right:return{...n,x:n.x+25};case rr.Left:return{...n,x:n.x-25};case rr.Down:return{...n,y:n.y+25};case rr.Up:return{...n,y:n.y-25}}};class CA{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new lv(ux(n)),this.windowListeners=new lv(uo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(il.Resize,this.handleCancel),this.windowListeners.add(il.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(il.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&qYe(r),n(tc)}handleKeyDown(e){if(oI(e)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:s=Eie,coordinateGetter:o=XYe,scrollBehavior:l="smooth"}=a,{code:c}=e;if(s.end.includes(c)){this.handleEnd(e);return}if(s.cancel.includes(c)){this.handleCancel(e);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:tc;this.referenceCoordinates||(this.referenceCoordinates=d);const h=o(e,{active:n,context:r.current,currentCoordinates:d});if(h){const f=a0(h,d),p={x:0,y:0},{scrollableAncestors:x}=r.current;for(const v of x){const g=e.code,{isTop:y,isRight:_,isLeft:N,isBottom:k,maxScroll:A,minScroll:M}=Mie(v),C=HYe(v),j={x:Math.min(g===rr.Right?C.right-C.width/2:C.right,Math.max(g===rr.Right?C.left:C.left+C.width/2,h.x)),y:Math.min(g===rr.Down?C.bottom-C.height/2:C.bottom,Math.max(g===rr.Down?C.top:C.top+C.height/2,h.y))},P=g===rr.Right&&!_||g===rr.Left&&!N,E=g===rr.Down&&!k||g===rr.Up&&!y;if(P&&j.x!==h.x){const U=v.scrollLeft+f.x,L=g===rr.Right&&U<=A.x||g===rr.Left&&U>=M.x;if(L&&!f.y){v.scrollTo({left:U,behavior:l});return}L?p.x=v.scrollLeft-U:p.x=g===rr.Right?v.scrollLeft-A.x:v.scrollLeft-M.x,p.x&&v.scrollBy({left:-p.x,behavior:l});break}else if(E&&j.y!==h.y){const U=v.scrollTop+f.y,L=g===rr.Down&&U<=A.y||g===rr.Up&&U>=M.y;if(L&&!f.x){v.scrollTo({top:U,behavior:l});return}L?p.y=v.scrollTop-U:p.y=g===rr.Down?v.scrollTop-A.y:v.scrollTop-M.y,p.y&&v.scrollBy({top:-p.y,behavior:l});break}}this.handleMove(e,sb(a0(h,this.referenceCoordinates),p))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}CA.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=Eie,onActivation:a}=e,{active:s}=n;const{code:o}=t.nativeEvent;if(r.start.includes(o)){const l=s.activatorNode.current;return l&&t.target!==l?!1:(t.preventDefault(),a?.({event:t.nativeEvent}),!0)}return!1}}];function qW(t){return!!(t&&"distance"in t)}function GW(t){return!!(t&&"delay"in t)}class cI{constructor(e,n,r){var a;r===void 0&&(r=WYe(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:s}=e,{target:o}=s;this.props=e,this.events=n,this.document=ux(o),this.documentListeners=new lv(this.document),this.listeners=new lv(r),this.windowListeners=new lv(uo(o)),this.initialCoordinates=(a=JR(s))!=null?a:tc,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(il.Resize,this.handleCancel),this.windowListeners.add(il.DragStart,VW),this.windowListeners.add(il.VisibilityChange,this.handleCancel),this.windowListeners.add(il.ContextMenu,VW),this.documentListeners.add(il.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(GW(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(qW(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:a}=this.props;a(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(il.Click,KYe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(il.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:a,props:s}=this,{onMove:o,options:{activationConstraint:l}}=s;if(!a)return;const c=(n=JR(e))!=null?n:tc,u=a0(a,c);if(!r&&l){if(qW(l)){if(l.tolerance!=null&&N2(u,l.tolerance))return this.handleCancel();if(N2(u,l.distance))return this.handleStart()}if(GW(l)&&N2(u,l.tolerance))return this.handleCancel();this.handlePending(l,u);return}e.cancelable&&e.preventDefault(),o(c)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===rr.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const YYe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class kA extends cI{constructor(e){const{event:n}=e,r=ux(n.target);super(e,YYe,r)}}kA.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const QYe={move:{name:"mousemove"},end:{name:"mouseup"}};var tF;(function(t){t[t.RightClick=2]="RightClick"})(tF||(tF={}));class ZYe extends cI{constructor(e){super(e,QYe,ux(e.event.target))}}ZYe.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===tF.RightClick?!1:(r?.({event:n}),!0)}}];const C2={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class JYe extends cI{constructor(e){super(e,C2)}static setup(){return window.addEventListener(C2.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(C2.move.name,e)};function e(){}}}JYe.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;const{touches:a}=n;return a.length>1?!1:(r?.({event:n}),!0)}}];var cv;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(cv||(cv={}));var LC;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(LC||(LC={}));function eQe(t){let{acceleration:e,activator:n=cv.Pointer,canScroll:r,draggingRect:a,enabled:s,interval:o=5,order:l=LC.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:h,threshold:f}=t;const p=nQe({delta:h,disabled:!s}),[x,v]=fYe(),g=w.useRef({x:0,y:0}),y=w.useRef({x:0,y:0}),_=w.useMemo(()=>{switch(n){case cv.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case cv.DraggableRect:return a}},[n,a,c]),N=w.useRef(null),k=w.useCallback(()=>{const M=N.current;if(!M)return;const C=g.current.x*y.current.x,j=g.current.y*y.current.y;M.scrollBy(C,j)},[]),A=w.useMemo(()=>l===LC.TreeOrder?[...u].reverse():u,[l,u]);w.useEffect(()=>{if(!s||!u.length||!_){v();return}for(const M of A){if(r?.(M)===!1)continue;const C=u.indexOf(M),j=d[C];if(!j)continue;const{direction:P,speed:E}=BYe(M,j,_,e,f);for(const U of["x","y"])p[U][P[U]]||(E[U]=0,P[U]=0);if(E.x>0||E.y>0){v(),N.current=M,x(k,o),g.current=E,y.current=P;return}}g.current={x:0,y:0},y.current={x:0,y:0},v()},[e,k,r,v,s,o,JSON.stringify(_),JSON.stringify(p),x,u,A,d,JSON.stringify(f)])}const tQe={x:{[ji.Backward]:!1,[ji.Forward]:!1},y:{[ji.Backward]:!1,[ji.Forward]:!1}};function nQe(t){let{delta:e,disabled:n}=t;const r=ZR(e);return K0(a=>{if(n||!r||!a)return tQe;const s={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[ji.Backward]:a.x[ji.Backward]||s.x===-1,[ji.Forward]:a.x[ji.Forward]||s.x===1},y:{[ji.Backward]:a.y[ji.Backward]||s.y===-1,[ji.Forward]:a.y[ji.Forward]||s.y===1}}},[n,e,r])}function rQe(t,e){const n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return K0(a=>{var s;return e==null?null:(s=r??a)!=null?s:null},[r,e])}function aQe(t,e){return w.useMemo(()=>t.reduce((n,r)=>{const{sensor:a}=r,s=a.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,r)}));return[...n,...s]},[]),[t,e])}var i0;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(i0||(i0={}));var nF;(function(t){t.Optimized="optimized"})(nF||(nF={}));const WW=new Map;function iQe(t,e){let{dragging:n,dependencies:r,config:a}=e;const[s,o]=w.useState(null),{frequency:l,measure:c,strategy:u}=a,d=w.useRef(t),h=g(),f=r0(h),p=w.useCallback(function(y){y===void 0&&(y=[]),!f.current&&o(_=>_===null?y:_.concat(y.filter(N=>!_.includes(N))))},[f]),x=w.useRef(null),v=K0(y=>{if(h&&!n)return WW;if(!y||y===WW||d.current!==t||s!=null){const _=new Map;for(let N of t){if(!N)continue;if(s&&s.length>0&&!s.includes(N.id)&&N.rect.current){_.set(N.id,N.rect.current);continue}const k=N.node.current,A=k?new lI(c(k),k):null;N.rect.current=A,A&&_.set(N.id,A)}return _}return y},[t,s,n,h,c]);return w.useEffect(()=>{d.current=t},[t]),w.useEffect(()=>{h||p()},[n,h]),w.useEffect(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),w.useEffect(()=>{h||typeof l!="number"||x.current!==null||(x.current=setTimeout(()=>{p(),x.current=null},l))},[l,h,p,...r]),{droppableRects:v,measureDroppableContainers:p,measuringScheduled:s!=null};function g(){switch(u){case i0.Always:return!1;case i0.BeforeDragging:return n;default:return!n}}}function jie(t,e){return K0(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function sQe(t,e){return jie(t,e)}function oQe(t){let{callback:e,disabled:n}=t;const r=sI(e),a=w.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return w.useEffect(()=>()=>a?.disconnect(),[a]),a}function AA(t){let{callback:e,disabled:n}=t;const r=sI(e),a=w.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return w.useEffect(()=>()=>a?.disconnect(),[a]),a}function lQe(t){return new lI(dx(t),t)}function KW(t,e,n){e===void 0&&(e=lQe);const[r,a]=w.useState(null);function s(){a(c=>{if(!t)return null;if(t.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=e(t);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const o=oQe({callback(c){if(t)for(const u of c){const{type:d,target:h}=u;if(d==="childList"&&h instanceof HTMLElement&&h.contains(t)){s();break}}}}),l=AA({callback:s});return $c(()=>{s(),t?(l?.observe(t),o?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),o?.disconnect())},[t]),r}function cQe(t){const e=jie(t);return Nie(t,e)}const XW=[];function uQe(t){const e=w.useRef(t),n=K0(r=>t?r&&r!==XW&&t&&e.current&&t.parentNode===e.current.parentNode?r:NA(t):XW,[t]);return w.useEffect(()=>{e.current=t},[t]),n}function dQe(t){const[e,n]=w.useState(null),r=w.useRef(t),a=w.useCallback(s=>{const o=_2(s.target);o&&n(l=>l?(l.set(o,eF(o)),new Map(l)):null)},[]);return w.useEffect(()=>{const s=r.current;if(t!==s){o(s);const l=t.map(c=>{const u=_2(c);return u?(u.addEventListener("scroll",a,{passive:!0}),[u,eF(u)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),r.current=t}return()=>{o(t),o(s)};function o(l){l.forEach(c=>{const u=_2(c);u?.removeEventListener("scroll",a)})}},[a,t]),w.useMemo(()=>t.length?e?Array.from(e.values()).reduce((s,o)=>sb(s,o),tc):Pie(t):tc,[t,e])}function YW(t,e){e===void 0&&(e=[]);const n=w.useRef(null);return w.useEffect(()=>{n.current=null},e),w.useEffect(()=>{const r=t!==tc;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?a0(t,n.current):tc}function hQe(t){w.useEffect(()=>{if(!_A)return;const e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function mQe(t,e){return w.useMemo(()=>t.reduce((n,r)=>{let{eventName:a,handler:s}=r;return n[a]=o=>{s(o,e)},n},{}),[t,e])}function Die(t){return w.useMemo(()=>t?OYe(t):null,[t])}const QW=[];function fQe(t,e){e===void 0&&(e=dx);const[n]=t,r=Die(n?uo(n):null),[a,s]=w.useState(QW);function o(){s(()=>t.length?t.map(c=>Tie(c)?r:new lI(e(c),c)):QW)}const l=AA({callback:o});return $c(()=>{l?.disconnect(),o(),t.forEach(c=>l?.observe(c))},[t]),a}function pQe(t){if(!t)return null;if(t.children.length>1)return t;const e=t.children[0];return W0(e)?e:t}function gQe(t){let{measure:e}=t;const[n,r]=w.useState(null),a=w.useCallback(u=>{for(const{target:d}of u)if(W0(d)){r(h=>{const f=e(d);return h?{...h,width:f.width,height:f.height}:f});break}},[e]),s=AA({callback:a}),o=w.useCallback(u=>{const d=pQe(u);s?.disconnect(),d&&s?.observe(d),r(d?e(d):null)},[e,s]),[l,c]=DC(o);return w.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const bQe=[{sensor:kA,options:{}},{sensor:CA,options:{}}],xQe={current:{}},h1={draggable:{measure:$W},droppable:{measure:$W,strategy:i0.WhileDragging,frequency:nF.Optimized},dragOverlay:{measure:dx}};class uv extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const yQe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new uv,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:RC},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:h1,measureDroppableContainers:RC,windowRect:null,measuringScheduled:!1},vQe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:RC,draggableNodes:new Map,over:null,measureDroppableContainers:RC},TA=w.createContext(vQe),Rie=w.createContext(yQe);function wQe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new uv}}}function SQe(t,e){switch(e.type){case di.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case di.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case di.DragEnd:case di.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case di.RegisterDroppable:{const{element:n}=e,{id:r}=n,a=new uv(t.droppable.containers);return a.set(r,n),{...t,droppable:{...t.droppable,containers:a}}}case di.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=e,s=t.droppable.containers.get(n);if(!s||r!==s.key)return t;const o=new uv(t.droppable.containers);return o.set(n,{...s,disabled:a}),{...t,droppable:{...t.droppable,containers:o}}}case di.UnregisterDroppable:{const{id:n,key:r}=e,a=t.droppable.containers.get(n);if(!a||r!==a.key)return t;const s=new uv(t.droppable.containers);return s.delete(n),{...t,droppable:{...t.droppable,containers:s}}}default:return t}}function _Qe(t){let{disabled:e}=t;const{active:n,activatorEvent:r,draggableNodes:a}=w.useContext(TA),s=ZR(r),o=ZR(n?.id);return w.useEffect(()=>{if(!e&&!r&&s&&o!=null){if(!oI(s)||document.activeElement===s.target)return;const l=a.get(o);if(!l)return;const{activatorNode:c,node:u}=l;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const h=bYe(d);if(h){h.focus();break}}})}},[r,e,a,o,s]),null}function NQe(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((a,s)=>s({transform:a,...r}),n):n}function CQe(t){return w.useMemo(()=>({draggable:{...h1.draggable,...t?.draggable},droppable:{...h1.droppable,...t?.droppable},dragOverlay:{...h1.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function kQe(t){let{activeNode:e,measure:n,initialRect:r,config:a=!0}=t;const s=w.useRef(!1),{x:o,y:l}=typeof a=="boolean"?{x:a,y:a}:a;$c(()=>{if(!o&&!l||!e){s.current=!1;return}if(s.current||!r)return;const u=e?.node.current;if(!u||u.isConnected===!1)return;const d=n(u),h=Nie(d,r);if(o||(h.x=0),l||(h.y=0),s.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const f=Cie(u);f&&f.scrollBy({top:h.y,left:h.x})}},[e,o,l,r,n])}const Fie=w.createContext({...tc,scaleX:1,scaleY:1});var hh;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(hh||(hh={}));const Lie=w.memo(function(e){var n,r,a,s;let{id:o,accessibility:l,autoScroll:c=!0,children:u,sensors:d=bQe,collisionDetection:h=PYe,measuring:f,modifiers:p,...x}=e;const v=w.useReducer(SQe,void 0,wQe),[g,y]=v,[_,N]=_Ye(),[k,A]=w.useState(hh.Uninitialized),M=k===hh.Initialized,{draggable:{active:C,nodes:j,translate:P},droppable:{containers:E}}=g,U=C!=null?j.get(C):null,L=w.useRef({initial:null,translated:null}),B=w.useMemo(()=>{var We;return C!=null?{id:C,data:(We=U?.data)!=null?We:xQe,rect:L}:null},[C,U]),D=w.useRef(null),[$,G]=w.useState(null),[z,W]=w.useState(null),X=r0(x,Object.values(x)),ae=X0("DndDescribedBy",o),H=w.useMemo(()=>E.getEnabled(),[E]),K=CQe(f),{droppableRects:te,measureDroppableContainers:Z,measuringScheduled:ve}=iQe(H,{dragging:M,dependencies:[P.x,P.y],config:K.droppable}),ce=rQe(j,C),ee=w.useMemo(()=>z?JR(z):null,[z]),je=De(),he=sQe(ce,K.draggable.measure);kQe({activeNode:C!=null?j.get(C):null,config:je.layoutShiftCompensation,initialRect:he,measure:K.draggable.measure});const oe=KW(ce,K.draggable.measure,he),_e=KW(ce?ce.parentElement:null),ie=w.useRef({activatorEvent:null,active:null,activeNode:ce,collisionRect:null,collisions:null,droppableRects:te,draggableNodes:j,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ze=E.getNodeFor((n=ie.current.over)==null?void 0:n.id),V=gQe({measure:K.dragOverlay.measure}),Y=(r=V.nodeRef.current)!=null?r:ce,me=M?(a=V.rect)!=null?a:oe:null,Q=!!(V.nodeRef.current&&V.rect),se=cQe(Q?null:oe),de=Die(Y?uo(Y):null),Le=uQe(M?ze??ce:null),Ne=fQe(Le),be=NQe(p,{transform:{x:P.x-se.x,y:P.y-se.y,scaleX:1,scaleY:1},activatorEvent:z,active:B,activeNodeRect:oe,containerNodeRect:_e,draggingNodeRect:me,over:ie.current.over,overlayNodeRect:V.rect,scrollableAncestors:Le,scrollableAncestorRects:Ne,windowRect:de}),O=ee?sb(ee,P):null,R=dQe(Le),q=YW(R),J=YW(R,[oe]),fe=sb(be,q),le=me?DYe(me,be):null,Be=B&&le?h({active:B,collisionRect:le,droppableRects:te,droppableContainers:H,pointerCoordinates:O}):null,Ie=Sie(Be,"id"),[Ke,Oe]=w.useState(null),pe=Q?be:sb(be,J),xe=EYe(pe,(s=Ke?.rect)!=null?s:null,oe),ke=w.useRef(null),ge=w.useCallback((We,Ae)=>{let{sensor:Re,options:$e}=Ae;if(D.current==null)return;const ht=j.get(D.current);if(!ht)return;const At=We.nativeEvent,Dt=new Re({active:D.current,activeNode:ht,event:At,options:$e,context:ie,onAbort(kt){if(!j.get(kt))return;const{onDragAbort:bt}=X.current,yt={id:kt};bt?.(yt),_({type:"onDragAbort",event:yt})},onPending(kt,Ue,bt,yt){if(!j.get(kt))return;const{onDragPending:Cn}=X.current,vr={id:kt,constraint:Ue,initialCoordinates:bt,offset:yt};Cn?.(vr),_({type:"onDragPending",event:vr})},onStart(kt){const Ue=D.current;if(Ue==null)return;const bt=j.get(Ue);if(!bt)return;const{onDragStart:yt}=X.current,Gt={activatorEvent:At,active:{id:Ue,data:bt.data,rect:L}};Fu.unstable_batchedUpdates(()=>{yt?.(Gt),A(hh.Initializing),y({type:di.DragStart,initialCoordinates:kt,active:Ue}),_({type:"onDragStart",event:Gt}),G(ke.current),W(At)})},onMove(kt){y({type:di.DragMove,coordinates:kt})},onEnd:It(di.DragEnd),onCancel:It(di.DragCancel)});ke.current=Dt;function It(kt){return async function(){const{active:bt,collisions:yt,over:Gt,scrollAdjustedTranslate:Cn}=ie.current;let vr=null;if(bt&&Cn){const{cancelDrop:Qn}=X.current;vr={activatorEvent:At,active:bt,collisions:yt,delta:Cn,over:Gt},kt===di.DragEnd&&typeof Qn=="function"&&await Promise.resolve(Qn(vr))&&(kt=di.DragCancel)}D.current=null,Fu.unstable_batchedUpdates(()=>{y({type:kt}),A(hh.Uninitialized),Oe(null),G(null),W(null),ke.current=null;const Qn=kt===di.DragEnd?"onDragEnd":"onDragCancel";if(vr){const tr=X.current[Qn];tr?.(vr),_({type:Qn,event:vr})}})}}},[j]),we=w.useCallback((We,Ae)=>(Re,$e)=>{const ht=Re.nativeEvent,At=j.get($e);if(D.current!==null||!At||ht.dndKit||ht.defaultPrevented)return;const Dt={active:At};We(Re,Ae.options,Dt)===!0&&(ht.dndKit={capturedBy:Ae.sensor},D.current=$e,ge(Re,Ae))},[j,ge]),qe=aQe(d,we);hQe(d),$c(()=>{oe&&k===hh.Initializing&&A(hh.Initialized)},[oe,k]),w.useEffect(()=>{const{onDragMove:We}=X.current,{active:Ae,activatorEvent:Re,collisions:$e,over:ht}=ie.current;if(!Ae||!Re)return;const At={active:Ae,activatorEvent:Re,collisions:$e,delta:{x:fe.x,y:fe.y},over:ht};Fu.unstable_batchedUpdates(()=>{We?.(At),_({type:"onDragMove",event:At})})},[fe.x,fe.y]),w.useEffect(()=>{const{active:We,activatorEvent:Ae,collisions:Re,droppableContainers:$e,scrollAdjustedTranslate:ht}=ie.current;if(!We||D.current==null||!Ae||!ht)return;const{onDragOver:At}=X.current,Dt=$e.get(Ie),It=Dt&&Dt.rect.current?{id:Dt.id,rect:Dt.rect.current,data:Dt.data,disabled:Dt.disabled}:null,kt={active:We,activatorEvent:Ae,collisions:Re,delta:{x:ht.x,y:ht.y},over:It};Fu.unstable_batchedUpdates(()=>{Oe(It),At?.(kt),_({type:"onDragOver",event:kt})})},[Ie]),$c(()=>{ie.current={activatorEvent:z,active:B,activeNode:ce,collisionRect:le,collisions:Be,droppableRects:te,draggableNodes:j,draggingNode:Y,draggingNodeRect:me,droppableContainers:E,over:Ke,scrollableAncestors:Le,scrollAdjustedTranslate:fe},L.current={initial:me,translated:le}},[B,ce,Be,le,j,Y,me,te,E,Ke,Le,fe]),eQe({...je,delta:P,draggingRect:le,pointerCoordinates:O,scrollableAncestors:Le,scrollableAncestorRects:Ne});const Ee=w.useMemo(()=>({active:B,activeNode:ce,activeNodeRect:oe,activatorEvent:z,collisions:Be,containerNodeRect:_e,dragOverlay:V,draggableNodes:j,droppableContainers:E,droppableRects:te,over:Ke,measureDroppableContainers:Z,scrollableAncestors:Le,scrollableAncestorRects:Ne,measuringConfiguration:K,measuringScheduled:ve,windowRect:de}),[B,ce,oe,z,Be,_e,V,j,E,te,Ke,Z,Le,Ne,K,ve,de]),tt=w.useMemo(()=>({activatorEvent:z,activators:qe,active:B,activeNodeRect:oe,ariaDescribedById:{draggable:ae},dispatch:y,draggableNodes:j,over:Ke,measureDroppableContainers:Z}),[z,qe,B,oe,y,ae,j,Ke,Z]);return Hr.createElement(xie.Provider,{value:N},Hr.createElement(TA.Provider,{value:tt},Hr.createElement(Rie.Provider,{value:Ee},Hr.createElement(Fie.Provider,{value:xe},u)),Hr.createElement(_Qe,{disabled:l?.restoreFocus===!1})),Hr.createElement(kYe,{...l,hiddenTextDescribedById:ae}));function De(){const We=$?.autoScrollEnabled===!1,Ae=typeof c=="object"?c.enabled===!1:c===!1,Re=M&&!We&&!Ae;return typeof c=="object"?{...c,enabled:Re}:{enabled:Re}}}),AQe=w.createContext(null),ZW="button",TQe="Draggable";function MQe(t){let{id:e,data:n,disabled:r=!1,attributes:a}=t;const s=X0(TQe),{activators:o,activatorEvent:l,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:h,over:f}=w.useContext(TA),{role:p=ZW,roleDescription:x="draggable",tabIndex:v=0}=a??{},g=c?.id===e,y=w.useContext(g?Fie:AQe),[_,N]=DC(),[k,A]=DC(),M=mQe(o,e),C=r0(n);$c(()=>(h.set(e,{id:e,key:s,node:_,activatorNode:k,data:C}),()=>{const P=h.get(e);P&&P.key===s&&h.delete(e)}),[h,e]);const j=w.useMemo(()=>({role:p,tabIndex:v,"aria-disabled":r,"aria-pressed":g&&p===ZW?!0:void 0,"aria-roledescription":x,"aria-describedby":d.draggable}),[r,p,v,g,x,d.draggable]);return{active:c,activatorEvent:l,activeNodeRect:u,attributes:j,isDragging:g,listeners:r?void 0:M,node:_,over:f,setNodeRef:N,setActivatorNodeRef:A,transform:y}}function PQe(){return w.useContext(Rie)}const EQe="Droppable",jQe={timeout:25};function DQe(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:a}=t;const s=X0(EQe),{active:o,dispatch:l,over:c,measureDroppableContainers:u}=w.useContext(TA),d=w.useRef({disabled:n}),h=w.useRef(!1),f=w.useRef(null),p=w.useRef(null),{disabled:x,updateMeasurementsFor:v,timeout:g}={...jQe,...a},y=r0(v??r),_=w.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{u(Array.isArray(y.current)?y.current:[y.current]),p.current=null},g)},[g]),N=AA({callback:_,disabled:x||!o}),k=w.useCallback((j,P)=>{N&&(P&&(N.unobserve(P),h.current=!1),j&&N.observe(j))},[N]),[A,M]=DC(k),C=r0(e);return w.useEffect(()=>{!N||!A.current||(N.disconnect(),h.current=!1,N.observe(A.current))},[A,N]),w.useEffect(()=>(l({type:di.RegisterDroppable,element:{id:r,key:s,disabled:n,node:A,rect:f,data:C}}),()=>l({type:di.UnregisterDroppable,key:s,id:r})),[r]),w.useEffect(()=>{n!==d.current.disabled&&(l({type:di.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,l]),{active:o,rect:f,isOver:c?.id===r,node:A,over:c,setNodeRef:M}}function MA(t,e,n){const r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function RQe(t,e){return t.reduce((n,r,a)=>{const s=e.get(r);return s&&(n[a]=s),n},Array(t.length))}function L_(t){return t!==null&&t>=0}function FQe(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function LQe(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}const uI=t=>{let{rects:e,activeIndex:n,overIndex:r,index:a}=t;const s=MA(e,r,n),o=e[a],l=s[a];return!l||!o?null:{x:l.left-o.left,y:l.top-o.top,scaleX:l.width/o.width,scaleY:l.height/o.height}},O_={scaleX:1,scaleY:1},OQe=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:a,rects:s,overIndex:o}=t;const l=(e=s[n])!=null?e:r;if(!l)return null;if(a===n){const u=s[o];return u?{x:0,y:n<o?u.top+u.height-(l.top+l.height):u.top-l.top,...O_}:null}const c=IQe(s,a,n);return a>n&&a<=o?{x:0,y:-l.height-c,...O_}:a<n&&a>=o?{x:0,y:l.height+c,...O_}:{x:0,y:0,...O_}};function IQe(t,e,n){const r=t[e],a=t[e-1],s=t[e+1];return r?n<e?a?r.top-(a.top+a.height):s?s.top-(r.top+r.height):0:s?s.top-(r.top+r.height):a?r.top-(a.top+a.height):0:0}const Oie="Sortable",Iie=Hr.createContext({activeIndex:-1,containerId:Oie,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:uI,disabled:{draggable:!1,droppable:!1}});function zie(t){let{children:e,id:n,items:r,strategy:a=uI,disabled:s=!1}=t;const{active:o,dragOverlay:l,droppableRects:c,over:u,measureDroppableContainers:d}=PQe(),h=X0(Oie,n),f=l.rect!==null,p=w.useMemo(()=>r.map(M=>typeof M=="object"&&"id"in M?M.id:M),[r]),x=o!=null,v=o?p.indexOf(o.id):-1,g=u?p.indexOf(u.id):-1,y=w.useRef(p),_=!FQe(p,y.current),N=g!==-1&&v===-1||_,k=LQe(s);$c(()=>{_&&x&&d(p)},[_,p,x,d]),w.useEffect(()=>{y.current=p},[p]);const A=w.useMemo(()=>({activeIndex:v,containerId:h,disabled:k,disableTransforms:N,items:p,overIndex:g,useDragOverlay:f,sortedRects:RQe(p,c),strategy:a}),[v,h,k.draggable,k.droppable,N,p,g,c,f,a]);return Hr.createElement(Iie.Provider,{value:A},e)}const zQe=t=>{let{id:e,items:n,activeIndex:r,overIndex:a}=t;return MA(n,r,a).indexOf(e)},UQe=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:a,items:s,newIndex:o,previousItems:l,previousContainerId:c,transition:u}=t;return!u||!r||l!==s&&a===o?!1:n?!0:o!==a&&e===c},BQe={duration:200,easing:"ease"},Uie="transform",HQe=Ob.Transition.toString({property:Uie,duration:0,easing:"linear"}),$Qe={roleDescription:"sortable"};function VQe(t){let{disabled:e,index:n,node:r,rect:a}=t;const[s,o]=w.useState(null),l=w.useRef(n);return $c(()=>{if(!e&&n!==l.current&&r.current){const c=a.current;if(c){const u=dx(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&o(d)}}n!==l.current&&(l.current=n)},[e,n,r,a]),w.useEffect(()=>{s&&o(null)},[s]),s}function Bie(t){let{animateLayoutChanges:e=UQe,attributes:n,disabled:r,data:a,getNewIndex:s=zQe,id:o,strategy:l,resizeObserverConfig:c,transition:u=BQe}=t;const{items:d,containerId:h,activeIndex:f,disabled:p,disableTransforms:x,sortedRects:v,overIndex:g,useDragOverlay:y,strategy:_}=w.useContext(Iie),N=qQe(r,p),k=d.indexOf(o),A=w.useMemo(()=>({sortable:{containerId:h,index:k,items:d},...a}),[h,a,k,d]),M=w.useMemo(()=>d.slice(d.indexOf(o)),[d,o]),{rect:C,node:j,isOver:P,setNodeRef:E}=DQe({id:o,data:A,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...c}}),{active:U,activatorEvent:L,activeNodeRect:B,attributes:D,setNodeRef:$,listeners:G,isDragging:z,over:W,setActivatorNodeRef:X,transform:ae}=MQe({id:o,data:A,attributes:{...$Qe,...n},disabled:N.draggable}),H=mYe(E,$),K=!!U,te=K&&!x&&L_(f)&&L_(g),Z=!y&&z,ve=Z&&te?ae:null,ee=te?ve??(l??_)({rects:v,activeNodeRect:B,activeIndex:f,overIndex:g,index:k}):null,je=L_(f)&&L_(g)?s({id:o,items:d,activeIndex:f,overIndex:g}):k,he=U?.id,oe=w.useRef({activeId:he,items:d,newIndex:je,containerId:h}),_e=d!==oe.current.items,ie=e({active:U,containerId:h,isDragging:z,isSorting:K,id:o,index:k,items:d,newIndex:oe.current.newIndex,previousItems:oe.current.items,previousContainerId:oe.current.containerId,transition:u,wasDragging:oe.current.activeId!=null}),ze=VQe({disabled:!ie,index:k,node:j,rect:C});return w.useEffect(()=>{K&&oe.current.newIndex!==je&&(oe.current.newIndex=je),h!==oe.current.containerId&&(oe.current.containerId=h),d!==oe.current.items&&(oe.current.items=d)},[K,je,h,d]),w.useEffect(()=>{if(he===oe.current.activeId)return;if(he!=null&&oe.current.activeId==null){oe.current.activeId=he;return}const Y=setTimeout(()=>{oe.current.activeId=he},50);return()=>clearTimeout(Y)},[he]),{active:U,activeIndex:f,attributes:D,data:A,rect:C,index:k,newIndex:je,items:d,isOver:P,isSorting:K,isDragging:z,listeners:G,node:j,overIndex:g,over:W,setNodeRef:H,setActivatorNodeRef:X,setDroppableNodeRef:E,setDraggableNodeRef:$,transform:ze??ee,transition:V()};function V(){if(ze||_e&&oe.current.newIndex===k)return HQe;if(!(Z&&!oI(L)||!u)&&(K||ie))return Ob.Transition.toString({...u,property:Uie})}}function qQe(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function OC(t){if(!t)return!1;const e=t.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const GQe=[rr.Down,rr.Right,rr.Up,rr.Left],Hie=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:s,over:o,scrollableAncestors:l}}=e;if(GQe.includes(t.code)){if(t.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const f=a.get(h.id);if(f)switch(t.code){case rr.Down:r.top<f.top&&c.push(h);break;case rr.Up:r.top>f.top&&c.push(h);break;case rr.Left:r.left>f.left&&c.push(h);break;case rr.Right:r.left<f.left&&c.push(h);break}});const u=TYe({collisionRect:r,droppableRects:a,droppableContainers:c});let d=Sie(u,"id");if(d===o?.id&&u.length>1&&(d=u[1].id),d!=null){const h=s.get(n.id),f=s.get(d),p=f?a.get(f.id):null,x=f?.node.current;if(x&&p&&h&&f){const g=NA(x).some((M,C)=>l[C]!==M),y=$ie(h,f),_=WQe(h,f),N=g||!y?{x:0,y:0}:{x:_?r.width-p.width:0,y:_?r.height-p.height:0},k={x:p.left,y:p.top};return N.x&&N.y?k:a0(k,N)}}}};function $ie(t,e){return!OC(t)||!OC(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function WQe(t,e){return!OC(t)||!OC(e)||!$ie(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}function Vie(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}function KQe({status:t,waitingReason:e,printerState:n,t:r}){if(t==="pending"&&e)return i.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-400 bg-purple-400/10 border-purple-400/20",children:[i.jsx(Wn,{className:"w-3.5 h-3.5"}),r("queue.status.waiting")]});if(t==="printing"&&n==="PAUSE")return i.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-400 bg-yellow-400/10 border-yellow-400/20",children:[i.jsx(YC,{className:"w-3.5 h-3.5"}),r("queue.status.paused")]});const a={pending:{icon:Wn,color:"text-status-warning bg-status-warning/10 border-status-warning/20",label:r("queue.status.pending")},printing:{icon:io,color:"text-blue-400 bg-blue-400/10 border-blue-400/20",label:r("queue.status.printing")},completed:{icon:pr,color:"text-status-ok bg-status-ok/10 border-status-ok/20",label:r("queue.status.completed")},failed:{icon:mi,color:"text-status-error bg-status-error/10 border-status-error/20",label:r("queue.status.failed")},skipped:{icon:TF,color:"text-orange-400 bg-orange-400/10 border-orange-400/20",label:r("queue.status.skipped")},cancelled:{icon:Lt,color:"text-gray-400 bg-gray-400/10 border-gray-400/20",label:r("queue.status.cancelled")}},{icon:s,color:o,label:l}=a[t];return i.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${o}`,children:[i.jsx(s,{className:"w-3.5 h-3.5"}),l]})}function XQe({selectedCount:t,printers:e,onSave:n,onClose:r,isSaving:a,t:s}){const[o,l]=w.useState("unchanged"),[c,u]=w.useState("unchanged"),[d,h]=w.useState("unchanged"),[f,p]=w.useState("unchanged"),[x,v]=w.useState("unchanged"),[g,y]=w.useState("unchanged"),[_,N]=w.useState("unchanged"),[k,A]=w.useState("unchanged"),[M,C]=w.useState("unchanged"),[j,P]=w.useState("unchanged"),E=()=>{const L={};o!=="unchanged"&&(L.printer_id=o),c!=="unchanged"&&(L.manual_start=c),d!=="unchanged"&&(L.auto_off_after=d),f!=="unchanged"&&(L.require_previous_success=f),x!=="unchanged"&&(L.bed_levelling=x),g!=="unchanged"&&(L.flow_cali=g),_!=="unchanged"&&(L.vibration_cali=_),k!=="unchanged"&&(L.layer_inspect=k),M!=="unchanged"&&(L.timelapse=M),j!=="unchanged"&&(L.use_ams=j),n(L)},U=o!=="unchanged"||c!=="unchanged"||d!=="unchanged"||f!=="unchanged"||x!=="unchanged"||g!=="unchanged"||_!=="unchanged"||k!=="unchanged"||M!=="unchanged"||j!=="unchanged";return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s("queue.bulkEdit.title",{count:t})}),i.jsx("button",{onClick:r,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:s("queue.bulkEdit.description")}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printer")}),i.jsxs("select",{value:o===null?"null":o==="unchanged"?"unchanged":String(o),onChange:L=>{const B=L.target.value;l(B==="unchanged"?"unchanged":B==="null"?null:Number(B))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"unchanged",children:s("queue.bulkEdit.noChange")}),i.jsx("option",{value:"null",children:s("queue.filter.unassigned")}),e.map(L=>i.jsx("option",{value:L.id,children:L.name},L.id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.queueOptions")}),i.jsxs("div",{className:"space-y-2",children:[i.jsx(Au,{label:s("queue.bulkEdit.staged"),value:c,onChange:u,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.autoPowerOff"),value:d,onChange:h,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.requirePrevious"),value:f,onChange:p,t:s})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:s("queue.bulkEdit.printOptions")}),i.jsxs("div",{className:"space-y-2",children:[i.jsx(Au,{label:s("queue.bulkEdit.bedLevelling"),value:x,onChange:v,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.flowCalibration"),value:g,onChange:y,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.vibrationCalibration"),value:_,onChange:N,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.layerInspection"),value:k,onChange:A,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.timelapse"),value:M,onChange:C,t:s}),i.jsx(Au,{label:s("queue.bulkEdit.useAms"),value:j,onChange:P,t:s})]})]})]}),i.jsxs("div",{className:"flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:r,children:s("common.cancel")}),i.jsx(Ce,{onClick:E,disabled:!U||a,children:s(a?"common.saving":"queue.bulkEdit.applyChanges")})]})]})})}function Au({label:t,value:e,onChange:n,t:r}){return i.jsxs("div",{className:"flex items-center justify-between py-1",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:t}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5",children:[i.jsx("button",{onClick:()=>n("unchanged"),className:`px-2 py-1 text-xs rounded ${e==="unchanged"?"bg-bambu-dark-tertiary text-white":"text-bambu-gray hover:text-white"}`,children:"—"}),i.jsx("button",{onClick:()=>n(!1),className:`px-2 py-1 text-xs rounded ${e===!1?"bg-red-500/20 text-red-400":"text-bambu-gray hover:text-white"}`,children:r("common.off")}),i.jsx("button",{onClick:()=>n(!0),className:`px-2 py-1 text-xs rounded ${e===!0?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:r("common.on")})]})]})}function k2({item:t,position:e,onEdit:n,onCancel:r,onRemove:a,onStop:s,onRequeue:o,onStart:l,timeFormat:c="system",isSelected:u=!1,onToggleSelect:d,hasPermission:h,canModify:f,printerState:p,t:x}){const{data:v}=Je({queryKey:["printerStatus",t.printer_id],queryFn:()=>ne.getPrinterStatus(t.printer_id),refetchInterval:3e4,enabled:t.printer_id!=null&&p==="printing"}),g=!!t.library_file_id&&!t.archive_id,{data:y}=Je({queryKey:["archive-plates",t.archive_id],queryFn:()=>ne.getArchivePlates(t.archive_id),enabled:!!t.archive_id&&!g}),{data:_}=Je({queryKey:["library-file-plates",t.library_file_id],queryFn:()=>ne.getLibraryFilePlates(t.library_file_id),enabled:g&&!!t.library_file_id}),N=g?_:y,k=N?.plates??[],A=h("queue:reorder"),{attributes:M,listeners:C,setNodeRef:j,transform:P,transition:E,isDragging:U}=Bie({id:t.id,disabled:t.status!=="pending"||!A}),L={transform:Ob.Transform.toString(P),transition:E},B=t.status==="printing",D=t.status==="pending",$=["completed","failed","skipped","cancelled"].includes(t.status),G=D&&d;return i.jsxs("div",{ref:j,style:L,className:`
  8292. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  8293. ${U?"opacity-50 scale-[1.02] shadow-xl z-50":""}
  8294. ${B?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""}
  8295. ${u&&G?"sm:border-bambu-dark-tertiary border-bambu-green/40":""}
  8296. ${!u&&!B?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""}
  8297. ${G?"sm:cursor-default":""}
  8298. `,onClick:G?()=>{window.innerWidth<640&&d()}:void 0,children:[G&&u&&i.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),i.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[D&&d&&i.jsx("button",{onClick:z=>{z.stopPropagation(),d()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&i.jsx(aa,{className:"w-4 h-4"})}),D?i.jsx("div",{...M,...C,className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation shrink-0",children:i.jsx(Eh,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?i.jsxs("div",{className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0",children:["#",e]}):i.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),i.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?i.jsx("img",{src:t.plate_id!=null?ne.getArchivePlateThumbnail(t.archive_id,t.plate_id):ne.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?i.jsx("img",{src:t.plate_id!=null?ne.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ne.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(fi,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsxs("p",{className:"text-sm sm:text-base text-white font-medium truncate",children:[t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,(N?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${k.find(z=>z.index===t.plate_id)?.name||x("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?i.jsx(Ks,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:i.jsx(Xr,{className:"w-3.5 h-3.5"})}):t.library_file_id?i.jsx(Ks,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewInFileManager"),children:i.jsx(Xr,{className:"w-3.5 h-3.5"})}):null]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[i.jsxs("span",{className:`flex items-center gap-1 sm:gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model?"text-blue-400":""}`,children:[i.jsx(gr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),i.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model?`${x("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?x("queue.filter.unassigned"):t.printer_name||`${x("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[i.jsx(Lu,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Qs(t.print_time_seconds)]}),t.filament_used_grams&&i.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[i.jsx(CX,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Vie(t.filament_used_grams)]}),t.created_by_username&&i.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[i.jsx(td,{className:"w-3.5 h-3.5"}),t.created_by_username]}),D&&!t.manual_start&&i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Wn,{className:"w-3.5 h-3.5"}),t.scheduled_time?new Date(t.scheduled_time).getTime()-Date.now()<-6e4?x?.("queue.time.overdue")??"Overdue":yv(t.scheduled_time,c,x):x?.("queue.time.asap")??"ASAP"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&i.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[i.jsx(gX,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.staged")]}),t.require_previous_success&&i.jsx("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:x("queue.badges.requiresPrevious")}),t.auto_off_after&&i.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[i.jsx(md,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.autoPowerOff")]})]}),B&&v&&i.jsxs("div",{className:"mt-2 sm:mt-3",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[i.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:i.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),i.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray",children:[v.remaining_time!=null&&v.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),Qs(v.remaining_time*60)]}),i.jsxs("span",{className:"text-bambu-green font-medium",title:x("printers.estimatedCompletion"),children:["ETA ",DF(v.remaining_time,c,x)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(fi,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&i.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[i.jsx(Ba,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),i.jsx("span",{children:t.waiting_reason})]}),t.error_message&&i.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),t.error_message]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:z=>z.stopPropagation(),children:[i.jsx(KQe,{status:t.status,waitingReason:t.waiting_reason,printerState:p,t:x}),i.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[B&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.stopPrint"):x("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:i.jsx(She,{className:"w-4 h-4"})}),D&&i.jsxs(i.Fragment,{children:[t.manual_start&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.startPrint"):x("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:i.jsx(io,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:n,disabled:!f("queue","update",t.created_by_id),title:f("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:r,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.cancel"):x("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),$&&i.jsxs(i.Fragment,{children:[i.jsx(Ce,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("queue:create")?x("queue.actions.requeue"):x("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:i.jsx(Ar,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:a,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})]})]})}function YQe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r,hasAnyPermission:a,canModify:s}=Ir(),[o,l]=w.useState(null),[c,u]=w.useState(""),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(null),[g,y]=w.useState(null),[_,N]=w.useState(null),[k,A]=w.useState([]),[M,C]=w.useState(!1),[j,P]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[E,U]=w.useState(()=>{const O=localStorage.getItem("queue.historySortAsc");return O!==null?O==="true":!1}),[L,B]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,$]=w.useState(()=>{const O=localStorage.getItem("queue.pendingSortAsc");return O!==null?O==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(E))},[E]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",L)},[L]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const G=yie(FC(kA,{activationConstraint:{distance:8}}),FC(CA,{coordinateGetter:Hie})),{data:z}=Je({queryKey:["settings"],queryFn:ne.getSettings}),W=z?.time_format||"system",{data:X,isLoading:ae}=Je({queryKey:["queue",o,c],queryFn:()=>ne.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:H}=Je({queryKey:["printers"],queryFn:()=>ne.getPrinters()}),K=st({mutationFn:O=>ne.cancelQueueItem(O),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),te=st({mutationFn:O=>ne.removeFromQueue(O),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),Z=st({mutationFn:O=>ne.stopQueueItem(O),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),ve=st({mutationFn:O=>ne.startQueueItem(O),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),ce=st({mutationFn:O=>ne.reorderQueue(O),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),ee=st({mutationFn:async()=>{const O=X?.filter(R=>["completed","failed","skipped","cancelled"].includes(R.status))||[];for(const R of O)await ne.removeFromQueue(R.id);return O.length},onSuccess:O=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:O}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),je=st({mutationFn:O=>ne.bulkUpdateQueue(O),onSuccess:O=>{e.invalidateQueries({queryKey:["queue"]}),A([]),C(!1),n(O.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),he=st({mutationFn:async O=>{for(const R of O)await ne.cancelQueueItem(R);return O.length},onSuccess:O=>{e.invalidateQueries({queryKey:["queue"]}),A([]),n(t("queue.toast.bulkCancelled",{count:O}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),oe=O=>{A(R=>R.includes(O)?R.filter(q=>q!==O):[...R,O])},_e=w.useMemo(()=>{const O=new Set;return H?.forEach(R=>{R.location&&O.add(R.location)}),X?.forEach(R=>{R.target_location&&O.add(R.target_location)}),Array.from(O).sort()},[H,X]),ie=w.useCallback(O=>d?O.target_location?O.target_location===d:O.printer_id?H?.find(q=>q.id===O.printer_id)?.location===d:!1:!0,[d,H]),ze=w.useMemo(()=>{let O=X?.filter(q=>q.status==="pending")||[];d&&(O=O.filter(ie));const R=q=>{if(!q.scheduled_time)return 0;const J=new Date(q.scheduled_time).getTime(),fe=Date.now()+4320*60*60*1e3;return J>fe?0:J};return[...O].sort((q,J)=>{let fe;if(L==="name"){const le=q.archive_name||q.library_file_name||"",Be=J.archive_name||J.library_file_name||"";fe=le.localeCompare(Be)}else L==="printer"?fe=(q.printer_name||"").localeCompare(J.printer_name||""):L==="time"?fe=R(q)-R(J):fe=q.position-J.position;return D?fe:-fe})},[X,L,D,ie,d]),V=()=>{const O=ze.map(R=>R.id);k.length===O.length?A([]):A(O)},Y=w.useMemo(()=>{let O=X?.filter(R=>R.status==="printing")||[];return d&&(O=O.filter(ie)),O},[X,d,ie]),me=w.useMemo(()=>{const O=new Set;return Y.forEach(R=>{R.printer_id&&O.add(R.printer_id)}),Array.from(O)},[Y]),Q=SF({queries:me.map(O=>({queryKey:["printerStatus",O],queryFn:()=>ne.getPrinterStatus(O),refetchInterval:5e3}))}),se=w.useMemo(()=>{const O={};return me.forEach((R,q)=>{const J=Q[q];J?.data?.state&&(O[R]=J.data.state)}),O},[me,Q]),de=w.useMemo(()=>{let O=X?.filter(R=>["completed","failed","skipped","cancelled"].includes(R.status))||[];return d&&(O=O.filter(ie)),[...O].sort((R,q)=>{let J;if(j==="name"){const fe=R.archive_name||R.library_file_name||"",le=q.archive_name||q.library_file_name||"";J=fe.localeCompare(le)}else j==="printer"?J=(R.printer_name||"").localeCompare(q.printer_name||""):J=new Date(q.completed_at||q.created_at).getTime()-new Date(R.completed_at||R.created_at).getTime();return E?-J:J})},[X,j,E,ie,d]),Le=w.useMemo(()=>ze.reduce((O,R)=>O+(R.print_time_seconds||0),0),[ze]),Ne=w.useMemo(()=>ze.reduce((O,R)=>O+(R.filament_used_grams||0),0),[ze]),be=O=>{const{active:R,over:q}=O;if(!q||R.id===q.id)return;const J=ze.findIndex(le=>le.id===R.id),fe=ze.findIndex(le=>le.id===q.id);if(J!==-1&&fe!==-1){const Be=MA(ze,J,fe).map((Ie,Ke)=>({id:Ie.id,position:Ke+1}));ce.mutate(Be)}};return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsx("div",{className:"flex items-center justify-between mb-8",children:i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx(bX,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2 sm:gap-3 lg:gap-4 mb-8",children:[i.jsx(wt,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-blue-500/20 flex items-center justify-center shrink-0",children:i.jsx(io,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Y.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.printing")})]})]})})}),i.jsx(wt,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center shrink-0",children:i.jsx(Wn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:ze.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.queued")})]})]})})}),i.jsx(wt,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center shrink-0",children:i.jsx(Lu,{className:"w-4 h-4 sm:w-5 sm:h-5 text-bambu-green"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Qs(Le)}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.totalTime")})]})]})})}),i.jsx(wt,{className:"bg-gradient-to-br from-purple-500/10 to-transparent border-purple-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-purple-500/20 flex items-center justify-center shrink-0",children:i.jsx(CX,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-500"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Vie(Ne)}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.totalWeight")})]})]})})}),i.jsx(wt,{className:"col-span-2 sm:col-span-1 bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-gray-500/20 flex items-center justify-center shrink-0",children:i.jsx(pr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:de.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.history")})]})]})})})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[i.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:o===-1?"unassigned":o||"",onChange:O=>{const R=O.target.value;l(R==="unassigned"?-1:R===""?null:Number(R))},children:[i.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),i.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),H?.map(O=>i.jsx("option",{value:O.id,children:O.name},O.id))]}),i.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:c,onChange:O=>u(O.target.value),children:[i.jsx("option",{value:"",children:t("queue.filter.allStatus")}),i.jsx("option",{value:"pending",children:t("queue.status.pending")}),i.jsx("option",{value:"printing",children:t("queue.status.printing")}),i.jsx("option",{value:"completed",children:t("queue.status.completed")}),i.jsx("option",{value:"failed",children:t("queue.status.failed")}),i.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),i.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),_e.length>0&&i.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:d,onChange:O=>h(O.target.value),children:[i.jsx("option",{value:"",children:t("queue.filter.allLocations")}),_e.map(O=>i.jsx("option",{value:O,children:O},O))]}),i.jsx("div",{className:"hidden sm:block flex-1"}),de.length>0&&i.jsxs(Ce,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>p(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[i.jsx(Jt,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):X?.length===0?i.jsxs(wt,{className:"p-12 text-center border-dashed",children:[i.jsx(ra,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),i.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),i.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):i.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[Y.length>0&&i.jsxs("div",{children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),i.jsx("div",{className:"space-y-2 sm:space-y-3",children:Y.map(O=>i.jsx(k2,{item:O,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:O}),onRequeue:()=>{},onStart:()=>{},timeFormat:W,hasPermission:r,canModify:s,printerState:O.printer_id?se[O.printer_id]:null,t},O.id))})]}),ze.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Wn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),i.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ze.length}),")"]}),i.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:L,onChange:O=>B(O.target.value),children:[i.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),i.jsx("option",{value:"name",children:t("queue.sort.byName")}),i.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),i.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>$(!D),title:t(D?"common.ascending":"common.descending"),className:"px-2",children:D?i.jsx(Mf,{className:"w-4 h-4"}):i.jsx(lb,{className:"w-4 h-4"})})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg",children:[i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:V,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[k.length===ze.length&&ze.length>0?i.jsx(oo,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4"}),k.length===ze.length&&ze.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),k.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:k.length})}),i.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>C(!0),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light",disabled:!a("queue:update_own","queue:update_all"),title:a("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[i.jsx($a,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>he.mutate(k),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:he.isPending||!a("queue:delete_own","queue:delete_all"),title:a("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[i.jsx(Lt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),i.jsx(Lie,{sensors:G,collisionDetection:_ie,onDragEnd:be,children:i.jsx(zie,{items:ze.map(O=>O.id),strategy:OQe,children:i.jsx("div",{className:"space-y-2 sm:space-y-3",children:ze.map((O,R)=>i.jsx(k2,{item:O,position:R+1,onEdit:()=>v(O),onCancel:()=>N({type:"cancel",item:O}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ve.mutate(O.id),timeFormat:W,isSelected:k.includes(O.id),onToggleSelect:()=>oe(O.id),hasPermission:r,canModify:s,t},O.id))})})})]}),de.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(pr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-bambu-gray"}),t("queue.sections.history"),i.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:de.length}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:j,onChange:O=>P(O.target.value),children:[i.jsx("option",{value:"date",children:t("queue.sort.byDate")}),i.jsx("option",{value:"name",children:t("queue.sort.byName")}),i.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>U(!E),title:t(E?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:E?i.jsx(Mf,{className:"w-4 h-4"}):i.jsx(lb,{className:"w-4 h-4"})})]})]}),i.jsx("div",{className:"space-y-2 sm:space-y-3",children:de.slice(0,20).map((O,R)=>i.jsx(k2,{item:O,position:R+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:O}),onStop:()=>{},onRequeue:()=>y(O),onStart:()=>{},timeFormat:W,hasPermission:r,canModify:s,t},O.id))})]})]}),x&&i.jsx(Xu,{mode:"edit-queue-item",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,queueItem:x,onClose:()=>v(null)}),g&&i.jsx(Xu,{mode:"add-to-queue",archiveId:g.archive_id??void 0,libraryFileId:g.library_file_id??void 0,archiveName:g.archive_name||g.library_file_name||`File #${g.archive_id||g.library_file_id}`,onClose:()=>y(null)}),_&&i.jsx(gn,{title:_.type==="cancel"?t("queue.confirm.cancelTitle"):_.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:_.type==="cancel"?t("queue.confirm.cancelMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):_.type==="stop"?t("queue.confirm.stopMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:_.type==="cancel"?t("queue.confirm.cancelButton"):_.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{_.type==="cancel"?K.mutate(_.item.id):_.type==="stop"?Z.mutate(_.item.id):te.mutate(_.item.id),N(null)},onCancel:()=>N(null)}),f&&i.jsx(gn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:de.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{ee.mutate(),p(!1)},onCancel:()=>p(!1)}),M&&i.jsx(XQe,{selectedCount:k.length,printers:H?.map(O=>({id:O.id,name:O.name}))||[],onSave:O=>{Object.keys(O).length>0&&je.mutate({item_ids:k,...O})},onClose:()=>C(!1),isSaving:je.isPending,t})]})}function QQe({printDates:t,months:e=3}){const n=w.useRef(null),[r,a]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const N=new ResizeObserver(k=>{const A=k[0]?.contentRect.width||0;a(A)});return N.observe(_),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach(U=>{const L=U.split("T")[0];_[L]=(_[L]||0)+1});const N=new Date,k=new Date(N);k.setMonth(k.getMonth()-e),k.setDate(k.getDate()-k.getDay());const A=[],M=[];let C=[],j=-1;const P=new Date(k);let E=0;for(;P<=N;)P.getDay()===0&&C.length>0&&(A.push(C),C=[],E++),P.getMonth()!==j&&(M.push({month:P.toLocaleDateString("en-US",{month:"short"}),weekIndex:E}),j=P.getMonth()),C.push(new Date(P)),P.setDate(P.getDate()+1);return C.length>0&&A.push(C),{weeks:A,monthLabels:M,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),u=_=>{if(_===0)return"bg-bambu-dark";const N=_/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,f=32,p=2,x=r-f-16,v=h>0?Math.floor((x-(h-1)*p)/h):12,g=Math.max(8,Math.min(20,v)),y=g<=10?10:12;return i.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&i.jsxs("div",{children:[i.jsx("div",{className:"flex mb-1",style:{marginLeft:f+4},children:o.map(({month:_,weekIndex:N},k)=>i.jsx("div",{className:"text-bambu-gray",style:{fontSize:y,marginLeft:k===0?0:`${(N-(o[k-1]?.weekIndex||0))*(g+p)-24}px`},children:_},k))}),i.jsxs("div",{className:"flex",style:{gap:p},children:[i.jsx("div",{className:"flex flex-col",style:{gap:p,marginRight:4,width:f},children:d.map((_,N)=>i.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:f,height:g,fontSize:y,visibility:N%2===1?"visible":"hidden"},children:_},_))}),s.map((_,N)=>i.jsx("div",{className:"flex flex-col",style:{gap:p},children:[0,1,2,3,4,5,6].map(k=>{const A=_.find(P=>P.getDay()===k);if(!A)return i.jsx("div",{style:{width:g,height:g}},k);const M=A.toISOString().split("T")[0],C=l[M]||0,j=M===new Date().toISOString().split("T")[0];return i.jsx("div",{className:`rounded-sm ${u(C)} ${j?"ring-1 ring-white":""}`,style:{width:g,height:g},title:`${A.toLocaleDateString()}: ${C} print${C!==1?"s":""}`},k)})},N))]}),i.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:y},children:[i.jsx("span",{children:"Less"}),i.jsxs("div",{className:"flex",style:{gap:p},children:[i.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:g,height:g}})]}),i.jsx("span",{children:"More"})]})]})})}const I_=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function ZQe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function JQe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),a=w.useMemo(()=>{const p=ZQe(n);return t.filter(x=>(hi(x.completed_at||x.created_at)||new Date(0))>=p)},[t,n]),s=w.useMemo(()=>{const p=new Map;return a.forEach(x=>{const v=hi(x.completed_at||x.created_at)||new Date,g=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`,y=p.get(g)||{date:g,filament:0,cost:0,prints:0};y.filament+=x.filament_used_grams||0,y.cost+=x.cost||0,y.prints+=x.quantity||1,p.set(g,y)}),Array.from(p.values()).sort((x,v)=>x.date.localeCompare(v.date)).map(x=>({...x,dateLabel:new Date(x.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[a]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return s;const p=new Map;return a.forEach(x=>{const v=hi(x.completed_at||x.created_at)||new Date,g=new Date(v);g.setDate(v.getDate()-v.getDay());const y=`${g.getFullYear()}-${String(g.getMonth()+1).padStart(2,"0")}-${String(g.getDate()).padStart(2,"0")}`,_=p.get(y)||{week:y,filament:0,cost:0,prints:0};_.filament+=x.filament_used_grams||0,_.cost+=x.cost||0,_.prints+=x.quantity||1,p.set(y,_)}),Array.from(p.values()).sort((x,v)=>x.week.localeCompare(v.week)).map(x=>({date:x.week,dateLabel:`Week of ${new Date(x.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...x}))},[a,s,n]),l=w.useMemo(()=>{const p=new Map;return a.forEach(x=>{const g=(x.filament_type||"Unknown").split(", ");g.forEach(y=>{const _=(x.filament_used_grams||0)/g.length;p.set(y,(p.get(y)||0)+_)})}),Array.from(p.entries()).map(([x,v])=>({name:x,value:Math.round(v)})).sort((x,v)=>v.value-x.value)},[a]),c=w.useMemo(()=>{const p=new Date,x=[];for(let v=5;v>=0;v--){const g=new Date(p.getFullYear(),p.getMonth()-v,1),y=new Date(p.getFullYear(),p.getMonth()-v+1,0),_=g.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(k=>{const A=hi(k.completed_at||k.created_at)||new Date(0);return A>=g&&A<=y});x.push({month:_,filament:Math.round(N.reduce((k,A)=>k+(A.filament_used_grams||0),0)),cost:N.reduce((k,A)=>k+(A.cost||0),0),prints:N.reduce((k,A)=>k+(A.quantity||1),0)})}return x},[t]),u=n==="7d"||n==="30d"?s:o,d=a.reduce((p,x)=>p+(x.filament_used_grams||0),0),h=a.reduce((p,x)=>p+(x.cost||0),0),f=a.reduce((p,x)=>p+(x.quantity||1),0);return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-2",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),i.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(p=>i.jsx("button",{onClick:()=>r(p),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===p?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:p==="all"?"All":p.replace("d","D")},p))})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Period Filament"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[(d/1e3).toFixed(2),"kg"]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Period Cost"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,h.toFixed(2)]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[f," prints"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Avg per Print"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[f>0?(d/f).toFixed(0):0,"g"]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,f>0?(h/f).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),i.jsx(n1,{width:"100%",height:250,children:i.jsxs(KHe,{data:u,children:[i.jsx("defs",{children:i.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[i.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),i.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),i.jsx(RN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),i.jsx(IN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),i.jsx(zN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),i.jsx(a1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:p=>[`${Number(p??0).toFixed(0)}g`,"Filament"]}),i.jsx(Wte,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):i.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(n1,{width:160,height:160,children:i.jsxs(GHe,{children:[i.jsx(yte,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((p,x)=>i.jsx(U0,{fill:I_[x%I_.length]},`cell-${x}`))}),i.jsx(a1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:p=>[`${p??0}g`,"Usage"]})]})}),i.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((p,x)=>{const v=l.reduce((y,_)=>y+_.value,0),g=v>0?(p.value/v*100).toFixed(0):0;return i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:I_[x%I_.length]}}),i.jsx("span",{className:"text-white truncate flex-1",children:p.name}),i.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[g,"%"]})]},p.name)})})]}):i.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),i.jsx(n1,{width:"100%",height:200,children:i.jsxs(RHe,{data:c,children:[i.jsx(RN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),i.jsx(IN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),i.jsx(zN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),i.jsx(a1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(p,x)=>[x==="filament"?`${p??0}g`:x==="cost"?`${e}${Number(p??0).toFixed(2)}`:p??0,x==="filament"?"Filament":x==="cost"?"Cost":"Prints"]}),i.jsx(OL,{}),i.jsx(Zte,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function eZe({id:t,title:e,component:n,isHidden:r,size:a,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:u,setNodeRef:d,transform:h,transition:f,isDragging:p}=Bie({id:t}),x={transform:Ob.Transform.toString(h),transition:f,opacity:p?.5:1};return r?null:i.jsxs("div",{ref:d,style:{...x,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{...c,...u,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:i.jsx(Eh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),i.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${a===1?"1/4":a===2?"1/2":"Full"} - Click to cycle`,children:a===4?i.jsx(kF,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):i.jsx(KC,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),i.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:i.jsx(u0,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),i.jsx("div",{className:"p-4",children:typeof n=="function"?n(a):n})]})}function tZe({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:a=!1,onResetLayout:s,renderControls:o}){const l=()=>{const j={};return t.forEach(P=>{j[P.id]=P.defaultSize||4}),j},[c,u]=w.useState(()=>{const j=localStorage.getItem(e);if(j)try{const P=JSON.parse(j);return P.sizes||(P.sizes=l()),P}catch{}return{order:t.map(P=>P.id),hidden:t.filter(P=>P.defaultVisible===!1).map(P=>P.id),sizes:l()}}),[d,h]=w.useState(!1),[f,p]=w.useState(!1);w.useEffect(()=>{if(!r)return;const j=window.matchMedia(`(max-width: ${r}px)`),P=U=>{p(U.matches)};P(j);const E=U=>P(U);return j.addEventListener?j.addEventListener("change",E):j.addListener(E),()=>{j.removeEventListener?j.removeEventListener("change",E):j.removeListener(E)}},[r]);const x=r&&f?1:n;w.useEffect(()=>{const j=()=>h(P=>!P);return window.addEventListener("toggle-hidden-panel",j),()=>window.removeEventListener("toggle-hidden-panel",j)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const P=t.map(E=>E.id).filter(E=>!c.order.includes(E));P.length>0&&u(E=>({...E,order:[...E.order,...P]}))},[t,c.order]);const v=yie(FC(kA,{activationConstraint:{distance:8}}),FC(CA,{coordinateGetter:Hie})),g=j=>{const{active:P,over:E}=j;E&&P.id!==E.id&&u(U=>{const L=U.order.indexOf(P.id),B=U.order.indexOf(E.id);return{...U,order:MA(U.order,L,B)}})},y=j=>{u(P=>({...P,hidden:P.hidden.includes(j)?P.hidden.filter(E=>E!==j):[...P.hidden,j]}))},_=j=>{u(P=>{const E=P.sizes[j]||4,U=E===1?2:E===2?4:1;return{...P,sizes:{...P.sizes,[j]:U}}})},N=()=>{const j={order:t.map(P=>P.id),hidden:t.filter(P=>P.defaultVisible===!1).map(P=>P.id),sizes:l()};u(j),s?.()},k=c.order.map(j=>t.find(P=>P.id===j)).filter(Boolean),A=k.filter(j=>!c.hidden.includes(j.id)),M=k.filter(j=>c.hidden.includes(j.id)),C=o?.({hiddenCount:M.length,showHiddenPanel:d,setShowHiddenPanel:h,resetLayout:N});return i.jsxs("div",{className:"space-y-4",children:[C,!a&&!o&&i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:N,children:[i.jsx(so,{className:"w-4 h-4"}),"Reset Layout"]}),M.length>0&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>h(!d),children:[i.jsx(Ql,{className:"w-4 h-4"}),M.length," Hidden"]})]}),d&&M.length>0&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(j=>i.jsxs("button",{onClick:()=>y(j.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[i.jsx(Ql,{className:"w-3 h-3"}),j.title]},j.id))})]}),i.jsx(Lie,{sensors:v,collisionDetection:_ie,onDragEnd:g,children:i.jsx(zie,{items:A.map(j=>j.id),strategy:uI,children:i.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${x}, minmax(0, 1fr))`},children:A.map(j=>{const P=c.sizes[j.id]||2,E=Math.min(P,x);return i.jsx(eZe,{id:j.id,title:j.title,component:j.component,isHidden:c.hidden.includes(j.id),size:P,columnSpan:E,onToggleVisibility:()=>y(j.id),onToggleSize:()=>_(j.id)},j.id)})})})}),A.length===0&&i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx("p",{children:"All widgets are hidden."}),i.jsx(Ce,{className:"mt-4",onClick:N,children:"Reset Layout"})]})]})}function nZe({stats:t,currency:e,t:n}){return i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(ni,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),i.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:i.jsx(Wn,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:i.jsx(ni,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:i.jsx(n3,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:i.jsx(nd,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(3)||"0.000"," kWh"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:i.jsx(n3,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function rZe({stats:t,printerMap:e,size:n=1,t:r}){const a=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return i.jsxs("div",{className:"flex items-center gap-6",children:[i.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[i.jsxs("svg",{className:"w-full h-full -rotate-90",children:[i.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),i.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${a/100*l} ${l}`})]}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[a,"%"]})})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),i.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),i.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),i.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,u])=>i.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[i.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),i.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function aZe({stats:t,printerMap:e,size:n=1,t:r}){const a=t?.average_time_accuracy;if(a==null)return i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,a))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(a),u=a-100,d=n===1?112:n===2?128:144,h=d/2-8,f=h*2*Math.PI,p=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,p):[];return i.jsxs("div",{className:"flex items-center gap-6",children:[i.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[i.jsxs("svg",{className:"w-full h-full -rotate-90",children:[i.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),i.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*f} ${f}`})]}),i.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[i.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[a.toFixed(0),"%"]}),i.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[i.jsx(_X,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&i.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:x.map(([v,g])=>i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),i.jsxs("span",{className:`font-medium ${g>=95&&g<=105?"text-status-ok":g>105?"text-blue-400":"text-status-warning"}`,children:[g.toFixed(0),"%"]})]},v))})]})]})}function iZe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),a=e===1?5:e===2?8:999,s=r.slice(0,a),o=r.length>a;return e===4&&s.length>4?i.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),i.jsx("span",{className:"text-bambu-gray",children:c})]}),i.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:i.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):i.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-white",children:l}),i.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:i.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&i.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-a})})]})}function sZe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return i.jsx(QQe,{printDates:t,months:n})}function oZe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,a])=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:i.jsx(gr,{className:"w-4 h-4 text-bambu-green"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[a," ",n("common.prints")]})]})]},r))})}function lZe({archives:t,currency:e,t:n}){return!t||t.length===0?i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):i.jsx(JQe,{archives:t,currency:e})}function cZe({size:t=1,t:e}){const{data:n,isLoading:r}=Je({queryKey:["failureAnalysis"],queryFn:()=>ne.getFailureAnalysis({days:30})});if(r)return i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return i.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const a=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,a),l=s.length>a;return i.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[i.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[i.jsx("div",{className:"flex items-center gap-4",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Tn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),i.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),i.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&i.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(MF,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate<n.trend[n.trend.length-2].failure_rate?"text-status-ok":"text-status-error"}`}),i.jsx("span",{className:"text-bambu-gray",children:e("stats.lastWeekRate",{rate:n.trend[n.trend.length-1].failure_rate.toFixed(1)})})]})})]}),o.length>0&&i.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[i.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),i.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),i.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-a})})]})]})}function uZe(){const{t}=Ot(),{showToast:e}=an(),{hasPermission:n}=Ir(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(0),[u,d]=w.useState(0),[h,f]=w.useState(!1);w.useEffect(()=>{const P=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const L=JSON.parse(U);d(L.hidden?.length||0)}}catch{d(0)}};P(),window.addEventListener("storage",P);const E=setInterval(P,500);return()=>{window.removeEventListener("storage",P),clearInterval(E)}},[l]);const{data:p,isLoading:x,refetch:v}=Je({queryKey:["archiveStats"],queryFn:ne.getArchiveStats}),{data:g}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:y}=Je({queryKey:["archives"],queryFn:()=>ne.getArchives(void 0,void 0,1e3,0)}),{data:_}=Je({queryKey:["settings"],queryFn:ne.getSettings}),N=async P=>{o(!1),a(!0);try{const{blob:E,filename:U}=await ne.exportStats({format:P,days:90}),L=URL.createObjectURL(E),B=document.createElement("a");B.href=L,B.download=U,B.click(),URL.revokeObjectURL(L),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{a(!1)}},k=async()=>{f(!0);try{const P=await ne.recalculateCosts();await v(),e(t("stats.recalculatedCosts",{count:P.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},A=rl(_?.currency||"USD"),M=new Map(g?.map(P=>[String(P.id),P.name])||[]),C=y?.map(P=>P.created_at)||[];if(x)return i.jsx("div",{className:"p-4 md:p-8",children:i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const j=[{id:"quick-stats",title:t("stats.quickStats"),component:i.jsx(nZe,{stats:p,currency:A,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:P=>i.jsx(rZe,{stats:p,printerMap:M,size:P,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:P=>i.jsx(aZe,{stats:p,printerMap:M,size:P,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:P=>i.jsx(iZe,{stats:p,size:P,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:P=>i.jsx(cZe,{size:P,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:P=>i.jsx(sZe,{printDates:C,size:P}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:i.jsx(oZe,{stats:p,printerMap:M,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:i.jsx(lZe,{archives:y||[],currency:A,t}),defaultSize:4}];return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&i.jsxs(Ce,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[i.jsx(Ql,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(P=>P+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[i.jsx(so,{className:"w-4 h-4"}),t("stats.resetLayout")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(the,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),i.jsxs("div",{className:"relative",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(S1,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&i.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[i.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>N("csv"),children:[i.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),i.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>N("xlsx"),children:[i.jsx(S1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),i.jsx(tZe,{widgets:j,storageKey:"bambusy-dashboard-layout",stackBelow:640,hideControls:!0},l)]})}function dZe({plug:t,onEdit:e}){const{t:n}=Ot(),r=en(),{showToast:a}=an(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[u,d]=w.useState(!1),[h,f]=w.useState(!1),{data:p,isLoading:x}=Je({queryKey:["smart-plug-status",t.id],queryFn:()=>ne.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),g=v?.find(E=>E.id===t.printer_id),y=st({mutationFn:E=>ne.controlSmartPlug(t.id,E),onMutate:async E=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const U=r.getQueryData(["smart-plug-status",t.id]),L=E==="on"?"ON":E==="off"||p?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],B=>({...B,state:L})),{previousStatus:U}},onError:(E,U,L)=>{L?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],L.previousStatus),a(`Failed to turn ${U} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=st({mutationFn:E=>ne.updateSmartPlug(t.id,E),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=st({mutationFn:()=>ne.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),k=p?.state==="ON",A=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,M=(p?.reachable??!1)||A,C=y.isPending,P=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const E=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${E}/`:`http://${E}/`})();return i.jsxs(i.Fragment,{children:[i.jsx(wt,{className:"relative",children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?M?"bg-teal-500/20":"bg-red-500/20":M?k?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?i.jsx(AF,{className:`w-5 h-5 ${M?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?i.jsx(d0,{className:`w-5 h-5 ${M?k?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):i.jsx(fl,{className:`w-5 h-5 ${M?k?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),i.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[x?i.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?i.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[i.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),M&&i.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?i.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[i.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),i.jsx("span",{className:M?k?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?p?.state||"?":"Offline"})]}):M?i.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[i.jsx(Wg,{className:"w-4 h-4 text-status-ok"}),i.jsx("span",{className:k?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):i.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[i.jsx(jf,{className:"w-4 h-4"}),i.jsx("span",{children:n("smartPlugs.offline")})]}),P&&i.jsxs("a",{href:P,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[i.jsx(Xr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),g&&i.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),i.jsx("span",{className:"text-sm text-white",children:g.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[i.jsx(Ql,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[i.jsx(qg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[i.jsx(ra,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&i.jsxs("div",{className:"flex gap-2 mb-3",children:[i.jsxs(Ce,{size:"sm",variant:k?"primary":"secondary",disabled:!M||C,onClick:()=>c(!0),className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(md,{className:"w-4 h-4"}),"On"]}),i.jsxs(Ce,{size:"sm",variant:k?"secondary":"primary",disabled:!M||C,onClick:()=>d(!0),className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(QC,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&i.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[p.energy.power!==null&&p.energy.power!==void 0&&i.jsxs("div",{className:"flex-1 text-center",children:[i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&i.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(3)}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),i.jsxs("button",{onClick:()=>f(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),i.jsx("span",{children:h?"-":"+"})]}),h&&i.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(h0,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:E=>_.mutate({show_in_switchbar:E.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Enabled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.enabled,onChange:E=>_.mutate({enabled:E.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Auto On"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:E=>_.mutate({auto_on:E.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:E=>_.mutate({auto_off:E.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&i.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[i.jsx(Wn,{className:"w-4 h-4"}),"Time"]}),i.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[i.jsx(JC,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),i.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:E=>_.mutate({off_delay_minutes:parseInt(E.target.value)||5}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}):i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),i.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:E=>_.mutate({off_temp_threshold:parseInt(E.target.value)||70}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),i.jsxs("div",{className:"flex gap-2 pt-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[i.jsx(ef,{className:"w-4 h-4"}),"Edit"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})}),s&&i.jsx(gn,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&i.jsx(gn,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{y.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&i.jsx(gn,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{y.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function hZe({plug:t,onClose:e}){const{t:n}=Ot(),r=en(),a=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[u,d]=w.useState(t?.ip_address||""),[h,f]=w.useState(t?.username||""),[p,x]=w.useState(t?.password||""),[v,g]=w.useState(t?.ha_entity_id||""),[y,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,k]=w.useState(t?.mqtt_power_path||""),[A,M]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,j]=w.useState(t?.mqtt_energy_topic||""),[P,E]=w.useState(t?.mqtt_energy_path||""),[U,L]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[B,D]=w.useState(t?.mqtt_state_topic||""),[$,G]=w.useState(t?.mqtt_state_path||""),[z,W]=w.useState(t?.mqtt_state_on_value||""),[X,ae]=w.useState(t?.ha_power_entity||""),[H,K]=w.useState(t?.ha_energy_today_entity||""),[te,Z]=w.useState(t?.ha_energy_total_entity||""),[ve,ce]=w.useState(""),[ee,je]=w.useState(""),[he,oe]=w.useState(!1),_e=w.useRef(null),[ie,ze]=w.useState(""),[V,Y]=w.useState(!1),me=w.useRef(null),[Q,se]=w.useState(""),[de,Le]=w.useState(!1),Ne=w.useRef(null),[be,O]=w.useState(""),[R,q]=w.useState(!1),J=w.useRef(null),[fe,le]=w.useState(t?.printer_id||null),[Be,Ie]=w.useState(null),[Ke,Oe]=w.useState(null),[pe,xe]=w.useState(t?.power_alert_enabled||!1),[ke,ge]=w.useState(t?.power_alert_high?.toString()||""),[we,qe]=w.useState(t?.power_alert_low?.toString()||""),[Ee,tt]=w.useState(t?.schedule_enabled||!1),[De,We]=w.useState(t?.schedule_on_time||""),[Ae,Re]=w.useState(t?.schedule_off_time||""),[$e,ht]=w.useState(t?.show_in_switchbar||!1),[At,Dt]=w.useState(t?.show_on_printer_card??!0),[It,kt]=w.useState(!1),[Ue,bt]=w.useState({scanned:0,total:0}),[yt,Gt]=w.useState([]),Cn=w.useRef(null),{data:vr}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:Qn}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:tr}=Je({queryKey:["settings"],queryFn:ne.getSettings}),En=!!(tr?.ha_enabled&&tr?.ha_url&&tr?.ha_token);w.useEffect(()=>{const Te=setTimeout(()=>{je(ve)},300);return()=>clearTimeout(Te)},[ve]),w.useEffect(()=>{const Te=lt=>{_e.current&&!_e.current.contains(lt.target)&&oe(!1),me.current&&!me.current.contains(lt.target)&&Y(!1),Ne.current&&!Ne.current.contains(lt.target)&&Le(!1),J.current&&!J.current.contains(lt.target)&&q(!1)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[]);const{data:dr,isLoading:Tr,error:si}=Je({queryKey:["ha-entities",ee],queryFn:()=>ne.getHAEntities(ee||void 0),enabled:s==="homeassistant"&&En,retry:!1,staleTime:0}),{data:Fe}=Je({queryKey:["ha-sensor-entities"],queryFn:ne.getHASensorEntities,enabled:s==="homeassistant"&&En,retry:!1,staleTime:0});w.useEffect(()=>{const Te=lt=>{lt.key==="Escape"&&e()};return window.addEventListener("keydown",Te),()=>{window.removeEventListener("keydown",Te),Cn.current&&clearInterval(Cn.current)}},[e]);const Se=async()=>{kt(!0),Gt([]),bt({scanned:0,total:0}),Oe(null);try{await ne.startTasmotaScan();const Te=async()=>{try{const lt=await ne.getTasmotaScanStatus();bt({scanned:lt.scanned,total:lt.total});const pt=await ne.getDiscoveredTasmotaDevices();Gt(pt),lt.running||(kt(!1),Cn.current&&(clearInterval(Cn.current),Cn.current=null))}catch(lt){console.error("Polling error:",lt)}};await Te(),Cn.current=setInterval(Te,500)}catch(Te){kt(!1);const lt=Te instanceof Error?Te.message:typeof Te=="string"?Te:JSON.stringify(Te);Oe(lt||"Failed to start scan")}},nt=async()=>{try{await ne.stopTasmotaScan()}catch{}kt(!1),Cn.current&&(clearInterval(Cn.current),Cn.current=null)},ot=Te=>{d(Te.ip_address),c(Te.name),Ie(null)},Ge=st({mutationFn:()=>ne.testSmartPlugConnection(u,h||null,p||null),onSuccess:Te=>{Ie(Te),Oe(null),!l&&Te.device_name&&c(Te.device_name)},onError:Te=>{Ie(null),Oe(Te.message)}}),zt=st({mutationFn:Te=>ne.createSmartPlug(Te),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Te=>{Oe(Te.message)}}),ye=st({mutationFn:Te=>ne.updateSmartPlug(t.id,Te),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Te=>{Oe(Te.message)}}),He=vr?.filter(Te=>s==="tasmota"?!Qn?.some(pt=>pt.printer_id===Te.id&&pt.id!==t?.id&&pt.plug_type==="tasmota"):!0),Ye=Te=>{if(Te.preventDefault(),Oe(null),!l.trim()){Oe("Name is required");return}if(s==="tasmota"&&!u.trim()){Oe("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Oe("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const pt=y.trim(),at=C.trim(),Tt=B.trim();if(!pt&&!at&&!Tt){Oe("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const lt={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&X||null,ha_energy_today_entity:s==="homeassistant"&&H||null,ha_energy_total_entity:s==="homeassistant"&&te||null,mqtt_power_topic:s==="mqtt"&&y.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(A)||1,mqtt_energy_topic:s==="mqtt"&&C.trim()||null,mqtt_energy_path:s==="mqtt"&&P.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(U)||1,mqtt_state_topic:s==="mqtt"&&B.trim()||null,mqtt_state_path:s==="mqtt"&&$.trim()||null,mqtt_state_on_value:s==="mqtt"&&z.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&p.trim()||null,printer_id:fe,power_alert_enabled:pe,power_alert_high:ke?parseFloat(ke):null,power_alert_low:we?parseFloat(we):null,schedule_enabled:Ee,schedule_on_time:De||null,schedule_off_time:Ae||null,show_in_switchbar:$e,show_on_printer_card:At};a?ye.mutate(lt):zt.mutate(lt)},Xe=zt.isPending||ye.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:Te=>Te.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:a?"Edit Smart Plug":"Add Smart Plug"}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Ye,className:"p-6 space-y-4 overflow-y-auto",children:[Ke&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Ke}),!a&&i.jsxs("div",{className:"flex gap-2 mb-2",children:[i.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Ie(null),Oe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[i.jsx(fl,{className:"w-4 h-4"}),"Tasmota"]}),i.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Ie(null),Oe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[i.jsx(d0,{className:"w-4 h-4"}),"HA"]}),i.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Ie(null),Oe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[i.jsx(AF,{className:"w-4 h-4"}),"MQTT"]})]}),!a&&s==="tasmota"&&i.jsxs("div",{className:"space-y-3",children:[It?i.jsxs(Ce,{type:"button",variant:"secondary",onClick:nt,className:"w-full",children:[i.jsx(Lt,{className:"w-4 h-4"}),"Stop Scanning"]}):i.jsxs(Ce,{type:"button",variant:"primary",onClick:Se,className:"w-full",children:[i.jsx(xr,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),It&&Ue.total>0&&i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),i.jsxs("span",{children:[Ue.scanned," / ",Ue.total]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ue.scanned/Ue.total*100}%`}})})]}),yt.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",yt.length," device(s) - click to select:"]}),i.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:yt.map(Te=>i.jsxs("button",{type:"button",onClick:()=>ot(Te),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fl,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:Te.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:Te.ip_address})]})]}),Te.state&&i.jsxs("span",{className:`flex items-center gap-1 text-xs ${Te.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[i.jsx(md,{className:"w-3 h-3"}),Te.state]})]},Te.ip_address))})]}),!It&&yt.length===0&&Ue.total>0&&i.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&i.jsxs("div",{className:"space-y-3",children:[!En&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",i.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),i.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:i.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),En&&i.jsxs(i.Fragment,{children:[Tr&&i.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),si&&i.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",si.message]}),(()=>{const Te=Qn?.filter(at=>at.ha_entity_id&&at.id!==t?.id).map(at=>at.ha_entity_id)||[],lt=(dr||[]).filter(at=>!Te.includes(at.entity_id)),pt=dr?.find(at=>at.entity_id===v);return i.jsxs("div",{ref:_e,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:he?ve:pt?`${pt.friendly_name} (${pt.entity_id})`:"",onChange:at=>{ce(at.target.value),he||oe(!0)},onFocus:()=>{oe(!0),ce("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!he&&i.jsx("button",{type:"button",onClick:()=>{g(""),ce("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Tr&&i.jsx(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),he&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[Tr&&i.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Tr&&lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:ee?`No entities found matching "${ee}"`:"No entities available"}),!Tr&&lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{g(at.entity_id),oe(!1),ce(""),l||c(at.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${at.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[i.jsx("span",{children:at.entity_id}),i.jsx("span",{className:at.state==="on"?"text-bambu-green":"",children:at.state})]})]},at.entity_id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ee?`Searching all entities (${lt.length} found)`:`Showing switch, light, input_boolean (${lt.length} available)`})]})})(),v&&Fe&&Fe.length>0&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),i.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const Te=Fe.filter(at=>at.unit_of_measurement==="W"||at.unit_of_measurement==="kW"||at.unit_of_measurement==="mW"),lt=ie?Te.filter(at=>at.entity_id.toLowerCase().includes(ie.toLowerCase())||at.friendly_name.toLowerCase().includes(ie.toLowerCase())):Te,pt=Fe.find(at=>at.entity_id===X);return i.jsxs("div",{ref:me,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:V?ie:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{ze(at.target.value),V||Y(!0)},onFocus:()=>{Y(!0),ze("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),X&&!V&&i.jsx("button",{type:"button",onClick:()=>{ae(""),ze("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),V&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[i.jsx("button",{type:"button",onClick:()=>{ae(""),Y(!1),ze("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{ae(at.entity_id),Y(!1),ze("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===X?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Te=Fe.filter(at=>at.unit_of_measurement==="kWh"||at.unit_of_measurement==="Wh"||at.unit_of_measurement==="MWh"),lt=Q?Te.filter(at=>at.entity_id.toLowerCase().includes(Q.toLowerCase())||at.friendly_name.toLowerCase().includes(Q.toLowerCase())):Te,pt=Fe.find(at=>at.entity_id===H);return i.jsxs("div",{ref:Ne,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:de?Q:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{se(at.target.value),de||Le(!0)},onFocus:()=>{Le(!0),se("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),H&&!de&&i.jsx("button",{type:"button",onClick:()=>{K(""),se("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),de&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[i.jsx("button",{type:"button",onClick:()=>{K(""),Le(!1),se("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{K(at.entity_id),Le(!1),se("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===H?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Te=Fe.filter(at=>at.unit_of_measurement==="kWh"||at.unit_of_measurement==="Wh"||at.unit_of_measurement==="MWh"),lt=be?Te.filter(at=>at.entity_id.toLowerCase().includes(be.toLowerCase())||at.friendly_name.toLowerCase().includes(be.toLowerCase())):Te,pt=Fe.find(at=>at.entity_id===te);return i.jsxs("div",{ref:J,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:R?be:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{O(at.target.value),R||q(!0)},onFocus:()=>{q(!0),O("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),te&&!R&&i.jsx("button",{type:"button",onClick:()=>{Z(""),O("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Lt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),R&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[i.jsx("button",{type:"button",onClick:()=>{Z(""),q(!1),O("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{Z(at.entity_id),q(!1),O("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&i.jsxs("div",{className:"space-y-3",children:[!tr?.mqtt_broker&&i.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",i.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),tr?.mqtt_broker&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),i.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:y,onChange:Te=>_(Te.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:N,onChange:Te=>k(Te.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),i.jsx("input",{type:"text",value:A,onChange:Te=>M(Te.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',i.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",i.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:C,onChange:Te=>j(Te.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:P,onChange:Te=>E(Te.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),i.jsx("input",{type:"text",value:U,onChange:Te=>L(Te.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",i.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",i.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:B,onChange:Te=>D(Te.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:$,onChange:Te=>G(Te.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),i.jsx("input",{type:"text",value:z,onChange:Te=>W(Te.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",i.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:u,onChange:Te=>{d(Te.target.value),Ie(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsxs(Ce,{type:"button",variant:"secondary",onClick:()=>Ge.mutate(),disabled:!u.trim()||Ge.isPending,children:[Ge.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Wg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&Be&&i.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${Be.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:Be.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-5 h-5"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:"Connected!"}),i.jsxs("p",{className:"text-sm opacity-80",children:[Be.device_name&&`Device: ${Be.device_name} - `,"State: ",Be.state]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx(jf,{className:"w-5 h-5"}),i.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:l,onChange:Te=>c(Te.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),i.jsx("input",{type:"text",value:h,onChange:Te=>f(Te.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),i.jsx("input",{type:"password",value:p,onChange:Te=>x(Te.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),i.jsxs("select",{value:fe??"",onChange:Te=>le(Te.target.value?Number(Te.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:"No printer (manual control only)"}),He?.map(Te=>i.jsx("option",{value:Te.id,children:Te.name},Te.id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(qg,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:pe,onChange:Te=>xe(Te.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),pe&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),i.jsx("input",{type:"number",value:ke,onChange:Te=>ge(Te.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),i.jsx("input",{type:"number",value:we,onChange:Te=>qe(Te.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Wn,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Ee,onChange:Te=>tt(Te.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Ee&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),i.jsx("input",{type:"time",value:De,onChange:Te=>We(Te.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),i.jsx("input",{type:"time",value:Ae,onChange:Te=>Re(Te.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),i.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(h0,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:$e,onChange:Te=>ht(Te.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&i.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ql,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:At,onChange:Te=>Dt(Te.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:Xe,className:"flex-1",children:[Xe?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),a?"Save":"Add"]})]})]})]})})}function In({checked:t,onChange:e,disabled:n}){const r=a=>{a.preventDefault(),a.stopPropagation(),n||e(!t)};return i.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:i.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}const mZe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function fZe({provider:t,onEdit:e}){const n=en(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),d=u?.find(v=>v.id===t.printer_id),h=st({mutationFn:v=>ne.updateNotificationProvider(t.id,v),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),f=st({mutationFn:()=>ne.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=st({mutationFn:()=>ne.testNotificationProvider(t.id),onSuccess:v=>{c(v),n.invalidateQueries({queryKey:["notification-providers"]})},onError:v=>{c({success:!1,message:v.message})}}),x=v=>v||"";return i.jsxs(i.Fragment,{children:[i.jsx(wt,{className:"relative",children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-start justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:i.jsx(qg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("h3",{className:"font-medium text-white",children:t.name}),i.jsx("p",{className:"text-sm text-bambu-gray",children:mZe[t.provider_type]||t.provider_type})]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&i.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",mb(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(hi(t.last_error_at)?.getTime()||0)>(hi(t.last_success)?.getTime()||0))&&i.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),i.jsx(In,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]})]}),d&&i.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),i.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&i.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),i.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&i.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&i.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&i.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&i.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&i.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&i.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&i.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&i.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&i.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&i.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&i.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&i.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&i.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&i.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.on_bed_cooled&&i.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:"Bed Cooled"}),t.quiet_hours_enabled&&i.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[i.jsx(N1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&i.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[i.jsx(ra,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),i.jsx("div",{className:"mb-3",children:i.jsxs(Ce,{size:"sm",variant:"secondary",disabled:p.isPending,onClick:()=>{c(null),p.mutate()},className:"w-full",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ZC,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&i.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?i.jsx(pr,{className:"w-4 h-4"}):i.jsx(mi,{className:"w-4 h-4"}),i.jsx("span",{children:l.message})]}),i.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-4 h-4"}),"Event Settings"]}),s?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Pn,{className:"w-4 h-4"})]}),s&&i.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Enabled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),i.jsx(In,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Started"}),i.jsx(In,{checked:t.on_print_start,onChange:v=>h.mutate({on_print_start:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),i.jsx(In,{checked:t.on_plate_not_empty??!0,onChange:v=>h.mutate({on_plate_not_empty:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),i.jsx(In,{checked:t.on_print_complete,onChange:v=>h.mutate({on_print_complete:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Bed Cooled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Bed cooled below threshold after print"})]}),i.jsx(In,{checked:t.on_bed_cooled??!1,onChange:v=>h.mutate({on_bed_cooled:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),i.jsx(In,{checked:t.on_print_failed,onChange:v=>h.mutate({on_print_failed:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),i.jsx(In,{checked:t.on_print_stopped,onChange:v=>h.mutate({on_print_stopped:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),i.jsx(In,{checked:t.on_print_progress,onChange:v=>h.mutate({on_print_progress:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),i.jsx(In,{checked:t.on_printer_offline,onChange:v=>h.mutate({on_printer_offline:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),i.jsx(In,{checked:t.on_printer_error,onChange:v=>h.mutate({on_printer_error:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),i.jsx(In,{checked:t.on_filament_low,onChange:v=>h.mutate({on_filament_low:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),i.jsx(In,{checked:t.on_maintenance_due??!1,onChange:v=>h.mutate({on_maintenance_due:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),i.jsx(In,{checked:t.on_ams_humidity_high??!1,onChange:v=>h.mutate({on_ams_humidity_high:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),i.jsx(In,{checked:t.on_ams_temperature_high??!1,onChange:v=>h.mutate({on_ams_temperature_high:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),i.jsx(In,{checked:t.on_ams_ht_humidity_high??!1,onChange:v=>h.mutate({on_ams_ht_humidity_high:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),i.jsx(In,{checked:t.on_ams_ht_temperature_high??!1,onChange:v=>h.mutate({on_ams_ht_temperature_high:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Added"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),i.jsx(In,{checked:t.on_queue_job_added??!1,onChange:v=>h.mutate({on_queue_job_added:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),i.jsx(In,{checked:t.on_queue_job_assigned??!1,onChange:v=>h.mutate({on_queue_job_assigned:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Started"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),i.jsx(In,{checked:t.on_queue_job_started??!1,onChange:v=>h.mutate({on_queue_job_started:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),i.jsx(In,{checked:t.on_queue_job_waiting??!0,onChange:v=>h.mutate({on_queue_job_waiting:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),i.jsx(In,{checked:t.on_queue_job_skipped??!0,onChange:v=>h.mutate({on_queue_job_skipped:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),i.jsx(In,{checked:t.on_queue_job_failed??!0,onChange:v=>h.mutate({on_queue_job_failed:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),i.jsx(In,{checked:t.on_queue_completed??!1,onChange:v=>h.mutate({on_queue_completed:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(N1,{className:"w-4 h-4 text-purple-400"}),i.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),i.jsx(In,{checked:t.quiet_hours_enabled,onChange:v=>h.mutate({quiet_hours_enabled:v})})]}),t.quiet_hours_enabled&&i.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Wn,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ra,{className:"w-4 h-4 text-emerald-400"}),i.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),i.jsx(In,{checked:t.daily_digest_enabled,onChange:v=>h.mutate({daily_digest_enabled:v})})]}),t.daily_digest_enabled&&i.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Wn,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),i.jsxs("div",{className:"flex gap-2 pt-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[i.jsx(ef,{className:"w-4 h-4"}),"Edit"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})}),r&&i.jsx(gn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{f.mutate(),a(!1)},onCancel:()=>a(!1)})]})}const JW=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function pZe({provider:t,onClose:e}){const n=en(),r=!!t,[a,s]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,h]=w.useState(t?.quiet_hours_enabled||!1),[f,p]=w.useState(t?.quiet_hours_start||"22:00"),[x,v]=w.useState(t?.quiet_hours_end||"07:00"),[g,y]=w.useState(t?.daily_digest_enabled||!1),[_,N]=w.useState(t?.daily_digest_time||"08:00"),[k,A]=w.useState(t?.on_print_start??!1),[M,C]=w.useState(t?.on_print_complete??!0),[j,P]=w.useState(t?.on_print_failed??!0),[E,U]=w.useState(t?.on_print_stopped??!0),[L,B]=w.useState(t?.on_print_progress??!1),[D,$]=w.useState(t?.on_printer_offline??!1),[G,z]=w.useState(t?.on_printer_error??!1),[W,X]=w.useState(t?.on_filament_low??!1),[ae,H]=w.useState(t?.on_maintenance_due??!1),[K,te]=w.useState(t?.on_bed_cooled??!1),[Z,ve]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([de,Le])=>[de,String(Le)])):{}),[ce,ee]=w.useState(null),[je,he]=w.useState(null),{data:oe}=Je({queryKey:["printers"],queryFn:ne.getPrinters});w.useEffect(()=>{const de=Le=>{Le.key==="Escape"&&e()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[e]);const _e=st({mutationFn:()=>ne.testNotificationConfig({provider_type:o,config:Z}),onSuccess:de=>{ee(de),he(null)},onError:de=>{ee({success:!1,message:de.message})}}),ie=st({mutationFn:de=>ne.createNotificationProvider(de),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:de=>{he(de.message)}}),ze=st({mutationFn:de=>ne.updateNotificationProvider(t.id,de),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:de=>{he(de.message)}}),V=de=>{if(de.preventDefault(),he(null),!a.trim()){he("Name is required");return}const Le=Q(o);for(const be of Le)if(!Z[be.key]?.trim()){he(`${be.label} is required`);return}const Ne={name:a.trim(),provider_type:o,config:Z,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?f:null,quiet_hours_end:d?x:null,daily_digest_enabled:g,daily_digest_time:g?_:null,on_print_start:k,on_print_complete:M,on_print_failed:j,on_print_stopped:E,on_print_progress:L,on_printer_offline:D,on_printer_error:G,on_filament_low:W,on_maintenance_due:ae,on_bed_cooled:K};r?ze.mutate(Ne):ie.mutate(Ne)},Y=ie.isPending||ze.isPending,me=de=>{switch(de){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:Le=>Le.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:Le=>Le.payload_format!=="slack"}];default:return[]}},Q=de=>me(de).filter(Le=>Le.required),se=me(o);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:de=>de.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:V,className:"p-6 space-y-4",children:[je&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:je}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:a,onChange:de=>s(de.target.value),placeholder:"My Notifications",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),i.jsx("select",{value:o,onChange:de=>{l(de.target.value),ve({}),ee(null)},disabled:r,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none disabled:opacity-50",children:JW.map(de=>i.jsx("option",{value:de.value,children:de.label},de.value))}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:JW.find(de=>de.value===o)?.description})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),se.filter(de=>!("showIf"in de)||de.showIf?.(Z)!==!1).map(de=>i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[de.label," ",de.required&&"*"]}),de.type==="select"&&"options"in de&&de.options?i.jsx("select",{value:Z[de.key]||de.options[0]?.value||"",onChange:Le=>{ve({...Z,[de.key]:Le.target.value}),ee(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:de.options.map(Le=>i.jsx("option",{value:Le.value,children:Le.label},Le.value))}):i.jsx("input",{type:de.type,value:Z[de.key]||"",onChange:Le=>{ve({...Z,[de.key]:Le.target.value}),ee(null)},placeholder:de.placeholder,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]},de.key))]}),i.jsx("div",{className:"flex gap-2",children:i.jsxs(Ce,{type:"button",variant:"secondary",onClick:()=>{ee(null),_e.mutate()},disabled:_e.isPending||!Z[Q(o)[0]?.key],className:"flex-1",children:[_e.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ZC,{className:"w-4 h-4"}),"Test Configuration"]})}),ce&&i.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ce.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ce.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-5 h-5"}),i.jsx("span",{children:ce.message})]}):i.jsxs(i.Fragment,{children:[i.jsx(mi,{className:"w-5 h-5"}),i.jsx("span",{children:ce.message})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),i.jsxs("select",{value:c??"",onChange:de=>u(de.target.value?Number(de.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:"All printers"}),oe?.map(de=>i.jsx("option",{value:de.id,children:de.name},de.id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),i.jsx(In,{checked:d,onChange:h})]}),d&&i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),i.jsx("input",{type:"time",value:f,onChange:de=>p(de.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),i.jsx("input",{type:"time",value:x,onChange:de=>v(de.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),i.jsx(In,{checked:g,onChange:y})]}),g&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),i.jsx("input",{type:"time",value:_,onChange:de=>N(de.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),i.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Start"}),i.jsx(In,{checked:k,onChange:A})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Complete"}),i.jsx(In,{checked:M,onChange:C})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Failed"}),i.jsx(In,{checked:j,onChange:P})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Stopped"}),i.jsx(In,{checked:E,onChange:U})]}),i.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:"Progress"}),i.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),i.jsx(In,{checked:L,onChange:B})]}),i.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:"Bed Cooled"}),i.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(after print completes)"})]}),i.jsx(In,{checked:K,onChange:te})]})]})]}),i.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Offline"}),i.jsx(In,{checked:D,onChange:$})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Error"}),i.jsx(In,{checked:G,onChange:z})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),i.jsx(In,{checked:W,onChange:X})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),i.jsx(In,{checked:ae,onChange:H})]})]})]})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:Y,className:"flex-1",children:[Y?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function gZe({template:t,onClose:e}){const n=en(),r=w.useRef(null),[a,s]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,h]=w.useState(!0),{data:f}=Je({queryKey:["template-variables"],queryFn:ne.getTemplateVariables}),p=f?.find(A=>A.event_type===t.event_type),{data:x,isLoading:v}=Je({queryKey:["template-preview",t.event_type,a,o],queryFn:()=>ne.previewTemplate({event_type:t.event_type,title_template:a,body_template:o}),enabled:d&&a.length>0&&o.length>0});w.useEffect(()=>{const A=M=>{M.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e]);const g=st({mutationFn:A=>ne.updateNotificationTemplate(t.id,A),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:A=>{u(A.message)}}),y=st({mutationFn:()=>ne.resetNotificationTemplate(t.id),onSuccess:A=>{s(A.title_template),l(A.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:A=>{u(A.message)}}),_=A=>{if(A.preventDefault(),u(null),!a.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}g.mutate({title_template:a,body_template:o})},N=A=>{const M=r.current;if(!M)return;const C=M.selectionStart,j=M.selectionEnd,P=o,E=P.substring(0,C),U=P.substring(j),L=E+`{${A}}`+U;l(L),setTimeout(()=>{M.focus();const B=C+A.length+2;M.setSelectionRange(B,B)},0)},k=a!==t.title_template||o!==t.body_template;return i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("form",{onSubmit:_,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),i.jsx("input",{type:"text",value:a,onChange:A=>s(A.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:"Notification title..."})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),i.jsx("textarea",{ref:r,value:o,onChange:A=>l(A.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:"Notification body..."})]}),p&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:p.variables.map(A=>i.jsxs("button",{type:"button",onClick:()=>N(A),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[i.jsx(Gn,{className:"w-3 h-3"}),A]},A))}),i.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[i.jsx(Ql,{className:"w-4 h-4"}),"Live Preview"]}),i.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&i.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),i.jsx("div",{className:"text-white font-medium",children:x.title})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),i.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):i.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[i.jsxs(Ce,{type:"button",variant:"ghost",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-orange-400 hover:text-orange-300",children:[y.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(so,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),i.jsxs(Ce,{onClick:_,disabled:g.isPending||!k,children:[g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(ps,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const bZe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},xZe={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function yZe({onClose:t}){const e=en(),{showToast:n}=an(),[r,a]=w.useState(7),[s,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=Je({queryKey:["settings"],queryFn:ne.getSettings}),d=u?.time_format||"system",{data:h,isLoading:f,refetch:p,isRefetching:x}=Je({queryKey:["notification-logs",r,l],queryFn:()=>ne.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:v}=Je({queryKey:["notification-log-stats",r],queryFn:()=>ne.getNotificationLogStats(r)}),g=st({mutationFn:()=>ne.clearNotificationLogs(30),onSuccess:_=>{n(_.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:_=>{n(`Failed to clear logs: ${_.message}`,"error")}}),y=_=>{const N=hi(_);if(!N)return"";const A=new Date().getTime()-N.getTime();return A<6e4?"Just now":A<36e5?`${Math.floor(A/6e4)}m ago`:A<864e5?`${Math.floor(A/36e5)}h ago`:N.toLocaleDateString()+" "+Ege(N,d)};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(db,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),v&&i.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:i.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[i.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",i.jsx("span",{className:"text-white font-medium",children:v.total})," notifications"]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[i.jsx(pr,{className:"w-4 h-4"}),v.success_count," sent"]}),v.failure_count>0&&i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(mi,{className:"w-4 h-4"}),v.failure_count," failed"]})]})}),i.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[i.jsxs("select",{value:r,onChange:_=>a(Number(_.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[i.jsx("option",{value:1,children:"Last 24 hours"}),i.jsx("option",{value:7,children:"Last 7 days"}),i.jsx("option",{value:30,children:"Last 30 days"}),i.jsx("option",{value:90,children:"Last 90 days"})]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),i.jsx("div",{className:"flex-1"}),i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>p(),disabled:x,children:[x?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4"}),"Refresh"]}),i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),"Clear Old"]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?i.jsx("div",{className:"space-y-2",children:h.map(_=>i.jsx(vZe,{log:_,isExpanded:s===_.id,onToggle:()=>o(s===_.id?null:_.id),formatDate:y,formatFullDate:N=>Rf(N,d)},_.id))}):i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(db,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function vZe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:a}){return i.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[i.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?i.jsx(pr,{className:"w-4 h-4 text-bambu-green shrink-0"}):i.jsx(mi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-xs font-medium ${xZe[t.event_type]||"text-bambu-gray"}`,children:bZe[t.event_type]||t.event_type}),i.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&i.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),i.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?i.jsx(yl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):i.jsx(Pn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&i.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),i.jsx("p",{className:"text-sm text-white",children:t.title})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),i.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),i.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),i.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[i.jsxs("span",{children:["Provider: ",t.provider_type]}),i.jsxs("span",{children:["Time: ",a(t.created_at)]})]})]})]})}function wZe({formData:t,setFormData:e,groups:n,onClose:r,onCreate:a,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Ot();w.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:i.jsxs(wt,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),i.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:r,children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),i.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),i.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(u=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&i.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),i.jsx(Ce,{onClick:a,disabled:o,children:s?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):i.jsxs(i.Fragment,{children:[i.jsx(Gn,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function SZe(){const{t}=Ot(),e=en(),{showToast:n}=an(),[r,a]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[u,d]=w.useState(!1),[h,f]=w.useState(!0),[p,x]=w.useState("all"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),{data:A,isLoading:M}=Je({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings}),{data:C,isLoading:j,refetch:P}=Je({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,refetchInterval:3e4}),{data:E}=Je({queryKey:["printers"],queryFn:ne.getPrinters});w.useEffect(()=>{A&&(a(A.spoolman_enabled==="true"),o(A.spoolman_url||""),c(A.spoolman_sync_mode||"auto"),d(A.spoolman_disable_weight_sync==="true"),f(A.spoolman_report_partial_usage!=="false"),g(!0))},[A]),w.useEffect(()=>{if(!v||!A)return;if(A.spoolman_enabled==="true"!==r||(A.spoolman_url||"")!==s||(A.spoolman_sync_mode||"auto")!==l||A.spoolman_disable_weight_sync==="true"!==u||A.spoolman_report_partial_usage!=="false"!==h){const K=setTimeout(()=>{U.mutate()},500);return()=>clearTimeout(K)}},[r,s,l,u,h,v]);const U=st({mutationFn:()=>ne.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),n(t("settings.toast.settingsSaved"))}}),L=st({mutationFn:ne.connectSpoolman,onSuccess:()=>{P()}}),B=st({mutationFn:ne.disconnectSpoolman,onSuccess:()=>{P()}}),D=st({mutationFn:ne.syncAllPrintersAms,onSuccess:H=>{H.success}}),$=st({mutationFn:H=>ne.syncPrinterAms(H),onSuccess:H=>{H.success}}),G=()=>{p==="all"?D.mutate():$.mutate(p)},z=st({mutationFn:ne.syncWeightsFromAms,onSuccess:H=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:H.synced,skipped:H.skipped}),"success"),k(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),k(!1)}}),W=D.isPending||$.isPending,X=p==="all"?D.data:$.data,ae=p==="all"?D.isSuccess:$.isSuccess;return M?i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),i.jsx(_t,{children:i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),U.isPending&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>a(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx(ni,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),i.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),i.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&i.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),i.jsxs("button",{type:"button",onClick:()=>a(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx(Xr,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),i.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&i.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[i.jsx("li",{children:t("settings.builtInFeatureRfid")}),i.jsx("li",{children:t("settings.builtInFeatureUsage")}),i.jsx("li",{children:t("settings.builtInFeatureCatalog")}),i.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>k(!0),disabled:z.isPending,children:[z.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),i.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[i.jsx("li",{children:t("settings.syncInfoRfidOnly")}),i.jsx("li",{children:t("settings.syncInfoAutoCreate")}),i.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),i.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),i.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),i.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:H=>o(H.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),i.jsxs("select",{value:l,onChange:H=>c(H.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),i.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:u,onChange:H=>d(H.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),u&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:h,onChange:H=>f(H.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),j?i.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):C?.connected?i.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[i.jsx(aa,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):i.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[i.jsx(Lt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),i.jsx("div",{className:"flex gap-2",children:C?.connected?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>B.mutate(),disabled:B.isPending,children:[B.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(tfe,{className:"w-4 h-4"}),t("settings.disconnect")]}):i.jsxs(Ce,{size:"sm",onClick:()=>L.mutate(),disabled:L.isPending||!s,children:[L.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(jh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),L.isError&&i.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:L.error.message}),C?.connected&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsxs("select",{value:p,onChange:H=>x(H.target.value==="all"?"all":Number(H.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"all",children:t("settings.allPrinters")}),E?.map(H=>i.jsx("option",{value:H.id,children:H.name},H.id))]}),i.jsx(Pn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:G,disabled:W,children:[W?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),ae&&X&&i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsx("div",{className:`p-2 rounded text-sm ${X.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:X.success?`Synced ${X.synced_count} spool${X.synced_count!==1?"s":""} successfully`:`Synced ${X.synced_count} spool${X.synced_count!==1?"s":""} with ${X.errors.length} error${X.errors.length!==1?"s":""}`}),X.skipped_count>0&&i.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{className:"font-medium",children:[X.skipped_count," spool",X.skipped_count!==1?"s":""," skipped"]})]}),X.skipped_count>5&&i.jsx("button",{onClick:()=>_(!y),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:y?"Show less":"Show all"})]}),i.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(y?X.skipped:X.skipped.slice(0,5)).map((H,K)=>i.jsxs("li",{className:"flex items-center gap-2",children:[H.color&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${H.color}`}}),i.jsx("span",{children:H.location}),i.jsxs("span",{className:"text-amber-300/60",children:["- ",H.reason]})]},K)),!y&&X.skipped_count>5&&i.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",X.skipped_count-5," more"]})]})]}),X.errors.length>0&&i.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[i.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),i.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:X.errors.map((H,K)=>i.jsx("li",{children:H},K))})]})]})]})]})]}),N&&i.jsx(gn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:z.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>z.mutate(),onCancel:()=>k(!1)})]})}function _Ze(){const{t}=Ot(),{showToast:e}=an(),[n,r]=w.useState([]),[a,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState(!1),[N,k]=w.useState(null),[A,M]=w.useState(!1),C=w.useCallback(async()=>{try{const z=await ne.getSpoolCatalog();r(z)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{C()},[C]);const j=n.filter(z=>z.name.toLowerCase().includes(o.toLowerCase())),P=async()=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const z=await ne.addCatalogEntry({name:p.trim(),weight:parseInt(v)});r(W=>[...W,z].sort((X,ae)=>X.name.localeCompare(ae.name))),d(!1),x(""),g(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},E=z=>{f(z.id),x(z.name),g(z.weight.toString())},U=()=>{f(null),x(""),g("")},L=async z=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const W=await ne.updateCatalogEntry(z,{name:p.trim(),weight:parseInt(v)});r(X=>X.map(ae=>ae.id===z?W:ae).sort((ae,H)=>ae.name.localeCompare(H.name))),f(null),x(""),g(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},B=async()=>{if(N)try{await ne.deleteCatalogEntry(N.id),r(z=>z.filter(W=>W.id!==N.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{k(null)}},D=async()=>{M(!1),s(!0);try{await ne.resetSpoolCatalog(),await C(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},$=()=>{const z=n.map(({name:H,weight:K})=>({name:H,weight:K})),W=new Blob([JSON.stringify(z,null,2)],{type:"application/json"}),X=URL.createObjectURL(W),ae=document.createElement("a");ae.href=X,ae.download="spool-catalog.json",document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(X),e(t("settings.catalog.exported",{count:n.length}),"success")},G=async z=>{const W=z.target.files?.[0];if(W){try{const X=await W.text(),ae=JSON.parse(X);if(!Array.isArray(ae))throw new Error("Invalid format");let H=0,K=0;for(const te of ae){if(!te.name||typeof te.weight!="number"){K++;continue}if(n.some(ve=>ve.name.toLowerCase()===te.name.toLowerCase())){K++;continue}try{const ve=await ne.addCatalogEntry({name:te.name,weight:te.weight});r(ce=>[...ce,ve].sort((ee,je)=>ee.name.localeCompare(je.name))),H++}catch{K++}}e(t("settings.catalog.imported",{added:H,skipped:K}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return i.jsxs(wt,{children:[i.jsxs(zn,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Ec,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("button",{onClick:$,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[i.jsx(da,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),i.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[i.jsx(Ra,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),i.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:G}),i.jsxs("button",{onClick:()=>M(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[i.jsx(so,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),i.jsxs("button",{onClick:()=>d(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[i.jsx(Gn,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:z=>l(z.target.value)})]}),u&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:p,onChange:z=>x(z.target.value)})}),i.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:z=>g(z.target.value)}),i.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),i.jsxs("button",{onClick:P,disabled:y,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[y?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(aa,{className:"w-4 h-4"}),t("common.add")]}),i.jsx("button",{onClick:()=>{d(!1),x(""),g("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:i.jsx(Lt,{className:"w-4 h-4"})})]})]}),a?i.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):i.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),i.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),i.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),i.jsx("th",{className:"px-4 py-2 w-24"})]})}),i.jsx("tbody",{children:j.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):j.map(z=>i.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:h===z.id?i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-4 py-2",children:i.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:p,onChange:W=>x(W.target.value)})}),i.jsx("td",{className:"px-4 py-2",children:i.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:W=>g(W.target.value)})}),i.jsx("td",{className:"px-4 py-2 text-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),i.jsx("td",{className:"px-4 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>L(z.id),disabled:y,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:y?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(aa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:U,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(Lt,{className:"w-4 h-4"})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-4 py-2 text-white",children:z.name}),i.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[z.weight,"g"]}),i.jsx("td",{className:"px-4 py-2 text-center",children:z.is_default?i.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),i.jsx("td",{className:"px-4 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>E(z),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>k(z),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})},z.id))})]})})]}),N&&i.jsx(gn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:N.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:B,onCancel:()=>k(null)}),A&&i.jsx(gn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:D,onCancel:()=>M(!1)})]})}function NZe(){const{t}=Ot(),{showToast:e}=an(),[n,r]=w.useState([]),[a,s]=w.useState(!0),[o,l]=w.useState(""),[c,u]=w.useState("Bambu Lab"),d=w.useRef(null),[h,f]=w.useState(!1),[p,x]=w.useState(null),[v,g]=w.useState(""),[y,_]=w.useState(""),[N,k]=w.useState("#FFFFFF"),[A,M]=w.useState(""),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(null),[$,G]=w.useState(!1),z=w.useCallback(async()=>{try{const oe=await ne.getColorCatalog();r(oe)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{z()},[z]);const W=[...new Set(n.map(oe=>oe.manufacturer))].sort(),X=n.filter(oe=>{const _e=o===""||oe.manufacturer.toLowerCase().includes(o.toLowerCase())||oe.color_name.toLowerCase().includes(o.toLowerCase())||(oe.material?.toLowerCase().includes(o.toLowerCase())??!1),ie=c===""||oe.manufacturer===c;return _e&&ie}),ae=()=>{g(""),_(""),k("#FFFFFF"),M("")},H=async()=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const oe=await ne.addColorEntry({manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:A.trim()||null});r(_e=>[..._e,oe].sort((ie,ze)=>ie.manufacturer.localeCompare(ze.manufacturer)||(ie.material||"").localeCompare(ze.material||"")||ie.color_name.localeCompare(ze.color_name))),f(!1),ae(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{j(!1)}},K=oe=>{x(oe.id),g(oe.manufacturer),_(oe.color_name),k(oe.hex_color),M(oe.material||"")},te=()=>{x(null),ae()},Z=async oe=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const _e=await ne.updateColorEntry(oe,{manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:A.trim()||null});r(ie=>ie.map(ze=>ze.id===oe?_e:ze).sort((ze,V)=>ze.manufacturer.localeCompare(V.manufacturer)||(ze.material||"").localeCompare(V.material||"")||ze.color_name.localeCompare(V.color_name))),x(null),ae(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{j(!1)}},ve=async()=>{if(B)try{await ne.deleteColorEntry(B.id),r(oe=>oe.filter(_e=>_e.id!==B.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{D(null)}},ce=async()=>{G(!1),s(!0);try{await ne.resetColorCatalog(),await z(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},ee=async()=>{E(!0),L(null);try{const oe={},_e=rd();_e&&(oe.Authorization=`Bearer ${_e}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:oe});if(!ie.ok)throw new Error("Failed to start sync");const ze=ie.body?.getReader();if(!ze)throw new Error("No response body");const V=new TextDecoder;let Y="";for(;;){const{done:me,value:Q}=await ze.read();if(me)break;Y+=V.decode(Q,{stream:!0});const se=Y.split(`
  8299. `);Y=se.pop()||"";for(const de of se)if(de.startsWith("data: "))try{const Le=JSON.parse(de.slice(6));Le.type==="progress"?L({fetched:Le.total_fetched,total:Le.total_available}):Le.type==="complete"?Le.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Le.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Le.added,skipped:Le.skipped}),"success"):Le.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Le.error}`,"error")}catch{}}await z()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{E(!1),L(null)}},je=()=>{const oe=n.map(({manufacturer:V,color_name:Y,hex_color:me,material:Q})=>({manufacturer:V,color_name:Y,hex_color:me,material:Q})),_e=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),ie=URL.createObjectURL(_e),ze=document.createElement("a");ze.href=ie,ze.download="color-catalog.json",document.body.appendChild(ze),ze.click(),document.body.removeChild(ze),URL.revokeObjectURL(ie),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},he=async oe=>{const _e=oe.target.files?.[0];if(_e){try{const ie=await _e.text(),ze=JSON.parse(ie);if(!Array.isArray(ze))throw new Error("Invalid format");let V=0,Y=0;for(const me of ze){if(!me.manufacturer||!me.color_name||!me.hex_color){Y++;continue}if(n.some(se=>se.manufacturer.toLowerCase()===me.manufacturer.toLowerCase()&&se.color_name.toLowerCase()===me.color_name.toLowerCase()&&(se.material||"").toLowerCase()===(me.material||"").toLowerCase())){Y++;continue}try{const se=await ne.addColorEntry({manufacturer:me.manufacturer,color_name:me.color_name,hex_color:me.hex_color,material:me.material||null});r(de=>[...de,se].sort((Le,Ne)=>Le.manufacturer.localeCompare(Ne.manufacturer)||(Le.material||"").localeCompare(Ne.material||"")||Le.color_name.localeCompare(Ne.color_name))),V++}catch{Y++}}e(t("settings.colorCatalog.imported",{added:V,skipped:Y}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}d.current&&(d.current.value="")}};return i.jsxs(wt,{children:[i.jsxs(zn,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(XC,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("button",{onClick:je,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[i.jsx(da,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),i.jsxs("button",{onClick:()=>d.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[i.jsx(Ra,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),i.jsx("input",{ref:d,type:"file",accept:".json",className:"hidden",onChange:he}),i.jsxs("button",{onClick:ee,disabled:P,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.colorCatalog.syncTooltip"),children:[P?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx($b,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:P?U?`${Math.min(U.fetched,U.total)} / ${U.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),i.jsxs("button",{onClick:()=>G(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[i.jsx(so,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),i.jsxs("button",{onClick:()=>f(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[i.jsx(Gn,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),i.jsxs("div",{className:"flex gap-2 flex-wrap",children:[i.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.searchColors"),value:o,onChange:oe=>l(oe.target.value)})]}),i.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:oe=>u(oe.target.value),children:[i.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),W.map(oe=>i.jsx("option",{value:oe,children:oe},oe))]})]}),h&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),i.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[i.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.manufacturer"),value:v,onChange:oe=>g(oe.target.value)}),i.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.colorName"),value:y,onChange:oe=>_(oe.target.value)}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:oe=>k(oe.target.value)}),i.jsx("input",{type:"text",className:"w-32 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:"#FFFFFF",value:N,onChange:oe=>k(oe.target.value)})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"text",className:"flex-1 max-w-lg min-w-[200px] px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.materialOptional"),value:A,onChange:oe=>M(oe.target.value)}),i.jsxs("button",{onClick:H,disabled:C,className:"w-24 px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center justify-center gap-3",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(aa,{className:"w-4 h-4"}),t("common.add")]}),i.jsx("button",{onClick:()=>{f(!1),ae()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:i.jsx(Lt,{className:"w-4 h-4"})})]})]})]}),(o||c)&&i.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:X.length,total:n.length})}),a?i.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):i.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),i.jsx("th",{className:"px-3 py-2 w-16"})]})}),i.jsx("tbody",{children:X.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:6,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):X.map(oe=>i.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:p===oe.id?i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:v,onChange:_e=>g(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:A,onChange:_e=>M(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:y,onChange:_e=>_(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:N,onChange:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>Z(oe.id),disabled:C,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(aa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:te,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(Lt,{className:"w-4 h-4"})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:oe.hex_color},title:oe.hex_color})}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.manufacturer}),i.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:oe.material||"-"}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.color_name}),i.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:oe.hex_color}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>K(oe),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>D(oe),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})},oe.id))})]})})]}),B&&i.jsx(gn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${B.manufacturer} - ${B.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:ve,onCancel:()=>D(null)}),$&&i.jsx(gn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:ce,onCancel:()=>G(!1)})]})}function CZe({link:t,onClose:e}){const{t:n}=Ot(),r=en(),a=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,h]=w.useState(t?.icon||"link"),[f,p]=w.useState(t?.open_in_new_tab||!1),[x,v]=w.useState(!!t?.custom_icon),[g,y]=w.useState(t?.custom_icon?ne.getExternalLinkIconUrl(t.id):null),[_,N]=w.useState(null),[k,A]=w.useState(null);w.useEffect(()=>{const B=D=>{D.key==="Escape"&&e()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e]);const M=st({mutationFn:async B=>{const D=await ne.createExternalLink(B);return _?await ne.uploadExternalLinkIcon(D.id,_):D},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{A(B.message)}}),C=st({mutationFn:async B=>{let D=await ne.updateExternalLink(t.id,B);return _?D=await ne.uploadExternalLinkIcon(t.id,_):!x&&t?.custom_icon&&(D=await ne.deleteExternalLinkIcon(t.id)),D},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{A(B.message)}}),j=B=>{const D=B.target.files?.[0];if(D){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(D.type)){A("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(D.size>1024*1024){A("Image file must be less than 1MB");return}N(D),v(!0);const G=new FileReader;G.onload=z=>{y(z.target?.result)},G.readAsDataURL(D)}},P=()=>{N(null),y(null),v(!1),s.current&&(s.current.value="")},E=B=>{if(B.preventDefault(),A(null),!o.trim()){A("Name is required");return}if(!c.trim()){A("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){A("URL must start with http:// or https://");return}const D={name:o.trim(),url:c.trim(),icon:d,open_in_new_tab:f};a?C.mutate(D):M.mutate(D)},U=M.isPending||C.isPending,L=tk(d);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:B=>B.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:x&&g?i.jsx("img",{src:g,alt:"",className:"w-5 h-5 rounded"}):i.jsx(L,{className:"w-5 h-5"})}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a?"Edit Link":"Add External Link"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:E,className:"p-6 space-y-4",children:[k&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:k}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:o,onChange:B=>l(B.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),i.jsx("input",{type:"text",value:c,onChange:B=>u(B.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),i.jsx("button",{type:"button",onClick:()=>p(!f),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${f?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${f?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),i.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),i.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:j}),x&&g?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:g,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:P,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:i.jsx(Jt,{className:"w-4 h-4"})})]}):i.jsxs(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Upload"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!x&&i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),i.jsx(xge,{value:d,onChange:h})]})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:U,className:"flex-1",children:[U?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),a?"Save":"Add"]})]})]})]})})}function kZe(){const{t}=Ot(),e=en(),[n,r]=w.useState(!1),[a,s]=w.useState(null),[o,l]=w.useState(null),[c,u]=w.useState(null),{data:d,isLoading:h}=Je({queryKey:["external-links"],queryFn:ne.getExternalLinks}),f=st({mutationFn:N=>ne.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),p=st({mutationFn:N=>ne.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(N,k)=>{u(k),N.dataTransfer.effectAllowed="move"},v=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},g=(N,k)=>{if(N.preventDefault(),c===null||c===k||!d)return;const A=d.map(P=>P.id),M=A.indexOf(c),C=A.indexOf(k);if(M===-1||C===-1)return;const j=[...A];j.splice(M,1),j.splice(C,0,c),p.mutate(j),u(null)},y=N=>{l(N)},_=()=>{o&&(f.mutate(o.id),l(null))};return i.jsxs(i.Fragment,{children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),i.jsxs(Ce,{size:"sm",onClick:()=>r(!0),children:[i.jsx(Gn,{className:"w-4 h-4"}),"Add Link"]})]})}),i.jsxs(_t,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?i.jsx("div",{className:"space-y-2",children:d.map(N=>{const k=tk(N.icon);return i.jsxs("div",{draggable:!0,onDragStart:A=>x(A,N.id),onDragOver:v,onDrop:A=>g(A,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[i.jsx(Eh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(k,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white font-medium truncate",children:N.name}),i.jsx(Xr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),i.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[i.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>y(N),disabled:f.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},N.id)})}):i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(jh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:t("externalLinks.noLinksConfigured")}),i.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||a)&&i.jsx(CZe,{link:a,onClose:()=>{r(!1),s(null)}}),o&&i.jsx(gn,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:_,onCancel:()=>l(null)})]})}const A2={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function AZe({printer:t,models:e}){const{t:n}=Ot(),r=en(),{showToast:a}=an(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[u,d]=w.useState(t.name),[h,f]=w.useState(""),[p,x]=w.useState(t.mode==="queue"?"review":t.mode),[v,g]=w.useState(t.target_printer_id),[y,_]=w.useState(t.bind_ip||""),[N,k]=w.useState(t.remote_interface_ip||""),[A,M]=w.useState(t.model||""),[C,j]=w.useState(!1),[P,E]=w.useState(null),[U,L]=w.useState(!1);w.useEffect(()=>{P||(c(t.enabled),x(t.mode==="queue"?"review":t.mode),d(t.name),g(t.target_printer_id),_(t.bind_ip||""),k(t.remote_interface_ip||""),M(t.model||""))},[t,P]);const{data:B}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:D}=Je({queryKey:["network-interfaces"],queryFn:()=>ne.getNetworkInterfaces().then(ee=>ee.interfaces)}),$=st({mutationFn:ee=>k1.update(t.id,ee),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.updated")),E(null)},onError:ee=>{a(ee.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),x(t.mode==="queue"?"review":t.mode),g(t.target_printer_id),_(t.bind_ip||""),E(null)}}),G=st({mutationFn:()=>k1.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.deleted")),L(!1)},onError:ee=>{a(ee.message||n("virtualPrinter.toast.failedToDelete"),"error"),L(!1)}}),z=ee=>{ee.stopPropagation();const je=!l;if(je){if(!y){a(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(p==="proxy"){if(!v){a(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!h&&!t.access_code_set){a(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(je),E("toggle"),$.mutate({enabled:je})},W=()=>{u.trim()&&(E("name"),$.mutate({name:u.trim()}))},X=()=>{if(!h){a(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(h.length!==8){a(n("virtualPrinter.toast.accessCodeLength"),"error");return}E("accessCode"),$.mutate({access_code:h}),f("")},ae=ee=>{x(ee),E("mode"),$.mutate({mode:ee})},H=ee=>{M(ee),E("model"),$.mutate({model:ee})},K=ee=>{g(ee),E("targetPrinter"),$.mutate({target_printer_id:ee})},te=ee=>{k(ee),E("remoteInterface"),$.mutate({remote_interface_ip:ee})},Z=t.status?.running||!1,ve=n(`virtualPrinter.mode.${A2[p]||"archive"}`),ce=B?.find(ee=>ee.id===v)?.name;return i.jsxs(i.Fragment,{children:[i.jsxs(wt,{children:[i.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[i.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?i.jsx(Pn,{className:"w-4 h-4"}):i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${Z?"bg-green-400 animate-pulse":"bg-gray-500"}`}),i.jsx("span",{className:"text-white font-medium truncate",children:t.name}),i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:ve}),t.model_name&&i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),ce&&i.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[p==="proxy"&&i.jsx(e3,{className:"w-3 h-3 inline mr-1"}),ce]}),y&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:y}),N&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:N}),i.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:ee=>ee.stopPropagation(),children:i.jsx("button",{onClick:z,disabled:P==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${P==="toggle"?"opacity-50":""}`,children:i.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${l?"translate-x-5":""}`})})})]}),s&&i.jsxs(_t,{className:"pt-0 space-y-4",children:[i.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"text",value:u,onChange:ee=>d(ee.target.value),onBlur:W,onKeyDown:ee=>ee.key==="Enter"&&W(),className:"flex-1 text-sm text-white bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),i.jsx("button",{onClick:()=>L(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(ee=>i.jsxs("button",{onClick:()=>ae(ee),disabled:P==="mode",className:`p-2 rounded-lg border text-left transition-colors ${p===ee?ee==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[ee==="proxy"&&i.jsx(e3,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${A2[ee]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${A2[ee]}Desc`)})]},ee))})]}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:A,onChange:ee=>H(ee.target.value),disabled:P==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:Object.entries(e).map(([ee,je])=>i.jsxs("option",{value:ee,children:[je," (",ee,")"]},ee))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),p==="proxy"&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?i.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[i.jsx(aa,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):i.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[i.jsx(Tn,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:C?"text":"password",value:h,onChange:ee=>f(ee.target.value),placeholder:t.access_code_set?n("virtualPrinter.accessCode.placeholderChange"):n("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm placeholder-bambu-gray pr-10 font-mono"}),i.jsx("button",{onClick:()=>j(!C),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:C?i.jsx(u0,{className:"w-4 h-4"}):i.jsx(Ql,{className:"w-4 h-4"})})]}),i.jsx(Ce,{onClick:X,disabled:!h||P==="accessCode",variant:"primary",children:P==="accessCode"?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),h&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i.jsx("span",{className:h.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:h.length})})})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:v??"",onChange:ee=>{const je=parseInt(ee.target.value,10);isNaN(je)||K(je)},disabled:P==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[i.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),B?.map(ee=>i.jsxs("option",{value:ee.id,children:[ee.name," (",ee.ip_address,")"]},ee.id))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:y,onChange:ee=>{_(ee.target.value),E("bindIp"),$.mutate({bind_ip:ee.target.value})},disabled:P==="bindIp",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[i.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),D?.map(ee=>i.jsxs("option",{value:ee.ip,children:[ee.name," (",ee.ip,")",ee.is_alias?" [alias]":""," - ",ee.subnet]},ee.ip))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),N?i.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:i.jsx(aa,{className:"w-3 h-3"})}):i.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:i.jsx(Zs,{className:"w-3 h-3"})})]}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:N,onChange:ee=>te(ee.target.value),disabled:P==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[i.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),D?.map(ee=>i.jsxs("option",{value:ee.ip,children:[ee.name," (",ee.ip,") - ",ee.subnet]},ee.ip))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),U&&i.jsx(gn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:G.isPending,onConfirm:()=>G.mutate(),onCancel:()=>L(!1)})]})}const eK={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function TZe({onClose:t}){const{t:e}=Ot(),n=en(),{showToast:r}=an(),[a,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,u]=w.useState(null),{data:d}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),h=st({mutationFn:()=>k1.create({name:a.trim()||"Bambuddy",mode:o,target_printer_id:o==="proxy"?c??void 0:void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["virtual-printers"]}),r(e("virtualPrinter.toast.created")),t()},onError:f=>{r(f.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:i.jsx(wt,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:i.jsxs(_t,{className:"p-6 space-y-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),i.jsx("input",{type:"text",value:a,onChange:f=>s(f.target.value),placeholder:"Bambuddy",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm placeholder-bambu-gray",autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(f=>i.jsxs("button",{onClick:()=>l(f),className:`p-2 rounded-lg border text-left transition-colors ${o===f?f==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[f==="proxy"&&i.jsx(e3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${eK[f]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${eK[f]}Desc`)})]},f))})]}),o==="proxy"&&i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:c??"",onChange:f=>{const p=parseInt(f.target.value,10);u(isNaN(p)?null:p)},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm appearance-none cursor-pointer pr-10",children:[i.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),d?.map(f=>i.jsxs("option",{value:f.id,children:[f.name," (",f.ip_address,")"]},f.id))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",disabled:h.isPending,children:e("common.cancel")}),i.jsx(Ce,{variant:"primary",onClick:()=>h.mutate(),className:"flex-1",disabled:h.isPending,children:h.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function MZe(){const{t}=Ot(),[e,n]=w.useState(!1),{data:r,isLoading:a}=Je({queryKey:["virtual-printers"],queryFn:k1.list,refetchInterval:1e4});if(a)return i.jsx(wt,{children:i.jsx(_t,{className:"py-8 flex justify-center",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[i.jsx(wt,{className:"border-l-4 border-l-yellow-500",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs",children:[i.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),i.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 mt-2 px-3 py-1.5 bg-yellow-500/20 border border-yellow-500/50 rounded text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs",children:[i.jsx(Xr,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),i.jsx(wt,{className:"lg:col-span-3",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),i.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(gr,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Gn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?i.jsx(wt,{children:i.jsxs(_t,{className:"py-8 text-center",children:[i.jsx(gr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Gn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>i.jsx(AZe,{printer:l,models:o},l.id))}),e&&i.jsx(TZe,{onClose:()=>n(!1)})]})}function tK({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:i.jsx(pr,{className:"w-3 h-3"}),failed:i.jsx(mi,{className:"w-3 h-3"}),skipped:i.jsx(TF,{className:"w-3 h-3"}),running:i.jsx(it,{className:"w-3 h-3 animate-spin"})};return i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function PZe(t){return t?new Date(t).toLocaleString():"-"}function EZe(){const t=en(),{showToast:e}=an(),{t:n}=Ot(),[r,a]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[u,d]=w.useState(!1),[h,f]=w.useState("daily"),[p,x]=w.useState(!0),[v,g]=w.useState(!0),[y,_]=w.useState(!1),[N,k]=w.useState(!0),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(""),[U,L]=w.useState(!1),[B,D]=w.useState(null),[$,G]=w.useState(null),z=w.useRef(null);w.useEffect(()=>{if(A||C){const O=R=>(R.preventDefault(),R.returnValue="A backup operation is in progress. Are you sure you want to leave?",R.returnValue);return window.addEventListener("beforeunload",O),()=>window.removeEventListener("beforeunload",O)}},[A,C]);const[W,X]=w.useState(!1),[ae,H]=w.useState(null),K=w.useRef(null),te=w.useRef(!1),{data:Z,isLoading:ve}=Je({queryKey:["github-backup-config"],queryFn:ne.getGitHubBackupConfig}),{data:ce}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus,refetchInterval:be=>be.state.data?.is_running?500:1e4}),{data:ee}=Je({queryKey:["github-backup-logs"],queryFn:()=>ne.getGitHubBackupLogs(20)}),{data:je}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:he}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),oe=SF({queries:(he??[]).map(be=>({queryKey:["printerStatus",be.id],queryFn:()=>ne.getPrinterStatus(be.id),staleTime:1e4,refetchInterval:3e4}))}),_e=(he??[]).map((be,O)=>({printer:be,connected:oe[O]?.data?.connected??!1})),ie=_e.length,ze=_e.filter(be=>be.connected).length,V=ie>0&&ze===0,Y=ze>0&&ze<ie;w.useEffect(()=>{Z&&(a(Z.repository_url),c(Z.branch),d(Z.schedule_enabled),f(Z.schedule_type),x(Z.backup_kprofiles),g(Z.backup_cloud_profiles),_(Z.backup_settings),k(Z.enabled),o(""),setTimeout(()=>{te.current=!0},100))},[Z]);const me=w.useCallback(async(be=!1)=>{if(Z?.has_token)try{be&&s?(await ne.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),o(""),e("Token updated")):(await ne.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(O){e(`Failed to save: ${O.message}`,"error")}},[Z?.has_token,r,s,l,u,h,p,v,y,N,t,e]);w.useEffect(()=>{if(!(!te.current||!Z?.has_token))return K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{me(!1)},500),()=>{K.current&&clearTimeout(K.current)}},[r,l,u,h,p,v,y,N,me,Z?.has_token]),w.useEffect(()=>{if(!(!te.current||!Z?.has_token||!s))return K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{me(!0)},1e3),()=>{K.current&&clearTimeout(K.current)}},[s,me,Z?.has_token]);const Q=st({mutationFn:be=>ne.saveGitHubBackupConfig(be),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),te.current=!0},onError:be=>{e(`Failed to save: ${be.message}`,"error")}}),se=st({mutationFn:ne.triggerGitHubBackup,onSuccess:be=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),be.success?be.files_changed>0?e(`Backup complete - ${be.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${be.message}`,"error")},onError:be=>{e(`Backup failed: ${be.message}`,"error")}}),de=st({mutationFn:()=>ne.clearGitHubBackupLogs(0),onSuccess:be=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${be.deleted} logs`)},onError:be=>{e(`Failed to clear logs: ${be.message}`,"error")}}),Le=async()=>{X(!0),H(null);try{let be;if(s){if(!r){e("Enter repository URL","error"),X(!1);return}be=await ne.testGitHubConnection(r,s)}else if(Z?.has_token)be=await ne.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),X(!1);return}H({success:be.success,message:be.message})}catch(be){H({success:!1,message:be.message})}finally{X(!1)}},Ne=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}Q.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N})};return ve?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(r3,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),Z&&je?.is_authenticated&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),i.jsx(In,{checked:N,onChange:k})]})]})}),i.jsx(_t,{className:"space-y-4",children:je?.is_authenticated?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),i.jsx("input",{type:"text",value:r,onChange:be=>{a(be.target.value),H(null)},placeholder:"https://github.com/username/bambuddy-backup",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",Z?.has_token&&i.jsx("span",{className:"text-green-400",children:"(saved)"})]}),i.jsx("input",{type:"password",value:s,onChange:be=>{o(be.target.value),H(null)},placeholder:Z?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),i.jsx("input",{type:"text",value:l,onChange:be=>c(be.target.value),placeholder:"main",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),i.jsxs("select",{value:u?h:"disabled",onChange:be=>{be.target.value==="disabled"?d(!1):(d(!0),f(be.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"disabled",children:"Manual only"}),i.jsx("option",{value:"hourly",children:"Hourly"}),i.jsx("option",{value:"daily",children:"Daily"}),i.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:`flex items-start gap-2 ${V?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[i.jsx("input",{type:"checkbox",checked:p,onChange:be=>x(be.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:V}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`text-sm ${V?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),V&&i.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[i.jsx(Tn,{className:"w-3 h-3"}),"No printers connected"]}),Y&&i.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[i.jsx(Tn,{className:"w-3 h-3"}),ze,"/",ie," connected"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:v,onChange:be=>g(be.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:!je?.is_authenticated}),i.jsxs("div",{children:[i.jsx("span",{className:`text-sm ${je?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:y,onChange:be=>_(be.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white text-sm",children:"App Settings"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[ce?.configured&&i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:ce.last_backup_at?i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:["Last backup: ",yv(ce.last_backup_at,"system",n)]}),i.jsx(tK,{status:ce.last_backup_status})]}):i.jsx("span",{children:"No backups yet"})}),ce.next_scheduled_run&&i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx(Wn,{className:"w-3 h-3 inline mr-1"}),"Next: ",yv(ce.next_scheduled_run,"system",n)]})]}),ae&&i.jsxs("div",{className:`text-sm flex items-center gap-1 ${ae.success?"text-green-400":"text-red-400"}`,children:[ae.success?i.jsx(pr,{className:"w-4 h-4"}):i.jsx(mi,{className:"w-4 h-4"}),ae.message]}),i.jsx("div",{className:"flex flex-wrap items-center gap-2",children:ce?.configured?i.jsx(i.Fragment,{children:se.isPending||ce.is_running?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{className:"text-sm",children:ce.progress||"Starting backup..."})]}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>se.mutate(),disabled:!Z?.enabled,children:[i.jsx(io,{className:"w-4 h-4"}),"Backup Now"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,disabled:W,children:[W?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4"}),"Test"]})]})}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:Ne,disabled:Q.isPending||!r||!s,children:[Q.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(pr,{className:"w-4 h-4"}),"Enable Backup"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,disabled:W||!r||!s,children:[W?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),ee&&ee.length>0&&i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(db,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>de.mutate(),disabled:de.isPending,children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),i.jsx("tbody",{children:ee.slice(0,10).map(be=>i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[i.jsx("td",{className:"py-2 px-2 text-white",children:PZe(be.started_at)}),i.jsx("td",{className:"py-2 px-2",children:i.jsx(tK,{status:be.status})}),i.jsx("td",{className:"py-2 px-2",children:be.commit_sha?i.jsxs("a",{href:`${Z?.repository_url}/commit/${be.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[be.commit_sha.substring(0,7),i.jsx(Xr,{className:"w-3 h-3"})]}):i.jsx("span",{className:"text-bambu-gray",children:"-"})})]},be.id))})]})})})]})]}),i.jsx("div",{className:"space-y-6",children:i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ec,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Download Backup"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:A||C,onClick:async()=>{M(!0),E("Preparing backup...");try{E("Creating backup archive... This may take a while for large archives.");const{blob:be,filename:O}=await ne.exportBackup();E("Downloading backup file...");const R=URL.createObjectURL(be),q=document.createElement("a");q.href=R,q.download=O,q.click(),URL.revokeObjectURL(R),e("Backup downloaded successfully")}catch(be){e(`Failed to create backup: ${be instanceof Error?be.message:"Unknown error"}`,"error")}finally{M(!1),E("")}},children:[i.jsx(da,{className:"w-4 h-4"}),"Download"]})]}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),i.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),i.jsx("input",{ref:z,type:"file",accept:".zip",className:"hidden",onChange:be=>{const O=be.target.files?.[0];O&&(D(O),L(!0)),be.target.value=""}}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:C||A,onClick:()=>z.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Restore"]})]}),$&&i.jsx("div",{className:`p-3 rounded-lg ${$.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[$.success?i.jsx(pr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):i.jsx(mi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:$.success?"text-green-200":"text-red-200",children:[$.message,$.success&&i.jsx("div",{className:"mt-2",children:i.jsxs(Ce,{size:"sm",onClick:()=>window.location.reload(),children:[i.jsx(so,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-yellow-200",children:[i.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",i.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),U&&B&&i.jsx(gn,{title:"Restore Backup",message:`Are you sure you want to restore from "${B.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{L(!1),j(!0),G(null);try{E("Uploading backup file...");const be=await ne.importBackup(B);G(be),be.success?e("Backup restored. Please restart Bambuddy.","success"):e(be.message,"error")}catch(be){const O=be instanceof Error?be.message:"Failed to restore backup";G({success:!1,message:O}),e(O,"error")}finally{j(!1),E(""),D(null)}},onCancel:()=>{L(!1),D(null)}}),(A||C)&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[i.jsx("div",{className:"flex justify-center mb-4",children:i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),i.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:A?"Creating Backup":"Restoring Backup"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:P||(A?"Preparing...":"Processing...")}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}const jZe={starttls:587,ssl:465,none:25},DZe={587:"starttls",465:"ssl",25:"none"};function RZe(){const{t}=Ot(),{showToast:e}=an(),n=en(),[r,a]=w.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=w.useState(""),{data:l,isLoading:c}=Je({queryKey:["smtpSettings"],queryFn:()=>ne.getSMTPSettings()}),{data:u}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()});w.useEffect(()=>{l&&a({...l,smtp_password:""})},[l]);const d=M=>{a({...r,smtp_security:M,smtp_port:jZe[M]})},h=M=>{const C=DZe[M];a({...r,smtp_port:M,...C?{smtp_security:C}:{}})},f=M=>{a({...r,smtp_auth_enabled:M,...M?{}:{smtp_username:"",smtp_password:""}})},p=st({mutationFn:M=>ne.saveSMTPSettings(M),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:M=>{e(M.message,"error")}}),x=st({mutationFn:M=>ne.testSMTP(M),onSuccess:M=>{e(M.message,M.success?"success":"error")},onError:M=>{e(M.message,"error")}}),v=st({mutationFn:M=>M?ne.enableAdvancedAuth():ne.disableAdvancedAuth(),onSuccess:M=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(M.message,"success")},onError:M=>{e(M.message,"error")}}),g=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}p.mutate(r)},y=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}x.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},_=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}v.mutate(!u?.advanced_auth_enabled)};if(c)return i.jsx("div",{className:"flex items-center justify-center p-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});const N=u?.advanced_auth_enabled??!1,k="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",A="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return i.jsxs("div",{className:"space-y-6",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(bv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),i.jsx(Ce,{onClick:_,disabled:v.isPending,variant:N?"danger":"primary",children:N?i.jsxs(i.Fragment,{children:[i.jsx(H_,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):i.jsxs(i.Fragment,{children:[i.jsx(zm,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),i.jsx(_t,{children:i.jsx("div",{className:"space-y-4",children:N?i.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),i.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),i.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),i.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),i.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):i.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),i.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),i.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:M=>f(M.target.value==="true"),className:k,children:[i.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),i.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),i.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${r.smtp_auth_enabled?"":"opacity-40 pointer-events-none"}`,children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),i.jsx("input",{type:"text",value:r.smtp_username||"",onChange:M=>a({...r,smtp_username:M.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),i.jsx("input",{type:"password",value:r.smtp_password||"",onChange:M=>a({...r,smtp_password:M.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),i.jsx("input",{type:"text",value:r.smtp_host,onChange:M=>a({...r,smtp_host:M.target.value}),placeholder:"smtp.gmail.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),i.jsx("input",{type:"number",value:r.smtp_port,onChange:M=>h(parseInt(M.target.value)||587),placeholder:"587",className:k})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),i.jsxs("select",{value:r.smtp_security,onChange:M=>d(M.target.value),className:k,children:[i.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),i.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),i.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),i.jsx("input",{type:"email",value:r.smtp_from_email,onChange:M=>a({...r,smtp_from_email:M.target.value}),placeholder:"your@email.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),i.jsx("input",{type:"text",value:r.smtp_from_name,onChange:M=>a({...r,smtp_from_name:M.target.value}),placeholder:"BamBuddy",className:k})]})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx(Ce,{onClick:g,disabled:p.isPending,className:"flex-1",children:p.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),i.jsx("input",{type:"email",value:s,onChange:M=>o(M.target.value),placeholder:"test@example.com",className:k})]}),i.jsx(Ce,{onClick:y,disabled:x.isPending,variant:"secondary",children:x.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):i.jsxs(i.Fragment,{children:[i.jsx(ZC,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})}const FZe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function LZe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const a of n)r=r[a];return r}function zy(t,e,n=0){if(n>5)return"...";if(e.$ref)return zy(t,LZe(t,e.$ref),n+1);if(e.allOf){const r={};for(const a of e.allOf){const s=zy(t,a,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[zy(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[a,s]of Object.entries(e.properties))r[a]=zy(t,s,n+1);return r}return{};default:return null}}function OZe({path:t,method:e,spec:n,schema:r,apiKey:a}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[h,f]=w.useState(null),[p,x]=w.useState(!1),[v,g]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const j={};for(const P of n.parameters)P.schema?.default!==void 0&&(j[P.name]=String(P.schema.default));c(P=>({...j,...P}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const j=n.requestBody.content["application/json"].schema,P=zy(r,j);d(JSON.stringify(P,null,2))}},[s,n.requestBody,r,u]);const _=(()=>{const j=[];for(const P of n.parameters||[])if(P.in==="path"||P.required){const E=l[P.name];(E===void 0||E==="")&&j.push(P.name)}return j})(),N=async()=>{if(_.length>0){f({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${_.join(", ")}`,duration:0});return}x(!0),f(null);try{let j=t;const P=new URLSearchParams;for(const ae of n.parameters||[]){const H=l[ae.name];H!==void 0&&H!==""&&(ae.in==="path"?j=j.replace(`{${ae.name}}`,encodeURIComponent(H)):ae.in==="query"&&P.append(ae.name,H))}const E=P.toString(),U=`${j}${E?`?${E}`:""}`,L={"Content-Type":"application/json"};a&&(L["X-API-Key"]=a);const B={method:e.toUpperCase(),headers:L};["post","put","patch"].includes(e)&&u&&(B.body=u);const D=performance.now(),$=await fetch(U,B),G=Math.round(performance.now()-D),z={};$.headers.forEach((ae,H)=>{z[H]=ae});let W;$.headers.get("content-type")?.includes("application/json")?W=await $.json():W=await $.text(),f({status:$.status,statusText:$.statusText,headers:z,body:W,duration:G})}catch(j){f({status:0,statusText:"Network Error",headers:{},body:j instanceof Error?j.message:"Unknown error",duration:0})}finally{x(!1)}},k=async()=>{if(h){const j=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(j),g(!0),setTimeout(()=>g(!1),2e3)}catch{const P=document.createElement("textarea");P.value=j,P.style.position="fixed",P.style.left="-999999px",document.body.appendChild(P),P.select(),document.execCommand("copy"),document.body.removeChild(P),g(!0),setTimeout(()=>g(!1),2e3)}}},A=(n.parameters||[]).filter(j=>j.in==="path"),M=(n.parameters||[]).filter(j=>j.in==="query"),C=["post","put","patch"].includes(e)&&n.requestBody;return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?i.jsx(Pn,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${FZe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),i.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&i.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&i.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),A.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),i.jsx("div",{className:"space-y-2",children:A.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),M.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),i.jsx("div",{className:"space-y-2",children:M.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),j.schema?.enum?i.jsxs("select",{value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:"-- Select --"}),j.schema.enum.map(P=>i.jsx("option",{value:P,children:P},P))]}):i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),C&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),i.jsx("textarea",{value:u,onChange:j=>d(j.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{onClick:N,disabled:p,children:[p?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(io,{className:"w-4 h-4"}),"Execute"]}),_.length>0&&i.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),"Fill in: ",_.join(", ")]})]}),h&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",i.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:k,children:v?i.jsx(pr,{className:"w-3 h-3 text-green-400"}):i.jsx(Yl,{className:"w-3 h-3"})})]}),i.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function IZe({apiKey:t=""}){const[e,n]=w.useState(null),[r,a]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function g(){try{const y=await fetch("/openapi.json");if(!y.ok)throw new Error("Failed to fetch OpenAPI schema");const _=await y.json();n(_)}catch(y){o(y instanceof Error?y.message:"Unknown error")}finally{a(!1)}}g()},[]),r)return i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return i.jsx(wt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-red-400",children:[i.jsx(Ba,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{children:"Failed to load API schema"}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[g,y]of Object.entries(e.paths))for(const[_,N]of Object.entries(y)){if(_==="parameters")continue;const k=N.tags||["Other"];for(const A of k)h[A]||(h[A]=[]),h[A].push({path:g,method:_,spec:N})}const f=Object.entries(h).map(([g,y])=>{if(!u)return{tag:g,endpoints:y};const _=y.filter(({path:N,method:k,spec:A})=>{const M=u.toLowerCase();return N.toLowerCase().includes(M)||k.toLowerCase().includes(M)||(A.summary?.toLowerCase()||"").includes(M)||(A.description?.toLowerCase()||"").includes(M)});return{tag:g,endpoints:_}}).filter(({endpoints:g})=>g.length>0).sort((g,y)=>g.tag.localeCompare(y.tag)),p=g=>{c(y=>{const _=new Set(y);return _.has(g)?_.delete(g):_.add(g),_})},x=()=>{c(new Set(f.map(g=>g.tag)))},v=()=>{c(new Set)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx("input",{type:"text",value:u,onChange:g=>d(g.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),i.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[i.jsx(Xr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f.reduce((g,y)=>g+y.endpoints.length,0)," endpoints in ",f.length," categories"]}),i.jsx("div",{className:"space-y-3",children:f.map(({tag:g,endpoints:y})=>i.jsxs(wt,{children:[i.jsx("button",{onClick:()=>p(g),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:i.jsxs("div",{className:"flex items-center gap-2",children:[l.has(g)?i.jsx(Pn,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(pi,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:g.replace(/-/g," ")}),i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:y.length})]})}),l.has(g)&&i.jsx(_t,{className:"pt-0 space-y-2",children:y.map(({path:_,method:N,spec:k})=>i.jsx(OZe,{path:_,method:N,spec:k,schema:e,apiKey:t},`${N}-${_}`))})]},g))})]})}const zZe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"],UZe={database:"bg-blue-600",library_files:"bg-green-500",library_thumbnails:"bg-teal-500",library_other:"bg-emerald-700",archive_timelapses:"bg-red-500",archive_thumbnails:"bg-amber-500",archive_files:"bg-sky-500",virtual_printer_uploads:"bg-purple-500",virtual_printer_upload_cache:"bg-fuchsia-500",virtual_printer_certs:"bg-violet-500",virtual_printer_other:"bg-purple-700",downloads:"bg-cyan-500",plate_calibration:"bg-lime-500",logs:"bg-orange-500",other_data:"bg-yellow-500"},nK=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],rK=(t,e)=>UZe[t]||nK[e%nK.length];function BZe(){const t=en(),e=rc(),[n,r]=BC(),{t:a,i18n:s}=Ot(),{showToast:o}=an(),{authEnabled:l,user:c,refreshAuth:u}=Ir(),{mode:d,darkStyle:h,darkBackground:f,darkAccent:p,lightStyle:x,lightBackground:v,lightAccent:g,setDarkStyle:y,setDarkBackground:_,setDarkAccent:N,setLightStyle:k,setLightBackground:A,setLightAccent:M}=tp(),[C,j]=w.useState(null),[P,E]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(!1),[$,G]=w.useState(null),[z,W]=w.useState(null),[X,ae]=w.useState(!1),[H,K]=w.useState(EX()),te=n.get("tab"),Z=te==="email",ve=Z?"users":te&&zZe.includes(te)?te:"general",[ce,ee]=w.useState(ve),[je,he]=w.useState(Z?"email":"users"),oe=ue=>{ee(ue),ue==="users"&&he("users"),ue==="general"?n.delete("tab"):n.set("tab",ue),r(n,{replace:!0})},[_e,ie]=w.useState(!1),[ze,V]=w.useState(""),[Y,me]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[Q,se]=w.useState(null),[de,Le]=w.useState(null),[Ne,be]=w.useState(""),[O,R]=w.useState(!1),[q,J]=w.useState(!1),[fe,le]=w.useState(null),[Be,Ie]=w.useState(!1),[Ke,Oe]=w.useState(!1),[pe,xe]=w.useState(!1),[ke,ge]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[we,qe]=w.useState(!1),[Ee,tt]=w.useState(!1),[De,We]=w.useState(!1),[Ae,Re]=w.useState(!1),[$e,ht]=w.useState(null),[At,Dt]=w.useState(null),[It,kt]=w.useState(null),[Ue,bt]=w.useState(!1),[yt,Gt]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Cn,vr]=w.useState(null),[Qn,tr]=w.useState(null),[En,dr]=w.useState(!1),[Tr,si]=w.useState({}),[Fe,Se]=w.useState({}),nt=ue=>{K(ue),Cge(ue),o(a("settings.toast.settingsSaved"),"success")},ot=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:Ge,isLoading:zt}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:ye,isLoading:He,isFetching:Ye}=Je({queryKey:["storage-usage"],queryFn:()=>ne.getStorageUsage(),enabled:ce==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),Xe=async()=>{tt(!0);try{const ue=await ne.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],ue)}catch(ue){const Et=ue instanceof Error?ue.message:"Failed to refresh storage usage";o(Et,"error")}finally{tt(!1)}},{data:Te,isLoading:lt}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:pt,isLoading:at}=Je({queryKey:["smart-plugs-energy",Te?.map(ue=>ue.id)],queryFn:async()=>{if(!Te||Te.length===0)return null;const ue=await Promise.all(Te.filter(fo=>fo.enabled).map(async fo=>{try{const _s=await ne.getSmartPlugStatus(fo.id);return{plug:fo,status:_s}}catch{return{plug:fo,status:null}}}));let Et=0,sa=0,Wr=0,Yc=0,cp=0;for(const{plug:fo,status:_s}of ue){const PA=fo.plug_type==="mqtt"&&_s?.energy?.power!=null;(_s?.reachable||PA)&&_s?.energy&&(cp++,_s.energy?.power!=null&&(Et+=_s.energy.power),_s.energy?.today!=null&&(sa+=_s.energy.today),_s.energy?.yesterday!=null&&(Wr+=_s.energy.yesterday),_s.energy?.total!=null&&(Yc+=_s.energy.total))}return{totalPower:Et,totalToday:sa,totalYesterday:Wr,totalLifetime:Yc,reachableCount:cp,totalPlugs:Te.filter(fo=>fo.enabled).length}},enabled:ce==="plugs"&&!!Te&&Te.length>0,refetchInterval:ce==="plugs"?1e4:!1}),{data:Tt,isLoading:$t}=Je({queryKey:["notification-providers"],queryFn:ne.getNotificationProviders}),{data:Rt,isLoading:Pt}=Je({queryKey:["api-keys"],queryFn:ne.getAPIKeys}),sn=st({mutationFn:ue=>ne.createAPIKey(ue),onSuccess:ue=>{se(ue.key||null),ie(!1),V(""),t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyCreated"))},onError:ue=>{o(`Failed to create API key: ${ue.message}`,"error")}}),Zt=st({mutationFn:ue=>ne.deleteAPIKey(ue),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyDeleted"))},onError:ue=>{o(`Failed to delete API key: ${ue.message}`,"error")}}),{data:un}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:kn,isLoading:Dn}=Je({queryKey:["notification-templates"],queryFn:ne.getNotificationTemplates}),{data:Xt}=Je({queryKey:["virtual-printer-settings"],queryFn:mge.getSettings,refetchInterval:1e4}),mn=Xt?.status?.running??!1,{data:fn}=Je({queryKey:["ffmpeg-status"],queryFn:ne.checkFfmpeg}),{data:Gr}=Je({queryKey:["version"],queryFn:ne.getVersion}),{data:pn,refetch:Rn,isRefetching:ia}=Je({queryKey:["updateCheck"],queryFn:ne.checkForUpdates,enabled:Ge?.check_updates!==!1,staleTime:300*1e3}),{data:Sn,refetch:va}=Je({queryKey:["updateStatus"],queryFn:ne.getUpdateStatus,refetchInterval:ue=>{const Et=ue.state.data;return Et?.status==="downloading"||Et?.status==="installing"?1e3:!1}}),{data:sr}=Je({queryKey:["mqtt-status"],queryFn:ne.getMQTTStatus,refetchInterval:ce==="network"?5e3:!1}),{data:ma}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus}),{data:xt}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:Ft={advanced_auth_enabled:!1,smtp_configured:!1}}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),{hasPermission:bn}=Ir(),{data:Nt=[],isLoading:Zn}=Je({queryKey:["users"],queryFn:()=>ne.getUsers(),enabled:l&&bn("users:read")}),{data:wr=[],isLoading:hr}=Je({queryKey:["groups"],queryFn:()=>ne.getGroups(),enabled:l&&bn("groups:read")}),wa=st({mutationFn:ue=>ne.createUser(ue),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),We(!1),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userCreated"))},onError:ue=>{o(ue.message,"error")}}),Va=st({mutationFn:({id:ue,data:Et})=>ne.updateUser(ue,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Re(!1),ht(null),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userUpdated"))},onError:ue=>{o(ue.message,"error")}}),Vt=st({mutationFn:({id:ue,deleteItems:Et})=>ne.deleteUser(ue,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(a("settings.toast.userDeleted")),Dt(null),kt(null)},onError:ue=>{o(ue.message,"error")}}),xn=st({mutationFn:ue=>ne.resetUserPassword({user_id:ue}),onSuccess:ue=>{o(ue.message,"success")},onError:ue=>{o(ue.message,"error")}}),Ss=async ue=>{Dt(ue),bt(!0);try{const Et=await ne.getUserItemsCount(ue);kt(Et)}catch{kt({archives:0,queue_items:0,library_files:0})}finally{bt(!1)}},Ci=st({mutationFn:ue=>ne.deleteGroup(ue),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(a("settings.toast.groupDeleted"))},onError:ue=>{o(ue.message,"error")}}),ns=()=>{const ue=Ft?.advanced_auth_enabled||!1;if(!yt.username){o(a("settings.toast.fillRequiredFields"),"error");return}if(ue&&!yt.email){o("Email is required when advanced authentication is enabled","error");return}if(!ue){if(!yt.password){o(a("settings.toast.fillRequiredFields"),"error");return}if(yt.password!==yt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(yt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}wa.mutate({username:yt.username,password:ue?void 0:yt.password,email:yt.email||void 0,role:yt.role,group_ids:yt.group_ids.length>0?yt.group_ids:void 0})},Tl=ue=>{if(yt.password){if(yt.password!==yt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(yt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}const Et={username:yt.username||void 0,password:yt.password||void 0,role:yt.role,group_ids:yt.group_ids};Et.password||delete Et.password,Va.mutate({id:ue,data:Et})},rs=ue=>{ht(ue.id),Gt({username:ue.username,password:"",email:ue.email||"",confirmPassword:"",role:ue.role,group_ids:ue.groups?.map(Et=>Et.id)||[]}),Re(!0)},oi=ue=>{Gt(Et=>({...Et,group_ids:Et.group_ids.includes(ue)?Et.group_ids.filter(sa=>sa!==ue):[...Et.group_ids,ue]}))},Sa=st({mutationFn:ne.applyUpdate,onSuccess:ue=>{ue.is_docker?o(ue.message,"error"):va()}}),[Qr,mr]=w.useState(null),ho=st({mutationFn:ne.testAllNotificationProviders,onSuccess:ue=>{mr(ue),t.invalidateQueries({queryKey:["notification-providers"]}),ue.failed===0?o(`All ${ue.tested} providers tested successfully!`,"success"):o(`${ue.success}/${ue.tested} providers succeeded`,ue.failed>0?"error":"success")},onError:ue=>{o(`Failed to test providers: ${ue.message}`,"error")}}),qa=st({mutationFn:async ue=>{if(!Te)return{success:0,failed:0};const Et=Te.filter(Wr=>Wr.enabled),sa=await Promise.all(Et.map(async Wr=>{try{return await ne.controlSmartPlug(Wr.id,ue),{success:!0}}catch{return{success:!1}}}));return{success:sa.filter(Wr=>Wr.success).length,failed:sa.filter(Wr=>!Wr.success).length}},onSuccess:(ue,Et)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ue.failed===0?o(`All ${ue.success} plugs turned ${Et}`,"success"):o(`${ue.success} plugs turned ${Et}, ${ue.failed} failed`,"error")},onError:ue=>{o(`Failed: ${ue.message}`,"error")}}),Oa=w.useRef(null),mo=w.useRef(!1),Ur=w.useRef(!0);w.useEffect(()=>{if(Ge&&!C){const ue={...Ge,external_url:Ge.external_url||window.location.origin};j(ue),setTimeout(()=>{Ur.current=!1},100)}},[Ge,C]);const fa=st({mutationFn:ne.updateSettings,onSuccess:ue=>{t.setQueryData(["settings"],ue),j(ue),t.invalidateQueries({queryKey:["archiveStats"]}),o(a("settings.toast.settingsSaved"),"success")},onError:ue=>{o(`Failed to save: ${ue.message}`,"error")},onSettled:()=>{mo.current=!1}}),Us=st({mutationFn:({id:ue,data:Et})=>ne.updatePrinter(ue,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(a("settings.toast.cameraSettingsSaved"),"success")},onError:ue=>{o(`Failed to update printer: ${ue.message}`,"error")}});w.useEffect(()=>{if(!(Ur.current||!C||!Ge||!(Ge.auto_archive!==C.auto_archive||Ge.save_thumbnails!==C.save_thumbnails||Ge.capture_finish_photo!==C.capture_finish_photo||Ge.default_filament_cost!==C.default_filament_cost||Ge.currency!==C.currency||Ge.energy_cost_per_kwh!==C.energy_cost_per_kwh||Ge.energy_tracking_mode!==C.energy_tracking_mode||Ge.check_updates!==C.check_updates||(Ge.check_printer_firmware??!0)!==(C.check_printer_firmware??!0)||(Ge.include_beta_updates??!1)!==(C.include_beta_updates??!1)||Ge.notification_language!==C.notification_language||(Ge.bed_cooled_threshold??35)!==(C.bed_cooled_threshold??35)||Ge.ams_humidity_good!==C.ams_humidity_good||Ge.ams_humidity_fair!==C.ams_humidity_fair||Ge.ams_temp_good!==C.ams_temp_good||Ge.ams_temp_fair!==C.ams_temp_fair||Ge.ams_history_retention_days!==C.ams_history_retention_days||Ge.per_printer_mapping_expanded!==C.per_printer_mapping_expanded||Ge.date_format!==C.date_format||Ge.time_format!==C.time_format||Ge.default_printer_id!==C.default_printer_id||Ge.ftp_retry_enabled!==C.ftp_retry_enabled||Ge.ftp_retry_count!==C.ftp_retry_count||Ge.ftp_retry_delay!==C.ftp_retry_delay||Ge.ftp_timeout!==C.ftp_timeout||Ge.mqtt_enabled!==C.mqtt_enabled||Ge.mqtt_broker!==C.mqtt_broker||Ge.mqtt_port!==C.mqtt_port||Ge.mqtt_username!==C.mqtt_username||Ge.mqtt_password!==C.mqtt_password||Ge.mqtt_topic_prefix!==C.mqtt_topic_prefix||Ge.mqtt_use_tls!==C.mqtt_use_tls||Ge.external_url!==C.external_url||Ge.ha_enabled!==C.ha_enabled||Ge.ha_url!==C.ha_url||Ge.ha_token!==C.ha_token||(Ge.library_archive_mode??"ask")!==(C.library_archive_mode??"ask")||Number(Ge.library_disk_warning_gb??5)!==Number(C.library_disk_warning_gb??5)||(Ge.camera_view_mode??"window")!==(C.camera_view_mode??"window")||(Ge.preferred_slicer??"bambu_studio")!==(C.preferred_slicer??"bambu_studio")||Ge.prometheus_enabled!==C.prometheus_enabled||Ge.prometheus_token!==C.prometheus_token))&&!mo.current)return Oa.current&&clearTimeout(Oa.current),Oa.current=setTimeout(()=>{if(mo.current)return;mo.current=!0;const Et={auto_archive:C.auto_archive,save_thumbnails:C.save_thumbnails,capture_finish_photo:C.capture_finish_photo,default_filament_cost:C.default_filament_cost,currency:C.currency,energy_cost_per_kwh:C.energy_cost_per_kwh,energy_tracking_mode:C.energy_tracking_mode,check_updates:C.check_updates,check_printer_firmware:C.check_printer_firmware,include_beta_updates:C.include_beta_updates,notification_language:C.notification_language,bed_cooled_threshold:C.bed_cooled_threshold,ams_humidity_good:C.ams_humidity_good,ams_humidity_fair:C.ams_humidity_fair,ams_temp_good:C.ams_temp_good,ams_temp_fair:C.ams_temp_fair,ams_history_retention_days:C.ams_history_retention_days,per_printer_mapping_expanded:C.per_printer_mapping_expanded,date_format:C.date_format,time_format:C.time_format,default_printer_id:C.default_printer_id,ftp_retry_enabled:C.ftp_retry_enabled,ftp_retry_count:C.ftp_retry_count,ftp_retry_delay:C.ftp_retry_delay,ftp_timeout:C.ftp_timeout,mqtt_enabled:C.mqtt_enabled,mqtt_broker:C.mqtt_broker,mqtt_port:C.mqtt_port,mqtt_username:C.mqtt_username,mqtt_password:C.mqtt_password,mqtt_topic_prefix:C.mqtt_topic_prefix,mqtt_use_tls:C.mqtt_use_tls,external_url:C.external_url,ha_enabled:C.ha_enabled,ha_url:C.ha_url,ha_token:C.ha_token,library_archive_mode:C.library_archive_mode,library_disk_warning_gb:C.library_disk_warning_gb,camera_view_mode:C.camera_view_mode,preferred_slicer:C.preferred_slicer,prometheus_enabled:C.prometheus_enabled,prometheus_token:C.prometheus_token};fa.mutate(Et)},500),()=>{Oa.current&&clearTimeout(Oa.current)}},[C,Ge,fa]);const Ht=w.useCallback((ue,Et)=>{j(sa=>sa?{...sa,[ue]:Et}:null)},[]),Vn=async(ue,Et,sa)=>{if(!Et){o(a("settings.toast.enterCameraUrl"),"error");return}Se(Wr=>({...Wr,[ue]:!0})),si(Wr=>({...Wr,[ue]:null}));try{const Wr=await ne.testExternalCamera(ue,Et,sa);si(Yc=>({...Yc,[ue]:Wr})),Wr.success?o(a("settings.toast.cameraConnected",{resolution:Wr.resolution||""}),"success"):o(Wr.error||a("settings.toast.connectionFailed"),"error")}catch(Wr){const Yc=Wr instanceof Error?Wr.message:a("settings.toast.testFailed");si(cp=>({...cp,[ue]:{success:!1,error:Yc}})),o(Yc,"error")}finally{Se(Wr=>({...Wr,[ue]:!1}))}},[Ml,um]=w.useState({}),Xc=w.useRef({}),Y0=w.useRef(new Set);w.useEffect(()=>{if(un){const ue={};un.forEach(Et=>{Et.external_camera_url&&!Y0.current.has(Et.id)&&(ue[Et.id]=Et.external_camera_url,Y0.current.add(Et.id))}),Object.keys(ue).length>0&&um(Et=>({...Et,...ue}))}},[un]);const hx=(ue,Et)=>{um(sa=>({...sa,[ue]:Et})),Xc.current[ue]&&clearTimeout(Xc.current[ue]),Xc.current[ue]=setTimeout(()=>{Us.mutate({id:ue,data:{external_camera_url:Et||null}})},800)},lp=(ue,Et)=>{const sa={};Et.type!==void 0&&(sa.external_camera_type=Et.type||null),Et.enabled!==void 0&&(sa.external_camera_enabled=Et.enabled),Us.mutate({id:ue,data:sa})};return zt||!C?i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-8",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:a("settings.title")}),i.jsx("p",{className:"text-bambu-gray",children:a("settings.configureBambuddy")})]}),i.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>oe("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${ce==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:a("settings.tabs.general")}),i.jsxs("button",{onClick:()=>oe("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(fl,{className:"w-4 h-4"}),a("settings.tabs.smartPlugs"),Te&&Te.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Te.length})]}),i.jsxs("button",{onClick:()=>oe("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(qg,{className:"w-4 h-4"}),a("settings.tabs.notifications"),Tt&&Tt.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Tt.length})]}),i.jsxs("button",{onClick:()=>oe("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Whe,{className:"w-4 h-4"}),a("settings.tabs.filament")]}),i.jsxs("button",{onClick:()=>oe("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Wg,{className:"w-4 h-4"}),a("settings.tabs.network"),i.jsx("span",{className:`w-2 h-2 rounded-full ${sr?.enabled?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.tabs.apiKeys"),Rt&&Rt.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Rt.length})]}),i.jsxs("button",{onClick:()=>oe("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(gr,{className:"w-4 h-4"}),a("settings.tabs.virtualPrinter"),i.jsx("span",{className:`w-2 h-2 rounded-full ${mn?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(mh,{className:"w-4 h-4"}),a("settings.tabs.users"),l&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),i.jsxs("button",{onClick:()=>oe("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${ce==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Ec,{className:"w-4 h-4"}),a("settings.tabs.backup"),i.jsx("span",{className:`w-2 h-2 rounded-full ${xt?.is_authenticated&&ma?.configured&&ma?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),ce==="general"&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.general")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Ph,{className:"w-4 h-4 inline mr-1"}),a("settings.language")]}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:s.language,onChange:ue=>{s.changeLanguage(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:bB.map(ue=>i.jsxs("option",{value:ue.code,children:[ue.nativeName," (",ue.name,")"]},ue.code))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.languageDescription")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.defaultView")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:H,onChange:ue=>nt(ue.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:xv.map(ue=>i.jsx("option",{value:ue.to,children:a(ue.labelKey)},ue.id))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.defaultViewDescription")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.date_format||"system",onChange:ue=>Ht("date_format",ue.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),i.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),i.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.time_format||"system",onChange:ue=>Ht("time_format",ue.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),i.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.default_printer_id??"",onChange:ue=>Ht("default_printer_id",ue.target.value?Number(ue.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"",children:a("settings.noDefaultPrinter")}),un?.map(ue=>i.jsx("option",{value:ue.id,children:ue.name},ue.id))]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.preferredSlicer")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.preferred_slicer??"bambu_studio",onChange:ue=>Ht("preferred_slicer",ue.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),i.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.preferredSlicerDescription")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.sidebarOrder")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:ot,children:[i.jsx(so,{className:"w-4 h-4"}),"Reset"]})]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(XC,{className:"w-5 h-5"}),"Appearance"]})}),i.jsxs(_t,{className:"space-y-6",children:[i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:f,onChange:ue=>{_(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"}),i.jsx("option",{value:"oled",children:"OLED Black"}),i.jsx("option",{value:"slate",children:"Slate Blue"}),i.jsx("option",{value:"forest",children:"Forest Green"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:p,onChange:ue=>{N(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:h,onChange:ue=>{y(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:v,onChange:ue=>{A(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:g,onChange:ue=>{M(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:x,onChange:ue=>{k(ue.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.archiveSettings")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Auto-archive prints"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.auto_archive,onChange:ue=>Ht("auto_archive",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.saveThumbnails")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.save_thumbnails,onChange:ue=>Ht("save_thumbnails",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.captureFinishPhoto")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.capture_finish_photo,onChange:ue=>Ht("capture_finish_photo",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.capture_finish_photo&&fn&&!fn.installed&&i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm",children:[i.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),i.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(PF,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),i.jsxs("select",{value:C.camera_view_mode??"window",onChange:ue=>Ht("camera_view_mode",ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"window",children:a("settings.newWindow")}),i.jsx("option",{value:"embedded",children:a("settings.embeddedOverlay")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:a("settings.externalCameras")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),un&&un.length>0?i.jsx("div",{className:"space-y-3",children:un.map(ue=>i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-white font-medium text-sm",children:ue.name}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:ue.external_camera_enabled,onChange:Et=>lp(ue.id,{enabled:Et.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ue.external_camera_enabled&&i.jsxs("div",{className:"space-y-2 mt-2",children:[i.jsx("input",{type:"text",placeholder:ue.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Ml[ue.id]??ue.external_camera_url??"",onChange:Et=>hx(ue.id,Et.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ue.external_camera_type||"mjpeg",onChange:Et=>lp(ue.id,{type:Et.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),i.jsx("option",{value:"rtsp",children:"RTSP Stream"}),i.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),i.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>Vn(ue.id,Ml[ue.id]??ue.external_camera_url??"",ue.external_camera_type||"mjpeg"),disabled:Fe[ue.id]||!(Ml[ue.id]??ue.external_camera_url),children:Fe[ue.id]?i.jsx(it,{className:"w-4 h-4 animate-spin"}):"Test"})]}),Tr[ue.id]&&i.jsx("div",{className:`text-xs flex items-center gap-1 ${Tr[ue.id]?.success?"text-green-500":"text-red-500"}`,children:Tr[ue.id]?.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-3 h-3"}),"Connected",Tr[ue.id]?.resolution&&` (${Tr[ue.id]?.resolution})`]}):i.jsxs(i.Fragment,{children:[i.jsx(mi,{className:"w-3 h-3"}),Tr[ue.id]?.error||a("settings.toast.connectionFailed")]})})]})]},ue.id))}):i.jsx("p",{className:"text-xs text-bambu-gray italic",children:a("settings.noPrintersConfigured")})]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.costTracking")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),i.jsx("select",{value:C.currency,onChange:ue=>Ht("currency",ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:T$e.map(ue=>i.jsx("option",{value:ue.code,children:ue.label},ue.code))})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:C.default_filament_cost,onChange:ue=>Ht("default_filament_cost",parseFloat(ue.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.001",min:"0",value:C.energy_cost_per_kwh,onChange:ue=>Ht("energy_cost_per_kwh",parseFloat(ue.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),i.jsxs("select",{value:C.energy_tracking_mode||"total",onChange:ue=>Ht("energy_tracking_mode",ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"print",children:a("settings.printsOnly")}),i.jsx("option",{value:"total",children:a("settings.totalConsumption")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),i.jsxs("select",{value:C.library_archive_mode??"ask",onChange:ue=>Ht("library_archive_mode",ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"always",children:a("settings.archiveMode.always")}),i.jsx("option",{value:"never",children:a("settings.archiveMode.never")}),i.jsx("option",{value:"ask",children:a("settings.archiveMode.ask")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:C.library_disk_warning_gb??5,onChange:ue=>Ht("library_disk_warning_gb",parseFloat(ue.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[i.jsx(kZe,{}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkForUpdatesLabel")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_updates,onChange:ue=>Ht("check_updates",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkPrinterFirmware")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_printer_firmware??!0,onChange:ue=>Ht("check_printer_firmware",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:`flex items-center justify-between ${C.check_updates?"":"opacity-50"}`,children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.includeBetaUpdates")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.includeBetaUpdatesDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.include_beta_updates??!1,onChange:ue=>Ht("include_beta_updates",ue.target.checked),disabled:!C.check_updates,className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.currentVersion")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Gr?.version||"..."]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>Rn(),disabled:ia,children:[ia?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Ar,{className:"w-4 h-4"}),"Check now"]})]}),pn?.update_available?i.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{children:[i.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:pn.release_name})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[pn.release_notes&&i.jsx("button",{onClick:()=>Ie(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:a("settings.viewReleaseOnGitHub"),children:i.jsx(Xr,{className:"w-4 h-4"})})]})]}),Sn?.status==="downloading"||Sn?.status==="installing"?i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{children:Sn.message})]}),i.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Sn.progress}%`}})})]}):Sn?.status==="complete"?i.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:Sn.message}):Sn?.status==="error"?i.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:Sn.error||Sn.message}):pn?.is_docker?i.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),i.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):i.jsxs(Ce,{className:"mt-3",onClick:()=>Sa.mutate(),disabled:Sa.isPending,children:[Sa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(da,{className:"w-4 h-4"}),"Install Update"]})]}):pn?.error?i.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",pn.error]}):pn&&!pn.update_available?i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.dataManagement")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.clearNotificationLogs")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.clearNotificationLogsDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>R(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),a("common.clear")]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.resetUiPreferences")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.resetUiPreferencesDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>J(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),"Reset"]})]}),i.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.storageUsage","Storage Usage")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageDescription","Breakdown of data usage by category")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Xe,disabled:Ye||Ee,children:[i.jsx(Ar,{className:`w-4 h-4 ${Ye||Ee?"animate-spin":""}`}),a("common.refresh","Refresh")]})]}),i.jsx("div",{className:"mt-3",children:He?i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("common.loading","Loading")]}):ye?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:ye.categories.filter(ue=>ue.bytes>0).map((ue,Et)=>i.jsx("div",{className:`${rK(ue.key,Et)} h-full`,style:{width:`${ue.percent_of_total}%`},title:`${ue.label}: ${ue.formatted}`},ue.key))}),i.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:ye.categories.filter(ue=>ue.bytes>0).map((ue,Et)=>i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:`w-3 h-3 rounded-full ${rK(ue.key,Et)}`}),i.jsx("span",{className:"text-bambu-gray",children:ue.label}),i.jsx("span",{className:"text-white",children:ue.formatted}),i.jsxs("span",{className:"text-bambu-gray",children:["(",ue.percent_of_total.toFixed(1),"%)"]})]},ue.key))}),i.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[a("settings.storageUsageTotal","Total"),": ",i.jsx("span",{className:"text-white",children:ye.total_formatted}),ye.scan_errors>0&&i.jsxs("span",{className:"ml-2 text-amber-400",children:[a("settings.storageUsageErrors","Scan errors"),": ",ye.scan_errors]})]}),ye.other_breakdown?.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("settings.storageUsageOtherBreakdown","Other breakdown")}),i.jsx("div",{className:"space-y-2",children:ye.other_breakdown.map(ue=>i.jsxs("div",{className:"flex items-center justify-between text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white",children:ue.label}),i.jsx("span",{className:`px-2 py-0.5 rounded-full border ${ue.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:ue.kind==="system"?a("settings.storageUsageSystem","System"):a("settings.storageUsageData","Data")})]}),i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx("span",{className:"text-white",children:ue.formatted}),i.jsxs("span",{children:["(",ue.percent_of_total.toFixed(1),"%)"]})]})]},`${ue.bucket}-${ue.kind}`))})]})]}):i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Backup & Restore"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>oe("backup"),children:[i.jsx(Ec,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),ce==="network"&&C&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ph,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),i.jsx("input",{type:"text",value:C.external_url??"",onChange:ue=>Ht("external_url",ue.target.value),placeholder:"http://192.168.1.100:8000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ar,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableRetry")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ftp_retry_enabled??!0,onChange:ue=>Ht("ftp_retry_enabled",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.ftp_retry_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_count??3,onChange:ue=>Ht("ftp_retry_count",parseInt(ue.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(ue=>i.jsxs("option",{value:ue,children:[ue," ",ue===1?"time":"times"]},ue))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_delay??2,onChange:ue=>Ht("ftp_retry_delay",parseInt(ue.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(ue=>i.jsxs("option",{value:ue,children:[ue," ",ue===1?"second":"seconds"]},ue))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_timeout??30,onChange:ue=>Ht("ftp_timeout",parseInt(ue.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(ue=>i.jsxs("option",{value:ue,children:[ue," seconds"]},ue))}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(d0,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),C.ha_enabled&&Qn&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Qn.success?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${Qn.success?"text-green-400":"text-red-400"}`,children:Qn.success?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white",children:a("settings.enableHomeAssistant")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.homeAssistantDescription")}),C.ha_env_managed&&i.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[i.jsx(zm,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:a("settings.autoEnabledViaEnv")})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ha_enabled??!1,onChange:ue=>Ht("ha_enabled",ue.target.checked),disabled:C.ha_env_managed,className:"sr-only peer"}),i.jsx("div",{className:`w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green ${C.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),C.ha_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",C.ha_url_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",value:C.ha_url??"",onChange:ue=>Ht("ha_url",ue.target.value),placeholder:"http://192.168.1.100:8123",disabled:C.ha_url_from_env,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${C.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_url_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_url_from_env&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.urlFromEnvReadOnly")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",C.ha_token_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"password",value:C.ha_token??"",onChange:ue=>Ht("ha_token",ue.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:C.ha_token_from_env,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${C.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_token_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_token_from_env?i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.tokenFromEnvReadOnly")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),C.ha_url&&C.ha_token&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:En,onClick:async()=>{dr(!0),tr(null);try{const ue=await ne.testHAConnection(C.ha_url,C.ha_token);tr(ue)}catch(ue){tr({success:!1,message:null,error:ue instanceof Error?ue.message:a("common.unknownError")})}finally{dr(!1)}},children:[En?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Wg,{className:"w-4 h-4"}),a("settings.testConnection")]})})]})]})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Wg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),sr?.enabled&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${sr.connected?"text-green-400":"text-red-400"}`,children:sr.connected?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMqtt")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_enabled??!1,onChange:ue=>Ht("mqtt_enabled",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.mqtt_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),i.jsx("input",{type:"text",value:C.mqtt_broker??"",onChange:ue=>Ht("mqtt_broker",ue.target.value),placeholder:"mqtt.example.com or 192.168.1.100",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-end gap-4",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),i.jsx("input",{type:"number",min:"1",max:"65535",value:C.mqtt_port??1883,onChange:ue=>Ht("mqtt_port",Math.min(65535,Math.max(1,parseInt(ue.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_use_tls??!1,onChange:ue=>{const Et=ue.target.checked;Ht("mqtt_use_tls",Et);const sa=C.mqtt_port??1883;Et&&sa===1883?Ht("mqtt_port",8883):!Et&&sa===8883&&Ht("mqtt_port",1883)},className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]}),i.jsx("span",{className:"text-white text-sm",children:a("settings.useTls")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),i.jsx("input",{type:"text",value:C.mqtt_username??"",onChange:ue=>Ht("mqtt_username",ue.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),i.jsx("input",{type:"password",value:C.mqtt_password??"",onChange:ue=>Ht("mqtt_password",ue.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),i.jsx("input",{type:"text",value:C.mqtt_topic_prefix??"bambuddy",onChange:ue=>Ht("mqtt_topic_prefix",ue.target.value),placeholder:"bambuddy",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",C.mqtt_topic_prefix||"bambuddy","/printers/<serial>/status, etc."]})]}),sr&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("span",{className:`w-2 h-2 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:"text-bambu-gray",children:sr.connected?i.jsxs(i.Fragment,{children:[a("settings.mqttConnectedTo")," ",i.jsxs("span",{className:"text-white",children:[sr.broker,":",sr.port]})]}):a("settings.spoolmanDisconnected")})]})})]})]})]})]}),i.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(c3,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMetricsEndpoint")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.prometheusDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.prometheus_enabled??!1,onChange:ue=>Ht("prometheus_enabled",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.prometheus_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),i.jsx("input",{type:"password",value:C.prometheus_token??"",onChange:ue=>Ht("prometheus_token",ue.target.value),placeholder:a("settings.leaveEmptyForNoAuth"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer <token>"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm text-white mb-2",children:a("settings.availableMetrics")}),i.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),i.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),Qn&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Qn.success?i.jsx(pr,{className:"w-8 h-8 text-green-400"}):i.jsx(mi,{className:"w-8 h-8 text-red-400"}),i.jsx("h3",{className:"text-lg font-medium text-white",children:Qn.success?"Connection Successful":"Connection Failed"})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:Qn.success?Qn.message||"Successfully connected to Home Assistant.":Qn.error||"Failed to connect to Home Assistant."}),i.jsx("div",{className:"flex justify-end",children:i.jsx(Ce,{variant:"primary",onClick:()=>tr(null),children:"OK"})})]})}),ce==="plugs"&&i.jsxs("div",{className:"max-w-4xl",children:[i.jsxs("div",{className:"flex items-start justify-between mb-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Te&&Te.filter(ue=>ue.enabled).length>1&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>le("on"),disabled:qa.isPending,title:a("settings.turnAllPlugsOn"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(md,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>le("off"),disabled:qa.isPending,title:a("settings.turnAllPlugsOff"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(QC,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),i.jsxs(Ce,{className:"whitespace-nowrap",onClick:()=>{L(null),E(!0)},children:[i.jsx(Gn,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Te&&Te.length>0&&i.jsxs(wt,{className:"mb-6",children:[i.jsx(zn,{children:i.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[i.jsx(nd,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",at&&i.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),i.jsx(_t,{children:pt?i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(nd,{className:"w-3 h-3"}),"Current Power"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalPower.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[pt.reachableCount,"/",pt.totalPlugs," plugs online"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(ra,{className:"w-3 h-3"}),"Today"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalToday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalToday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(c3,{className:"w-3 h-3"}),"Yesterday"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalYesterday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalYesterday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(n3,{className:"w-3 h-3"}),"Total"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalLifetime.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalLifetime*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]})]}):at?null:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),lt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Te&&Te.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Te.map(ue=>i.jsx(dZe,{plug:ue,onEdit:Et=>{L(Et),E(!0)}},ue.id))}):i.jsx(wt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(fl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.noSmartPlugsTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.noSmartPlugsDescription")}),i.jsxs(Ce,{onClick:()=>{L(null),E(!0)},children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.addFirstSmartPlug")]})]})})})]}),ce==="notifications"&&i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(qg,{className:"w-5 h-5 text-bambu-green"}),a("settings.providers")]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[i.jsx(db,{className:"w-4 h-4"}),a("settings.log")]}),Tt&&Tt.length>0&&i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>{mr(null),ho.mutate()},disabled:ho.isPending,children:[ho.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ZC,{className:"w-4 h-4"}),a("settings.testAll")]}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),D(!0)},children:[i.jsx(Gn,{className:"w-4 h-4"}),"Add"]})]})]}),i.jsx(wt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.notificationLanguage")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.notificationLanguageDescription")})]}),i.jsx("select",{value:C.notification_language||"en",onChange:ue=>Ht("notification_language",ue.target.value),className:"px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:bB.map(ue=>i.jsx("option",{value:ue.code,children:ue.nativeName},ue.code))})]})})}),i.jsx(wt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.bedCooledThreshold")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.bedCooledThresholdDescription")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:20,max:80,step:1,value:C.bed_cooled_threshold??35,onChange:ue=>Ht("bed_cooled_threshold",Number(ue.target.value)),className:"w-16 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm text-center focus:outline-none focus:ring-1 focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),Qr&&i.jsx(wt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm font-medium text-white",children:a("settings.testResults")}),i.jsx("button",{onClick:()=>mr(null),className:"text-bambu-gray hover:text-white text-xs",children:a("common.dismiss")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[i.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[i.jsx(pr,{className:"w-4 h-4"}),a("settings.testPassedCount",{count:Qr.success})]}),Qr.failed>0&&i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(mi,{className:"w-4 h-4"}),a("settings.testFailedCount",{count:Qr.failed})]})]}),Qr.results.filter(ue=>!ue.success).length>0&&i.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Qr.results.filter(ue=>!ue.success).map(ue=>i.jsxs("div",{className:"text-xs text-red-400",children:[i.jsxs("span",{className:"font-medium",children:[ue.provider_name,":"]})," ",ue.message]},ue.provider_id))})]})}),$t?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Tt&&Tt.length>0?i.jsx("div",{className:"space-y-3",children:Tt.map(ue=>i.jsx(fZe,{provider:ue,onEdit:Et=>{G(Et),D(!0)}},ue.id))}):i.jsx(wt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(qg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:a("settings.noProvidersTitle")}),i.jsx("p",{className:"text-xs mb-3",children:a("settings.noProvidersDescription")}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),D(!0)},children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.addProvider")]})]})})})]}),i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),a("settings.messageTemplates")]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:a("settings.messageTemplatesDescription")}),Dn?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):kn&&kn.length>0?i.jsx("div",{className:"space-y-2",children:[...kn].sort((ue,Et)=>ue.name.localeCompare(Et.name)).map(ue=>i.jsx(wt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>W(ue),children:i.jsx(_t,{className:"py-2.5 px-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium text-sm truncate",children:ue.name}),i.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ue.title_template})]}),i.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:Et=>{Et.stopPropagation(),W(ue)},children:i.jsx(ef,{className:"w-4 h-4 text-bambu-gray"})})]})})},ue.id))}):i.jsx(wt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(Ms,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm",children:a("settings.noTemplatesAvailable")})]})})})]})]}),ce==="apikeys"&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiKeys")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiKeysDescription")})]}),i.jsxs(Ce,{size:"sm",onClick:()=>ie(!0),className:"flex-shrink-0",children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.createKey")]})]}),Q&&i.jsx(wt,{className:"mb-6 border-bambu-green",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:a("settings.apiKeyCreated")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:a("settings.apiKeyCopyWarning")}),i.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[i.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:Q}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(Q);else{const ue=document.createElement("textarea");ue.value=Q,ue.style.position="fixed",ue.style.left="-999999px",document.body.appendChild(ue),ue.select(),document.execCommand("copy"),document.body.removeChild(ue)}o(a("settings.toast.keyCopied"))}catch{o(a("settings.toast.copyFailed"),"error")}},children:i.jsx(Yl,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex gap-2 mt-3",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>{be(Q),o(a("settings.toast.keyAddedToBrowser"))},children:a("settings.useInApiBrowser")}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>se(null),children:a("common.dismiss")})]})]})]})})}),_e&&i.jsxs(wt,{className:"mb-6",children:[i.jsx(zn,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.createNewApiKey")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keyName")}),i.jsx("input",{type:"text",value:ze,onChange:ue=>V(ue.target.value),placeholder:a("settings.keyNamePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("common.permissions")}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Y.can_read_status,onChange:ue=>me(Et=>({...Et,can_read_status:ue.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.readStatus")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.readStatusDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Y.can_queue,onChange:ue=>me(Et=>({...Et,can_queue:ue.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.manageQueue")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.manageQueueDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Y.can_control_printer,onChange:ue=>me(Et=>({...Et,can_control_printer:ue.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.controlPrinter")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.controlPrinterDescription")})]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[i.jsxs(Ce,{onClick:()=>sn.mutate({name:ze||a("settings.unnamedKey"),...Y}),disabled:sn.isPending,children:[sn.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Gn,{className:"w-4 h-4"}),a("settings.createKey")]}),i.jsx(Ce,{variant:"secondary",onClick:()=>ie(!1),children:a("common.cancel")})]})]})]}),Pt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Rt&&Rt.length>0?i.jsx("div",{className:"space-y-3",children:Rt.map(ue=>i.jsx(wt,{children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(nl,{className:`w-5 h-5 ${ue.enabled?"text-bambu-green":"text-bambu-gray"}`}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:ue.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[ue.key_prefix,"••••••••",ue.last_used&&` · ${a("settings.lastUsed")}: ${mb(ue.last_used)}`]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex gap-1 text-xs",children:[ue.can_read_status&&i.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:a("settings.read")}),ue.can_queue&&i.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:a("queue.title")}),ue.can_control_printer&&i.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:a("settings.control")})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Le(ue.id),children:i.jsx(Jt,{className:"w-4 h-4 text-red-400"})})]})]})})},ue.id))}):i.jsx(wt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(nl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.apiKeysEmptyTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.apiKeysEmptyDescription")}),i.jsxs(Ce,{onClick:()=>ie(!0),children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.createFirstKey")]})]})})}),i.jsxs(wt,{className:"mt-6",children:[i.jsx(zn,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.webhookEndpoints")})}),i.jsxs(_t,{className:"space-y-3 text-sm",children:[i.jsx("p",{className:"text-bambu-gray",children:a("settings.webhookApiKeyHint")}),i.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getAllStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getSpecificStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-green-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.addToQueue")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.pausePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.resumePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-red-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.stopPrint")]})]})]})]})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ph,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiBrowser")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiBrowserDescription")})]}),i.jsx(wt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("settings.apiKeyForTesting")}),i.jsx("input",{type:"text",value:Ne,onChange:ue=>be(ue.target.value),placeholder:a("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:a("settings.apiKeyHint")})]})}),i.jsx(IZe,{apiKey:Ne})]})]}),ce==="virtual-printer"&&i.jsx(MZe,{}),ce==="filament"&&C&&i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"lg:w-1/3 space-y-6",children:[i.jsx(SZe,{}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.amsDisplayThresholds")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.amsThresholdsDescription")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(CF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"font-medium",children:a("settings.humidity")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodGreen")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_good??40,onChange:ue=>Ht("ams_humidity_good",parseInt(ue.target.value)||40),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_fair??60,onChange:ue=>Ht("ams_humidity_fair",parseInt(ue.target.value)||60),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairBad")})]}),i.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(JC,{className:"w-4 h-4 text-orange-400"}),i.jsx("span",{className:"font-medium",children:a("settings.temperature")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodBlue")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_good??28,onChange:ue=>Ht("ams_temp_good",parseFloat(ue.target.value)||28),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_fair??35,onChange:ue=>Ht("ams_temp_fair",parseFloat(ue.target.value)||35),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairHot")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(Ec,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"font-medium",children:a("settings.historyRetention")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keepSensorHistory")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"1",max:"365",value:C.ams_history_retention_days??30,onChange:ue=>Ht("ams_history_retention_days",parseInt(ue.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:a("common.days")})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.historyRetentionDescription")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(gr,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"font-medium",children:a("settings.printModal")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-white",children:a("settings.expandCustomMapping")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:a("settings.expandCustomMappingDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.per_printer_mapping_expanded??!1,onChange:ue=>Ht("per_printer_mapping_expanded",ue.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})]})]})]})]}),i.jsxs("div",{className:"lg:w-2/3 space-y-6",children:[i.jsx(_Ze,{}),i.jsx(NZe,{})]})]})}),de!==null&&i.jsx(gn,{title:a("settings.deleteApiKeyTitle"),message:a("settings.deleteApiKeyMessage"),confirmText:a("settings.deleteKey"),variant:"danger",onConfirm:()=>{Zt.mutate(de),Le(null)},onCancel:()=>Le(null)}),P&&i.jsx(hZe,{plug:U,onClose:()=>{E(!1),L(null)}}),B&&i.jsx(pZe,{provider:$,onClose:()=>{D(!1),G(null)}}),z&&i.jsx(gZe,{template:z,onClose:()=>W(null)}),X&&i.jsx(yZe,{onClose:()=>ae(!1)}),O&&i.jsx(gn,{title:a("settings.clearNotificationLogs"),message:a("settings.clearLogsMessage"),confirmText:a("settings.clearLogs"),variant:"warning",onConfirm:async()=>{R(!1);try{const ue=await ne.clearNotificationLogs(30);o(ue.message,"success")}catch{o(a("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>R(!1)}),q&&i.jsx(gn,{title:a("settings.resetUiPreferences"),message:a("settings.resetUiPreferencesMessage"),confirmText:a("settings.resetPreferences"),variant:"default",onConfirm:()=>{J(!1),localStorage.clear(),o(a("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>J(!1)}),fe&&i.jsx(gn,{title:`Turn All Plugs ${fe==="on"?"On":"Off"}`,message:`This will turn ${fe==="on"?"ON":"OFF"} all ${Te?.filter(ue=>ue.enabled).length||0} enabled smart plugs. ${fe==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${fe==="on"?"On":"Off"}`,variant:fe==="off"?"danger":"warning",onConfirm:()=>{const ue=fe;le(null),qa.mutate(ue)},onCancel:()=>le(null)}),Be&&pn?.release_notes&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ie(!1),children:i.jsxs(wt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ue=>ue.stopPropagation(),children:[i.jsxs(zn,{className:"flex flex-row items-center justify-between shrink-0",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray",children:pn.release_name})]}),i.jsx("button",{onClick:()=>Ie(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx(_t,{className:"overflow-y-auto flex-1",children:i.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:pn.release_notes})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:i.jsxs(Ce,{variant:"secondary",className:"w-full",children:[i.jsx(Xr,{className:"w-4 h-4"}),"View on GitHub"]})}),i.jsx(Ce,{onClick:()=>Ie(!1),className:"flex-1",children:"Close"})]})]})}),ce==="users"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>he("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(mh,{className:"w-4 h-4"}),a("settings.tabs.users")]}),i.jsxs("button",{onClick:()=>he("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(bv,{className:"w-4 h-4"}),a("settings.tabs.emailAuth")||"Email Authentication",Ft?.advanced_auth_enabled&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]})]}),je==="users"&&i.jsxs(i.Fragment,{children:[i.jsx(wt,{children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?i.jsx(zm,{className:"w-5 h-5 text-green-400"}):i.jsx(H_,{className:"w-5 h-5 text-gray-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.authentication")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&i.jsxs(Ce,{variant:"secondary",onClick:()=>Oe(!0),children:[i.jsx(H_,{className:"w-4 h-4"}),a("common.disable")]}):i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("common.enable")]})]})})}),Ft?.advanced_auth_enabled&&i.jsx(wt,{className:"border-blue-500/30 bg-blue-500/5",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:i.jsx(bv,{className:"w-5 h-5 text-blue-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.email.advancedAuthEnabled")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[c&&i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(mh,{className:"w-5 h-5 text-bambu-green"}),a("settings.currentUser")]}),i.jsxs(Ce,{size:"sm",variant:"ghost",onClick:()=>xe(!0),children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.changePassword")]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),c.groups?.map(ue=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ue.name==="Administrators"?"bg-purple-500/20 text-purple-300":ue.name==="Operators"?"bg-blue-500/20 text-blue-300":ue.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ue.name},ue.id))]})]})})})]}),i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(mh,{className:"w-5 h-5 text-bambu-green"}),a("settings.users")]}),bn("users:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>{We(!0),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.addUser")]})]})}),i.jsx(_t,{children:Zn?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Nt.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noUsersFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Nt.map(ue=>i.jsxs("div",{className:"py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ue.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ue.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),ue.groups?.map(Et=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${Et.name==="Administrators"?"bg-purple-500/20 text-purple-300":Et.name==="Operators"?"bg-blue-500/20 text-blue-300":Et.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:Et.name},Et.id))]})]}),i.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[bn("users:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>rs(ue),children:i.jsx(ef,{className:"w-4 h-4"})}),bn("users:delete")&&ue.id!==c?.id&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>Ss(ue.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},ue.id))})})]})]}),i.jsx("div",{children:i.jsxs(wt,{children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(l3,{className:"w-5 h-5 text-bambu-green"}),a("settings.groups")]}),bn("groups:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>e("/groups/new"),children:[i.jsx(Gn,{className:"w-4 h-4"}),a("settings.addGroup")]})]})}),i.jsx(_t,{children:hr?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):wr.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noGroupsFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:wr.map(ue=>i.jsxs("div",{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(l3,{className:`w-4 h-4 ${ue.name==="Administrators"?"text-purple-400":ue.name==="Operators"?"text-blue-400":ue.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),i.jsx("span",{className:"text-white font-medium",children:ue.name}),ue.is_system&&i.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:a("settings.system")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[bn("groups:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${ue.id}/edit`),children:i.jsx(ef,{className:"w-4 h-4"})}),bn("groups:delete")&&!ue.is_system&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>vr(ue.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ue.description||a("settings.noDescription")}),i.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[i.jsx("span",{children:a("settings.userCount",{count:ue.user_count})}),i.jsx("span",{children:a("settings.permissionCount",{count:ue.permissions.length})})]})]},ue.id))})})]})})]}),!l&&i.jsx(wt,{children:i.jsx(_t,{className:"py-6",children:i.jsxs("div",{className:"text-center",children:[i.jsx(H_,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:a("settings.authDisabledTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:a("settings.authDisabledMessage")}),i.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature1")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature2")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature3")})]})]}),i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("settings.enableAuthentication")]})]})})})]}),je==="email"&&i.jsx("div",{className:"max-w-2xl",children:i.jsx(RZe,{})})]}),De&&!Ft?.advanced_auth_enabled&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{We(!1),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(wt,{className:"w-full max-w-md",onClick:ue=>ue.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.createUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{We(!1),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.username")}),i.jsx("input",{type:"text",value:yt.username,onChange:ue=>Gt({...yt,username:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.password")}),i.jsx("input",{type:"password",value:yt.password,onChange:ue=>Gt({...yt,password:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:yt.confirmPassword,onChange:ue=>Gt({...yt,confirmPassword:ue.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${yt.confirmPassword&&yt.password!==yt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),yt.confirmPassword&&yt.password!==yt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),i.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[wr.map(ue=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:yt.group_ids.includes(ue.id),onChange:()=>oi(ue.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ue.name}),ue.is_system&&i.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},ue.id)),wr.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.noGroupsAvailable")})]})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{We(!1),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),i.jsx(Ce,{onClick:ns,disabled:wa.isPending||!yt.username||!yt.password||yt.password!==yt.confirmPassword||yt.password.length<6,children:wa.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Gn,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),De&&Ft?.advanced_auth_enabled&&i.jsx(wZe,{formData:yt,setFormData:Gt,groups:wr,onClose:()=>{We(!1),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:ns,isCreating:wa.isPending,isCreateButtonDisabled:wa.isPending||!yt.username||!yt.email}),Ae&&$e!==null&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Re(!1),ht(null),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(wt,{className:"w-full max-w-md",onClick:ue=>ue.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ef,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.editUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Re(!1),ht(null),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("settings.username")," ",Ft?.advanced_auth_enabled&&i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",value:yt.username,onChange:ue=>Gt({...yt,username:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.email")||"Email"," ",Ft?.advanced_auth_enabled?i.jsx("span",{className:"text-red-400",children:"*"}):i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.optional")||"optional",")"]})]}),i.jsx("input",{type:"email",value:yt.email,onChange:ue=>Gt({...yt,email:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("users.form.emailPlaceholder")||"user@example.com",required:Ft?.advanced_auth_enabled})]}),!Ft?.advanced_auth_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.password")||"Password"," ",i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),i.jsx("input",{type:"password",value:yt.password,onChange:ue=>Gt({...yt,password:ue.target.value,confirmPassword:""}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),yt.password&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:yt.confirmPassword,onChange:ue=>Gt({...yt,confirmPassword:ue.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${yt.confirmPassword&&yt.password!==yt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),yt.confirmPassword&&yt.password!==yt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),Ft?.advanced_auth_enabled&&i.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>$e&&xn.mutate($e),disabled:xn.isPending||!yt.email,className:"w-full",children:xn.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.form.resettingPassword")||"Resetting Password..."]}):i.jsxs(i.Fragment,{children:[i.jsx(so,{className:"w-4 h-4"}),a("users.form.resetPassword")||"Reset Password"]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("users.form.groups")||"Groups"}),i.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:wr.map(ue=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:yt.group_ids.includes(ue.id),onChange:()=>oi(ue.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ue.name}),ue.is_system&&i.jsxs("span",{className:"text-xs text-yellow-400",children:["(",a("users.system")||"System",")"]})]},ue.id))})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Re(!1),ht(null),Gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a("users.modal.cancel")||"Cancel"}),i.jsx(Ce,{onClick:()=>Tl($e),disabled:Va.isPending||!yt.username||Ft?.advanced_auth_enabled&&!yt.email||!!(!Ft?.advanced_auth_enabled&&yt.password&&(yt.password!==yt.confirmPassword||yt.password.length<6)),children:Va.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.modal.saving")||"Saving..."]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),a("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),At!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Dt(null),kt(null)},children:i.jsxs(wt,{className:"w-full max-w-md",onClick:ue=>ue.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[i.jsx(Jt,{className:"w-5 h-5"}),i.jsx("h3",{className:"text-lg font-semibold",children:a("settings.deleteUserTitle")})]})}),i.jsx(_t,{className:"space-y-4",children:Ue?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):It&&It.archives+It.queue_items+It.library_files>0?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.userHasCreated")}),i.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[It.archives>0&&i.jsxs("li",{children:[It.archives," archive",It.archives!==1?"s":""]}),It.queue_items>0&&i.jsxs("li",{children:[It.queue_items," queue item",It.queue_items!==1?"s":""]}),It.library_files>0&&i.jsxs("li",{children:[It.library_files," library file",It.library_files!==1?"s":""]})]}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.userItemsQuestion")}),i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(Ce,{variant:"danger",onClick:()=>Vt.mutate({id:At,deleteItems:!0}),disabled:Vt.isPending,className:"justify-center",children:"Delete user AND their items"}),i.jsx(Ce,{variant:"secondary",onClick:()=>Vt.mutate({id:At,deleteItems:!1}),disabled:Vt.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),i.jsx(Ce,{variant:"ghost",onClick:()=>{Dt(null),kt(null)},disabled:Vt.isPending,className:"justify-center",children:"Cancel"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.deleteUserConfirm")}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.actionCannotBeUndone")}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Ce,{variant:"ghost",onClick:()=>{Dt(null),kt(null)},disabled:Vt.isPending,children:"Cancel"}),i.jsx(Ce,{variant:"danger",onClick:()=>Vt.mutate({id:At,deleteItems:!1}),disabled:Vt.isPending,children:"Delete User"})]})]})})]})}),Cn!==null&&i.jsx(gn,{title:a("settings.deleteGroupTitle"),message:a("settings.deleteGroupMessage"),confirmText:a("settings.deleteGroup"),variant:"danger",onConfirm:()=>{Ci.mutate(Cn),vr(null)},onCancel:()=>vr(null)}),ce==="backup"&&i.jsx(EZe,{}),Ke&&i.jsx(gn,{title:a("settings.disableAuthenticationTitle"),message:a("settings.disableAuthenticationMessage"),confirmText:a("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ne.disableAuth(),o(a("settings.toast.authDisabled"),"success"),await u(),Oe(!1),window.location.href="/"}catch(ue){const Et=ue instanceof Error?ue.message:a("settings.toast.authDisableFailed");o(Et,"error")}},onCancel:()=>Oe(!1)}),pe&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{xe(!1),ge({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsxs(wt,{className:"w-full max-w-md",onClick:ue=>ue.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.changePassword")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{xe(!1),ge({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),i.jsx("input",{type:"password",value:ke.currentPassword,onChange:ue=>ge({...ke,currentPassword:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),i.jsx("input",{type:"password",value:ke.newPassword,onChange:ue=>ge({...ke,newPassword:ue.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:a("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),i.jsx("input",{type:"password",value:ke.confirmPassword,onChange:ue=>ge({...ke,confirmPassword:ue.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${ke.confirmPassword&&ke.newPassword!==ke.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),ke.confirmPassword&&ke.newPassword!==ke.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{xe(!1),ge({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),i.jsx(Ce,{onClick:async()=>{if(ke.newPassword!==ke.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(ke.newPassword.length<6){o(a("settings.toast.passwordTooShort"),"error");return}qe(!0);try{await ne.changePassword(ke.currentPassword,ke.newPassword),o(a("settings.toast.passwordChanged"),"success"),xe(!1),ge({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ue){const Et=ue instanceof Error?ue.message:"Failed to change password";o(Et,"error")}finally{qe(!1)}},disabled:we||!ke.currentPassword||!ke.newPassword||ke.newPassword!==ke.confirmPassword||ke.newPassword.length<6,children:we?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(nl,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const qie=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},HZe=t=>t.startsWith("HH")?"HF":"S",$Ze=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Gie=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function T2({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:a,onToggleSelect:s,note:o}){const l=HZe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return i.jsxs("div",{className:"flex items-center gap-2",children:[r&&i.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:a?i.jsx(oo,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4"})}),i.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${a?"ring-1 ring-bambu-green":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:qie(t.k_value)}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&i.jsx("span",{title:"Has note",children:i.jsx(SX,{className:"w-3 h-3 text-yellow-500"})}),i.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&i.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function M2({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:a=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:u,onSaveNote:d,hasPermission:h}){const{t:f}=Ot(),{showToast:p}=an(),[x,v]=w.useState(t?.name||""),[g,y]=w.useState(t?.k_value?qie(t.k_value):"0.020"),[_,N]=w.useState(t?.filament_id||""),[k,A]=w.useState(t?.nozzle_id?$Ze(t.nozzle_id):"HH00"),[M,C]=w.useState(t?.nozzle_diameter||n),[j,P]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[E,U]=w.useState(!1),[L,B]=w.useState({current:0,total:0}),[D,$]=w.useState(o),G=Hr.useMemo(()=>{const te=new Map;for(const ve of a)te.set(ve.filament_id,ve.name);const Z=new Map;for(const ve of r)if(ve.filament_id&&!Z.has(ve.filament_id)){const ee=te.get(ve.filament_id)||Gie(ve.name||"");Z.set(ve.filament_id,{id:ve.filament_id,name:ee||ve.filament_id})}return Array.from(Z.values()).sort((ve,ce)=>ve.name.localeCompare(ce.name))},[r,a]),z=st({mutationFn:te=>(console.log("[KProfile] Calling API..."),ne.setKProfile(e,te)),onSuccess:te=>{if(console.log("[KProfile] Save success:",te),p(f("kProfiles.toast.profileSaved")),d&&D!==o){let Z;D===""&&l?Z=l:t&&t.slot_id>0?Z=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:Z=`name_${x}_${_}`,d(Z,D)}U(!0),setTimeout(()=>{U(!1),u()},2500)},onError:te=>{console.error("[KProfile] Save error:",te),p(te.message,"error"),U(!1)}}),W=st({mutationFn:te=>(console.log("[KProfile] Deleting profile..."),ne.deleteKProfile(e,te)),onSuccess:te=>{console.log("[KProfile] Delete success:",te),p(f("kProfiles.toast.profileDeleted")),U(!0),setTimeout(()=>{U(!1),c()},4e3)},onError:te=>{console.error("[KProfile] Delete error:",te),p(te.message,"error"),U(!1)}}),[X,ae]=w.useState(!1),H=()=>{t&&W.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},K=async te=>{if(te.preventDefault(),s&&!t&&j.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const Z=parseFloat(g).toFixed(6),ve=`${k}-${M}`;if(t||j.length===1){const ee={name:x,k_value:Z,filament_id:_,nozzle_id:ve,nozzle_diameter:M,extruder_id:t?t.extruder_id:j[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",ee),z.mutate(ee);return}U(!0),B({current:1,total:j.length});const ce=j.map(ee=>({name:x,k_value:Z,filament_id:_,nozzle_id:ve,nozzle_diameter:M,extruder_id:ee,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${ce.length} profiles in batch:`,ce);try{if(await ne.setKProfilesBatch(e,ce),p(f("kProfiles.toast.profilesSaved",{count:j.length})),d&&D){const ee=`name_${x}_${_}`;d(ee,D)}}catch(ee){console.error("[KProfile] Failed to save batch:",ee),p(f("kProfiles.toast.failedToSaveBatch"),"error"),U(!1),B({current:0,total:0});return}B({current:j.length,total:j.length}),setTimeout(()=>{U(!1),B({current:0,total:0}),u()},3e3)};return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[i.jsxs(wt,{className:"w-full max-w-md relative",children:[E&&i.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:L.total>1?f("kProfiles.modal.savingExtruder",{current:L.current,total:L.total}):f("kProfiles.modal.syncing")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),i.jsxs(_t,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),i.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:E,children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:K,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),i.jsx("input",{type:"text",value:x,onChange:te=>v(te.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:f("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),i.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:te=>{const Z=te.target.value;(Z===""||/^\d*\.?\d*$/.test(Z))&&y(Z)},onBlur:te=>{const Z=parseFloat(te.target.value);isNaN(Z)||y((Math.trunc(Z*1e3)/1e3).toFixed(3))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono",placeholder:f("kProfiles.modal.kValuePlaceholder"),required:!0}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),i.jsxs("select",{value:_,onChange:te=>{const Z=te.target.value;if(N(Z),!t&&Z&&!x){const ve=G.find(ce=>ce.id===Z);ve&&v(`${k==="HH00"?"HF":"S"} ${ve.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[i.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&i.jsx("option",{value:t.filament_id,children:G.find(te=>te.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&G.map(te=>i.jsx("option",{value:te.id,children:te.name},te.id))]}),!t&&G.length===0&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),i.jsxs("select",{value:k,onChange:te=>{const Z=te.target.value;if(A(Z),!t&&_&&!x){const ve=G.find(ce=>ce.id===_);ve&&v(`${Z==="HS00"?"HF":"S"} ${ve.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),i.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),i.jsxs("select",{value:M,onChange:te=>C(te.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?i.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?f("kProfiles.modal.left"):f("kProfiles.modal.right")}):i.jsxs("div",{className:"flex gap-4",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(1),onChange:te=>{te.target.checked?P([...j,1]):P(j.filter(Z=>Z!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(0),onChange:te=>{te.target.checked?P([...j,0]):P(j.filter(Z=>Z!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),i.jsx("textarea",{value:D,onChange:te=>$(te.target.value),placeholder:f("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none resize-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),i.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>ae(!0),disabled:W.isPending||E||!h("kprofiles:delete"),title:h("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:W.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"})}),i.jsx(Ce,{type:"button",variant:"secondary",onClick:c,disabled:E,className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{type:"submit",disabled:z.isPending||E||!h(t?"kprofiles:update":"kprofiles:create"),title:h(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[z.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(GC,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),X&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:i.jsx(wt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>ae(!1),className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{onClick:()=>{ae(!1),H()},disabled:W.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[W.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const z_={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function VZe(){const{t}=Ot(),{showToast:e}=an(),{hasPermission:n}=Ir(),[r,a]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(z_.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState(()=>localStorage.getItem(z_.SORT_OPTION)||"name"),[A,M]=w.useState(!1),[C,j]=w.useState(new Set),[P,E]=w.useState(!1),[U,L]=w.useState(!1),B=w.useCallback(R=>`${R.slot_id}_${R.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(z_.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(z_.SORT_OPTION,N)},[N]);const{data:D,isLoading:$}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:G,isLoading:z,isFetching:W,error:X,refetch:ae}=Je({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const R=await ne.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",R?.profiles?.length||0,"profiles"),R},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:H}=Je({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ne.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:K}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),staleTime:3e5}),{data:te}=Je({queryKey:["filamentIdMap"],queryFn:()=>ne.getFilamentIdMap(),staleTime:3e5}),{data:Z,refetch:ve}=Je({queryKey:["kprofile-notes",r],queryFn:()=>ne.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),ce=X?.message?.includes("not connected");w.useEffect(()=>{if(!r&&D&&D.length>0){const R=D.find(q=>q.is_active);R&&a(R.id)}},[r,D]),w.useEffect(()=>{if(r){const R=setTimeout(()=>{ae()},150);return()=>clearTimeout(R)}},[r,s]);const ee=D?.filter(R=>R.is_active)||[],je=Hr.useMemo(()=>{const R=new Map;if(K)for(const q of K)R.set(q.filament_id,q.name);if(te)for(const[q,J]of Object.entries(te))R.has(q)||R.set(q,J);return R},[K,te]),he=Hr.useMemo(()=>Array.from(je.entries()).map(([R,q])=>({filament_id:R,name:q})),[je]),oe=Hr.useCallback(R=>je.get(R.filament_id)||Gie(R.name),[je]),_e=Hr.useMemo(()=>G?.profiles?G.profiles.filter(q=>{const J=p.toLowerCase(),fe=!J||q.name.toLowerCase().includes(J)||q.filament_id.toLowerCase().includes(J),le=v==="all"||v==="left"&&q.extruder_id===1||v==="right"&&q.extruder_id===0,Be=y==="all"||y==="hf"&&q.nozzle_id.startsWith("HH")||y==="s"&&q.nozzle_id.startsWith("HS");return fe&&le&&Be}).sort((q,J)=>{switch(N){case"k_value":return parseFloat(q.k_value)-parseFloat(J.k_value);case"filament":return oe(q).localeCompare(oe(J));default:return q.name.localeCompare(J.name)}}):[],[G?.profiles,p,v,y,N,oe]),ie=D?.find(R=>R.id===r),ze=ie?.nozzle_count===2;w.useEffect(()=>{const R=q=>{q.target instanceof HTMLInputElement||q.target instanceof HTMLTextAreaElement||q.target instanceof HTMLSelectElement||l||u||h||(q.key==="r"||q.key==="R"?(q.preventDefault(),ae()):q.key==="n"||q.key==="N"?(q.preventDefault(),d(!0)):q.key==="Escape"&&A&&(q.preventDefault(),M(!1),j(new Set)))};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[l,u,h,A,ae]);const V=w.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const R={version:1,exported_at:new Date().toISOString(),printer:ie?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(le=>({name:le.name,k_value:le.k_value,filament_id:le.filament_id,nozzle_id:le.nozzle_id,nozzle_diameter:le.nozzle_diameter,extruder_id:le.extruder_id}))},q=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),J=URL.createObjectURL(q),fe=document.createElement("a");fe.href=J,fe.download=`kprofiles_${ie?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(fe),fe.click(),document.body.removeChild(fe),URL.revokeObjectURL(J),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,ie,s,e,t]),Y=w.useCallback(()=>{const R=document.createElement("input");R.type="file",R.accept=".json",R.onchange=async q=>{const J=q.target.files?.[0];if(J)try{const fe=await J.text(),le=JSON.parse(fe);if(!le.profiles||!Array.isArray(le.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let Be=0;for(const Ie of le.profiles)if(!(!Ie.name||!Ie.k_value||!Ie.filament_id))try{await ne.setKProfile(r,{name:Ie.name,k_value:parseFloat(Ie.k_value).toFixed(6),filament_id:Ie.filament_id,nozzle_id:Ie.nozzle_id||`HH00-${s}`,nozzle_diameter:Ie.nozzle_diameter||s,extruder_id:Ie.extruder_id??0,slot_id:0}),Be++,await new Promise(Ke=>setTimeout(Ke,500))}catch(Ke){console.error("Failed to import profile:",Ie.name,Ke)}e(t("kProfiles.toast.importedProfiles",{count:Be,total:le.profiles.length})),ae()}catch(fe){console.error("Import error:",fe),e(t("kProfiles.toast.failedToParseImport"),"error")}},R.click()},[r,s,e,ae,t]),me=w.useCallback(R=>{j(q=>{const J=new Set(q);return J.has(R)?J.delete(R):J.add(R),J})},[]),Q=w.useCallback(()=>{j(new Set(_e.map(R=>B(R))))},[_e,B]),se=w.useCallback(()=>{C.size!==0&&E(!0)},[C.size]),de=w.useCallback(async()=>{const R=_e.filter(J=>C.has(B(J)));L(!0);let q=0;for(const J of R)try{await ne.deleteKProfile(r,{slot_id:J.slot_id,extruder_id:J.extruder_id,nozzle_id:J.nozzle_id,nozzle_diameter:J.nozzle_diameter,filament_id:J.filament_id,setting_id:J.setting_id}),q++,await new Promise(fe=>setTimeout(fe,300))}catch(fe){console.error("Failed to delete profile:",J.name,fe)}e(t("kProfiles.toast.profilesDeleted",{count:q})),L(!1),E(!1),M(!1),j(new Set),ae()},[r,C,_e,e,ae,B,t]),Le=w.useCallback(R=>{const q=[];return R.setting_id&&q.push(R.setting_id),q.push(`slot_${R.slot_id}_${R.filament_id}_${R.extruder_id}`),q.push(`name_${R.name}_${R.filament_id}`),q},[]),Ne=w.useCallback(async(R,q)=>{if(r)try{await ne.setKProfileNote(r,R,q),ve()}catch(J){console.error("Failed to save note:",J),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ve,e,t]),be=w.useCallback(R=>{if(!Z?.notes)return{note:"",key:null};const q=Le(R);for(const J of q)if(Z.notes[J])return{note:Z.notes[J],key:J};return{note:"",key:null}},[Z,Le]),O=w.useCallback(R=>be(R).note,[be]);return $?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!D||D.length===0?i.jsx(wt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(Ba,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):ee.length===0?i.jsx(wt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(gr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):i.jsxs(i.Fragment,{children:[W&&!z&&i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[i.jsx(it,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1 min-w-48",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),i.jsx("select",{value:r||"",onChange:R=>a(parseInt(R.target.value)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:ee.map(R=>i.jsx("option",{value:R.id,children:R.name},R.id))})]}),i.jsxs("div",{className:"w-32",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),i.jsxs("select",{value:s,onChange:R=>o(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),i.jsxs("div",{className:"flex items-end gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),disabled:W||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[i.jsx(Ar,{className:`w-4 h-4 ${W?"animate-spin":""}`}),t("kProfiles.refresh")]}),i.jsxs(Ce,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[i.jsx(Gn,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[i.jsxs("div",{className:"flex-1 min-w-48 relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:R=>x(R.target.value),placeholder:t("kProfiles.searchPlaceholder"),className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),ze&&i.jsx("div",{className:"w-36",children:i.jsxs("select",{value:v,onChange:R=>g(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),i.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),i.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:y,onChange:R=>_(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),i.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),i.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:N,onChange:R=>k(R.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"name",children:t("kProfiles.sortName")}),i.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),i.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[i.jsxs(Ce,{variant:"secondary",onClick:V,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[i.jsx(da,{className:"w-4 h-4"}),t("kProfiles.export")]}),i.jsxs(Ce,{variant:"secondary",onClick:Y,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[i.jsx(Ra,{className:"w-4 h-4"}),t("kProfiles.import")]}),i.jsx("div",{className:"flex-1"}),A?i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:Q,children:[i.jsx(oo,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),i.jsxs(Ce,{variant:"secondary",onClick:se,disabled:C.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(Jt,{className:"w-4 h-4"}),t("kProfiles.delete")," (",C.size,")"]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>{M(!1),j(new Set)},children:[i.jsx(Lt,{className:"w-4 h-4"}),t("common.cancel")]})]}):i.jsxs(Ce,{variant:"secondary",onClick:()=>M(!0),disabled:!_e.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(oo,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),z?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):ce?i.jsx(wt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(jf,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),children:[i.jsx(Ar,{className:"w-4 h-4"}),t("common.refresh")]})]})}):_e.length>0?ze?i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(R=>R.extruder_id===1).map(R=>i.jsx(T2,{profile:R,onEdit:()=>c(R),onCopy:()=>f(R),selectionMode:A,isSelected:C.has(B(R)),onToggleSelect:()=>me(B(R)),note:O(R)},B(R)))})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(R=>R.extruder_id===0).map(R=>i.jsx(T2,{profile:R,onEdit:()=>c(R),onCopy:()=>f(R),selectionMode:A,isSelected:C.has(B(R)),onToggleSelect:()=>me(B(R)),note:O(R)},B(R)))})]})]}):i.jsx("div",{className:"space-y-1",children:_e.map(R=>i.jsx(T2,{profile:R,onEdit:()=>c(R),onCopy:()=>f(R),selectionMode:A,isSelected:C.has(B(R)),onToggleSelect:()=>me(B(R)),note:O(R)},B(R)))}):p||v!=="all"||y!=="all"?i.jsx(wt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(xr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):i.jsx(wt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(GC,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),i.jsxs(Ce,{onClick:()=>d(!0),children:[i.jsx(Gn,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:R,key:q}=be(l);return i.jsx(M2,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:H?.profiles||G?.profiles,builtinFilaments:he,isDualNozzle:ze,initialNote:R,initialNoteKey:q,onSaveNote:Ne,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&i.jsx(M2,{printerId:r,nozzleDiameter:s,existingProfiles:H?.profiles||G?.profiles,builtinFilaments:he,isDualNozzle:ze,onSaveNote:Ne,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),h&&r&&i.jsx(M2,{printerId:r,nozzleDiameter:s,existingProfiles:H?.profiles||G?.profiles,builtinFilaments:he,isDualNozzle:ze,onSaveNote:Ne,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{f(null),ae()},onSave:()=>{f(null),ae()}}),P&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:C.size})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>E(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),i.jsxs(Ce,{onClick:de,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Wie=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],qZe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function GZe(t){const e=t.toUpperCase();for(const n of Wie)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function WZe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of Wie){const a=n.indexOf(r);if(a>0){const s=e.slice(0,a).trim();if(s&&s.length>1)return s}}return null}function P2({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:a}=Ot(),{hasPermission:s}=Ir(),o=t.filament_type||GZe(t.name),l=t.filament_vendor||WZe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=qZe[o.toUpperCase()]||null),i.jsx(wt,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:i.jsxs(_t,{className:"p-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&i.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),i.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&i.jsx("span",{className:"text-xs text-bambu-gray",children:l}),i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:a("profiles.localProfiles.badge")})]})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&i.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:a("profiles.localProfiles.delete"),children:i.jsx(Jt,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Pn,{className:"w-3.5 h-3.5"})})]})]}),r&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.filamentType")}),i.jsx("span",{className:"text-white",children:o})]}),l&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.vendor")}),i.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.nozzleTemp")}),i.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.cost")}),i.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.density")}),i.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.pressureAdvance")}),i.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.compatiblePrinters")}),i.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.inheritsFrom")}),i.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.source")}),i.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function KZe(){const{t}=Ot(),{hasPermission:e}=Ir(),n=en(),{showToast:r}=an(),[a,s]=w.useState(""),[o,l]=w.useState(null),[c,u]=w.useState(!1),[d,h]=w.useState(null),{data:f,isLoading:p}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets()}),x=st({mutationFn:async C=>{const j=[];for(const P of Array.from(C)){const E=new FormData;E.append("file",P),j.push(await ne.importLocalPresets(E))}return j},onSuccess:C=>{n.invalidateQueries({queryKey:["localPresets"]});let j=0,P=0,E=0;for(const U of C)j+=U.imported,P+=U.skipped,E+=U.errors.length;j>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:j})),P>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:P}),"warning"),E>0&&r(t("profiles.localProfiles.toast.importError",{count:E}),"error")},onError:C=>{r(C.message,"error")}}),v=st({mutationFn:C=>ne.deleteLocalPreset(C),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),g=w.useCallback(C=>{!C||C.length===0||x.mutate(C)},[x]),y=w.useCallback(C=>{C.preventDefault(),u(!1),g(C.dataTransfer.files)},[g]),_=w.useCallback(C=>{if(!a)return C;const j=a.toLowerCase();return C.filter(P=>P.name.toLowerCase().includes(j)||P.filament_type?.toLowerCase().includes(j)||P.filament_vendor?.toLowerCase().includes(j))},[a]),N=w.useMemo(()=>_(f?.filament||[]),[f?.filament,_]),k=w.useMemo(()=>_(f?.printer||[]),[f?.printer,_]),A=w.useMemo(()=>_(f?.process||[]),[f?.process,_]),M=N.length+k.length+A.length;return p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&i.jsxs("div",{onDragOver:C=>{C.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:y,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:C=>g(C.target.files)}),x.isPending?i.jsxs("div",{className:"flex items-center justify-center gap-2",children:[i.jsx(it,{className:"w-5 h-5 text-bambu-green animate-spin"}),i.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),M>0&&i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:a,onChange:C=>s(C.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),M===0&&!p&&i.jsxs("div",{className:"text-center py-12",children:[i.jsx(Vb,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),i.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),M>0&&i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx($C,{className:"w-4 h-4 text-bambu-green"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:N.map(C=>i.jsx(P2,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),A.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(fi,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",A.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:A.map(C=>i.jsx(P2,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),k.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(ed,{className:"w-4 h-4 text-orange-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:k.map(C=>i.jsx(P2,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]})]}),d!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Ba,{className:"w-5 h-5 text-red-400"}),i.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>v.mutate(d),disabled:v.isPending,children:[v.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function dI(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),a=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:a,nozzle:o,layerHeight:c,filamentType:d}}function s0(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function XZe({onSuccess:t,t:e}){const{showToast:n}=an(),[r,a]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),[p,x]=w.useState("global"),[v,g]=w.useState(null),[y,_]=w.useState(null),N=st({mutationFn:()=>ne.cloudLogin(s,l,p),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):j.needs_verification?(g(j.verification_type||"email"),_(j.tfa_key||null),j.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),a("code")):n(j.message,"error")},onError:j=>n(j.message,"error")}),k=st({mutationFn:()=>ne.cloudVerify(s,u,y||void 0),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):n(j.message,"error")},onError:j=>n(j.message,"error")}),A=st({mutationFn:()=>ne.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:j=>n(j.message,"error")}),M=j=>{j.preventDefault(),r==="email"?N.mutate():r==="code"?k.mutate():r==="token"&&A.mutate()},C=N.isPending||k.isPending||A.isPending;return i.jsx(wt,{className:"max-w-md mx-auto",children:i.jsxs(_t,{children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:i.jsx($b,{className:"w-6 h-6 text-bambu-green"})}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),i.jsxs("form",{onSubmit:M,className:"space-y-4",children:[r==="email"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),i.jsx("input",{type:"email",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),i.jsx("input",{type:"password",value:l,onChange:j=>c(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"••••••••",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),i.jsxs("select",{value:p,onChange:j=>x(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),i.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),i.jsx("input",{type:"text",value:u,onChange:j=>d(j.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),i.jsx("textarea",{value:h,onChange:j=>f(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r==="code"&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>a("email"),className:"flex-1",children:e("profiles.login.back")}),i.jsxs(Ce,{type:"submit",disabled:C,className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(LB,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(nl,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(LB,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Mg({label:t,value:e,options:n,onChange:r}){const[a,s]=w.useState(!1),o=n.find(l=>l.value===e);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>s(!a),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),i.jsx("span",{children:o?.label||"All"}),i.jsx(Pn,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"rotate-180":""}`})]}),a&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),i.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>i.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[i.jsx("span",{children:l.label}),l.count!==void 0&&i.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function YZe(){const[t,e]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?i.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:i.jsx(Mf,{className:"w-5 h-5"})}):null}function E2({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:a,compareIndex:s,compareDisabled:o,t:l}){const c=dI(t.name),u=s0(t.setting_id);return i.jsxs("div",{className:"flex items-center gap-2 group",children:[i.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${a?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[a&&s!==void 0&&i.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!a&&u&&i.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function rF(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(`
  8300. `)){const a=t.replace(/\\n/g,`
  8301. `).replace(/\\"/g,'"').replace(/\\t/g," ").split(`
  8302. `);if(a.length>1)return`"""
  8303. `+a.map(s=>n+" "+s).join(`
  8304. `)+`
  8305. `+n+'"""'}return JSON.stringify(t)}if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.length===0?"[]":`[
  8306. `+t.map(a=>n+" "+rF(a,e+1)).join(`,
  8307. `)+`
  8308. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{
  8309. `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+rF(o,e+1)).join(`,
  8310. `)+`
  8311. `+n+"}"}return String(t)}function QZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=an(),c=en(),[u,d]=w.useState(!1),{data:h,isLoading:f}=Je({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),p=st({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),x=s0(t.setting_id),v=dI(t.name,h?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&i.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:rF(h)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Tn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ce,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ce,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(Yl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:a,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx($a,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ce,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Kie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Xie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function ZZe({onClose:t,onApply:e,t:n}){const{showToast:r}=an(),[a,s]=w.useState(Kie),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[g,y]=w.useState(null),[_,N]=w.useState(null),k=o==="all"?a:a.filter(B=>B.type===o),A=B=>{s(B),Xie(B)},M=B=>{const D=a.filter($=>$.id!==B);A(D),N(null),r(n("profiles.templates.toast.deleted"))},C=B=>{u(B.id),h(B.name),p(B.description),v(JSON.stringify(B.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const B=JSON.parse(x),D=a.map($=>$.id===c?{...$,name:d.trim(),description:f.trim(),settings:B}:$);A(D),u(null),r(n("profiles.templates.toast.updated"))}catch(B){y(B.message)}},P=()=>{u(null),h(""),p(""),v("{}"),y(null)},E=B=>{const D=a.map($=>$.id===B?{...$,showInModal:!$.showInModal}:$);A(D)},U={filament:{label:n("profiles.presets.types.filament"),icon:$C,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:ed,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:gr,color:"text-purple-400"}},L=_?a.find(B=>B.id===_):null;return w.useEffect(()=>{const B=D=>{D.key==="Escape"&&(_?N(null):c?P():t())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[L&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(wt,{className:"w-full max-w-md",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Tn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:L.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ce,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(wt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(B=>i.jsx("button",{onClick:()=>l(B),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:B==="all"?n("common.all"):U[B].label},B))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:k.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(hb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:k.map(B=>{const D=U[B.type],$=D.icon;return c===B.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:G=>h(G.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:f,onChange:G=>p(G.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:x,onChange:G=>{v(G.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${g?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),g&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:j,disabled:!d.trim(),children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},B.id):i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[i.jsx($,{className:`w-5 h-5 ${D.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:B.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:B.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(B.settings).length})}),i.jsx("button",{onClick:()=>E(B.id),className:`p-1 transition-colors ${B.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:B.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:B.showInModal?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(u0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(B),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>C(B),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(B.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]},B.id)})})})]})})]})}function Yie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const g of x){if(g==="inherits"||g==="version")continue;const y=e[g],_=n[g],N=g in e,k=g in n;let A;!N&&k?A="added":N&&!k?A="removed":JSON.stringify(y)!==JSON.stringify(_)?A="changed":A="same",v.push({key:g,left:y,right:_,status:A})}return v.sort((g,y)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[y.status]?_[g.status]-_[y.status]:g.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(g=>g.key.toLowerCase().includes(v)||String(g.left).toLowerCase().includes(v)||String(g.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const g=v.split("\\n").length;if(g>1)return`[${g} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(wt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gg,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(_1,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(t3,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(UM,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),i.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(UM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],g={added:i.jsx(Gn,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(_1,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(t3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(UM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[g,i.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function JZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=an(),s=en(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,g]=w.useState(""),[y,_]=w.useState(e?.setting||{inherits:""}),[N,k]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,M]=w.useState(null),[C,j]=w.useState(""),[P,E]=w.useState(!1),[U,L]=w.useState(""),[B,D]=w.useState(!1),[$,G]=w.useState(Kie),[z,W]=w.useState(!1),[X,ae]=w.useState(""),[H,K]=w.useState(""),[te,Z]=w.useState(!0),[ve,ce]=w.useState(null),[ee,je]=w.useState(!1),he=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),oe=w.useMemo(()=>he.filter(ke=>s0(ke.setting_id)),[he]),{data:_e}=Je({queryKey:["cloudFields",u],queryFn:()=>ne.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:ie}=Je({queryKey:["allPresetDetails",u,oe.map(ke=>ke.setting_id).join(",")],queryFn:async()=>{const ke={};for(let we=0;we<oe.length;we+=5){const qe=oe.slice(we,we+5);(await Promise.all(qe.map(async tt=>{try{const De=await ne.getCloudSettingDetail(tt.setting_id);return{id:tt.setting_id,detail:De}}catch{return null}}))).forEach(tt=>{tt&&(ke[tt.id]=tt.detail)})}return ke},enabled:oe.length>0,staleTime:1e3*60*10}),{data:ze,isLoading:V}=Je({queryKey:["cloudSettingDetail",p],queryFn:()=>ne.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&k(JSON.stringify(y,null,2))},[y,l]);const Y=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(ge=>!s0(ge.setting_id)).sort((ge,we)=>ge.name.localeCompare(we.name)),[n,u]);w.useEffect(()=>{if(!p)return;const ke=Y.find(ge=>ge.setting_id===p);ke&&(g(ke.name),o||(_({inherits:ke.name}),k(JSON.stringify({inherits:ke.name},null,2))))},[p,Y,o]);const me=w.useMemo(()=>{const ke=_e?.fields||[],ge=new Set(ke.map(tt=>tt.key)),we=new Set,qe=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);ie&&Object.values(ie).forEach(tt=>{tt?.setting&&Object.keys(tt.setting).forEach(De=>{!ge.has(De)&&!qe.has(De)&&we.add(De)})}),Object.keys(y).forEach(tt=>{!ge.has(tt)&&!qe.has(tt)&&we.add(tt)});const Ee=Array.from(we).sort().map(tt=>({key:tt,label:tt.replace(/_/g," ").replace(/\b\w/g,De=>De.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...ke,...Ee]},[_e,ie,y,r]),Q=me.filter(ke=>ke.label.toLowerCase().includes(C.toLowerCase())||ke.key.toLowerCase().includes(C.toLowerCase())),se=()=>{if(U.trim()){const ke=U.trim().toLowerCase().replace(/\s+/g,"_");de(ke,""),L(""),D(!1),a(r("profiles.presets.toast.fieldAdded",{key:ke}))}},de=(ke,ge)=>{_(we=>{const qe={...we};return ge===""||ge===void 0?delete qe[ke]:qe[ke]=ge,qe})},Le=ke=>{_(ge=>({...ge,...ke.settings})),ce(ke.name),a(r("profiles.templates.toast.applied"))},Ne=()=>{if(!X.trim())return;const ke={...y};if(delete ke.inherits,Object.keys(ke).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const ge={id:Date.now().toString(),name:X.trim(),description:H.trim()||r("profiles.presets.customTemplate"),type:u,settings:ke,showInModal:te},we=[...$,ge];G(we),Xie(we),W(!1),ae(""),K(""),Z(!0),a(r("profiles.templates.toast.created"))},be=w.useMemo(()=>$.filter(ke=>ke.type===u&&ke.showInModal),[u,$]),O=ke=>{k(ke);try{const ge=JSON.parse(ke);_(ge),M(null)}catch(ge){M(ge.message)}},R=ke=>{ke.preventDefault(),E(!1);const ge=ke.dataTransfer.files[0];if(ge&&ge.name.endsWith(".json")){const we=new FileReader;we.onload=qe=>{try{const Ee=qe.target?.result,tt=JSON.parse(Ee),De=tt.setting||tt;_(We=>({...We,...De})),k(JSON.stringify({...y,...De},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},we.readAsText(ge)}},q=st({mutationFn:()=>{const ke={...y},ge=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";ke[ge]=`"${h}"`;const we={type:u,name:h,base_id:p,setting:ke};return ne.createCloudSetting(we)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>a(ke.message,"error")}),J=st({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:ke=>a(ke.message,"error")}),fe=o?J:q,le=ze?.setting?.inherits,Be=le?Y.find(ke=>ke.name===le):void 0,{data:Ie}=Je({queryKey:["cloudSettingDetail",Be?.setting_id],queryFn:()=>ne.getCloudSettingDetail(Be.setting_id),enabled:!!Be?.setting_id}),Ke=w.useMemo(()=>{const ke=Ie?.setting||{},ge=ze?.setting||{},we=p&&ie?.[p]?.setting?ie[p].setting:{};return{...ke,...ge,...we}},[p,ze,Ie,ie]),Oe=ke=>{if(ke==null)return"";if(Array.isArray(ke)){const ge=[...new Set(ke.map(we=>String(we)))];return ge.length===1?ge[0]:ke.join(", ")}return String(ke)},pe=ke=>{const ge=y[ke.key],we=Ke[ke.key],qe=Oe(we),Ee=V?r("common.loading"):qe||"",tt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(ke.type==="boolean"){const De=ge==="1"||ge===void 0&&we==="1";return i.jsx("button",{type:"button",onClick:()=>de(ke.key,ge==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${De?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${De?"translate-x-3.5":"translate-x-0.5"}`})})}return ke.type==="select"?i.jsxs("select",{value:ge||"",onChange:De=>de(ke.key,De.target.value),className:tt,children:[i.jsx("option",{value:"",children:Ee}),ke.options?.map(De=>i.jsx("option",{value:De.value,children:De.label},De.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:ke.type==="number"?"number":"text",value:ge!==void 0?String(ge):"",onChange:De=>de(ke.key,De.target.value),step:ke.step,min:ke.min,max:ke.max,placeholder:Ee,className:tt}),ke.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:ke.unit})]})},xe=w.useMemo(()=>ze?.setting?ze.setting:{},[ze]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:ke=>{ke.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:R,children:[ee&&p&&i.jsx(Yie,{onClose:()=>je(!1),leftPreset:xe,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),i.jsx(wt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[p&&i.jsxs("button",{onClick:()=>je(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx(Gg,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]})]}),P&&i.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Ra,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:ke=>{d(ke.target.value),x("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:p,onChange:ke=>x(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),Y.map(ke=>i.jsx("option",{value:ke.setting_id,children:ke.name},ke.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:h,onChange:ke=>f(ke.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(aa,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),V&&i.jsx(it,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(OB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(WC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(mX,{className:"w-4 h-4"}),"JSON",A&&i.jsx(Ba,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const ke={name:h,type:u,base_id:p,setting:y},ge=new Blob([JSON.stringify(ke,null,2)],{type:"application/json"}),we=URL.createObjectURL(ge),qe=document.createElement("a");qe.href=we,qe.download=`${h||"preset"}.json`,document.body.appendChild(qe),qe.click(),document.body.removeChild(qe),URL.revokeObjectURL(we),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(da,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(Ra,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:ke=>{const ge=ke.target.files?.[0];if(ge){const we=new FileReader;we.onload=qe=>{try{const Ee=JSON.parse(qe.target?.result),tt=Ee.setting||Ee;_(De=>({...De,...tt})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},we.readAsText(ge)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(hb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&i.jsxs("button",{onClick:()=>W(!z),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ps,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),z&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:X,onChange:ke=>ae(ke.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:H,onChange:ke=>K(ke.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:Ne,disabled:!X.trim(),children:[i.jsx(ps,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>W(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>Z(!te),className:`flex items-center gap-1.5 text-xs transition-colors ${te?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[te?i.jsx(Ql,{className:"w-3.5 h-3.5"}):i.jsx(u0,{className:"w-3.5 h-3.5"}),r(te?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ve&&i.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[i.jsx(aa,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:ve})]}),i.jsx("button",{onClick:()=>ce(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[be.map(ke=>i.jsxs("button",{onClick:()=>Le(ke),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:ke.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ke.description})]},ke.id)),be.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:me.slice(0,10).map(ke=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:ke.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:pe(ke)})]},ke.key))})]}),Object.keys(y).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,ge])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[ke,": ",String(ge).slice(0,20),i.jsx("button",{onClick:()=>de(ke,void 0),className:"hover:text-white",children:i.jsx(Lt,{className:"w-3 h-3"})})]},ke))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:ie?r("profiles.templates.fieldsCount",{count:me.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:C,onChange:ke=>j(ke.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Q.filter(ke=>!(ke.key in y)).map(ke=>{const ge=Ke[ke.key],we=Oe(ge);return i.jsxs("div",{onClick:()=>{_(qe=>({...qe,[ke.key]:we||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:ke.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:ke.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[we&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:we,children:[we.slice(0,20),we.length>20?"...":""]}),i.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:i.jsx(Gn,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},ke.key)}),Q.filter(ke=>!(ke.key in y)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(C?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:B?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:U,onChange:ke=>L(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&se(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx(Ce,{size:"sm",onClick:se,disabled:!U.trim(),children:i.jsx(Gn,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>{D(!1),L("")},children:i.jsx(Lt,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>D(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(Gn,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(ke=>ke!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([ke])=>ke!=="inherits").map(([ke,ge])=>{const we=me.find(qe=>qe.key===ke);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:we?.label||ke}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:ke})]}),i.jsx("button",{onClick:()=>de(ke,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),we?pe(we):i.jsx("input",{type:"text",value:String(ge),onChange:qe=>de(ke,qe.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},ke)}),Object.keys(y).filter(ke=>ke!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(OB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(ke=>ke!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{W(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ps,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[A&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Ba,{className:"w-4 h-4"}),A]}),i.jsx("textarea",{value:N,onChange:ke=>O(ke.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ce,{onClick:()=>fe.mutate(),disabled:fe.isPending||!h.trim()||!o&&!p||!!A,className:"flex-1",children:[fe.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ps,{className:"w-4 h-4"}):i.jsx(Gn,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function eJe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState("all"),[A,M]=w.useState(null),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(null),[$,G]=w.useState(null),[z,W]=w.useState(!1),[X,ae]=w.useState([null,null]),[H,K]=w.useState(!1),[te,Z]=w.useState(null),ve=en(),ce=w.useMemo(()=>[...t.filament.map(se=>({...se,type:"filament"})),...t.printer.map(se=>({...se,type:"printer"})),...t.process.map(se=>({...se,type:"process"}))].map(se=>({...se,meta:dI(se.name)})),[t]),ee=w.useMemo(()=>{const Q=new Set,se=new Set,de=new Set;return ce.forEach(Le=>{Le.meta.nozzle&&Q.add(Le.meta.nozzle),Le.meta.filamentType&&se.add(Le.meta.filamentType),Le.meta.layerHeight&&de.add(Le.meta.layerHeight)}),{printers:a.map(Le=>({id:Le.id.toString(),name:Le.name})),nozzles:Array.from(Q).sort((Le,Ne)=>parseFloat(Le)-parseFloat(Ne)),filaments:Array.from(se).sort(),layerHeights:Array.from(de).sort((Le,Ne)=>parseFloat(Le)-parseFloat(Ne))}},[ce,a]),je=w.useMemo(()=>p==="all"?null:a.find(se=>se.id.toString()===p)?.model||null,[p,a]),he=w.useMemo(()=>ce.filter(Q=>u==="all"||Q.type===u).filter(Q=>{if(h==="all")return!0;const se=s0(Q.setting_id);return h==="custom"?se:!se}).filter(Q=>{if(p==="all"||!je)return!0;const se=Q.meta.printer?.toLowerCase()||"",de=je.toLowerCase();return se.includes(de)||de.includes(se)}).filter(Q=>v==="all"||Q.meta.nozzle===v).filter(Q=>y==="all"||Q.meta.filamentType===y).filter(Q=>N==="all"||Q.meta.layerHeight===N).filter(Q=>l===""||Q.name.toLowerCase().includes(l.toLowerCase())).sort((Q,se)=>Q.name.localeCompare(se.name)),[ce,u,h,p,je,v,y,N,l]),oe=Q=>{if(z){const se=X[0]?.setting_id===Q.setting_id,de=X[1]?.setting_id===Q.setting_id;if(se)ae([X[1],null]);else if(de)ae([X[0],null]);else if(!X[0])ae([Q,null]);else if(X[1]){if(X[0].type!==Q.type)return;ae([X[0],Q])}else{if(X[0].type!==Q.type)return;ae([X[0],Q])}}else M(Q)},_e=Q=>{if(X[0]?.setting_id===Q.setting_id)return 0;if(X[1]?.setting_id===Q.setting_id)return 1},ie=async Q=>{try{const se=await ne.getCloudSettingDetail(Q.setting_id),de=Q.type==="process"?"print":Q.type;L({type:de,name:Q.name,base_id:se.base_id||"GFSA00",setting:se.setting||{}}),M(null)}catch(se){console.error("Failed to fetch preset details for duplication:",se)}},ze=async Q=>{try{ve.removeQueries({queryKey:["cloudSettingDetail",Q.setting_id]});const se=await ne.getCloudSettingDetail(Q.setting_id),de=Q.type==="process"?"print":Q.type;D({type:de,name:Q.name,base_id:se.base_id||"GFSA00",setting:se.setting||{},setting_id:Q.setting_id}),M(null)}catch(se){console.error("Failed to fetch preset details for editing:",se)}},V=()=>{d("all"),f("all"),x("all"),g("all"),_("all"),k("all"),c("")},Y=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",me=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:Q=>c(Q.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ce,{variant:z?"primary":"secondary",onClick:()=>{z?(W(!1),ae([null,null])):W(!0)},children:[i.jsx(Gg,{className:"w-4 h-4"}),o(z?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(hb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ce,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Ar,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ce,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(Gn,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(qC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Mg,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:me},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Q=>d(Q)}),i.jsx(Mg,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Q=>f(Q)}),ee.printers.length>0&&i.jsx(Mg,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...ee.printers.map(Q=>({value:Q.id,label:Q.name}))],onChange:x}),ee.nozzles.length>0&&i.jsx(Mg,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...ee.nozzles.map(Q=>({value:Q,label:Q}))],onChange:g}),ee.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Mg,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...ee.filaments.map(Q=>({value:Q,label:Q}))],onChange:_}),ee.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Mg,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...ee.layerHeights.map(Q=>({value:Q,label:Q}))],onChange:k}),Y&&i.jsx("button",{onClick:V,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),z&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Gg,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:X[0]?o("profiles.cloudView.selectAnotherPreset",{type:X[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${X[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:X[0]?X[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(t3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${X[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:X[1]?X[1].name:o("profiles.cloudView.selectSecond")})]}),X[0]&&X[1]&&i.jsxs(Ce,{size:"sm",onClick:async()=>{try{const[Q,se]=await Promise.all([ne.getCloudSettingDetail(X[0].setting_id),ne.getCloudSettingDetail(X[1].setting_id)]);Z([Q.setting||{},se.setting||{}]),K(!0)}catch{}},children:[i.jsx(Gg,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",yv(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:he.length,total:me})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),he.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(fi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),Y&&i.jsx("button",{onClick:V,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx($C,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",he.filter(Q=>Q.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="filament").map(Q=>i.jsx(E2,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>ie(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(ed,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",he.filter(Q=>Q.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="process").map(Q=>i.jsx(E2,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>ie(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(gr,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",he.filter(Q=>Q.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="printer").map(Q=>i.jsx(E2,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>ie(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),A&&i.jsx(QZe,{setting:A,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>ie(A),onEdit:()=>ze(A),hasPermission:s,t:o}),(C||U||B||$)&&i.jsx(JZe,{onClose:()=>{j(!1),L(null),D(null),G(null)},initialData:B||U||($?{type:$.type,name:"",base_id:"",setting:$.setting}:void 0),allPresets:t,t:o}),P&&i.jsx(ZZe,{onClose:()=>E(!1),onApply:Q=>{G({type:Q.type,setting:Q.settings}),E(!1)},t:o}),H&&te&&X[0]&&X[1]&&i.jsx(Yie,{onClose:()=>{K(!1),Z(null)},leftPreset:te[0],rightPreset:te[1],leftLabel:X[0].name,rightLabel:X[1].name,t:o})]})}function tJe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r}=Ir(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=Je({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:d=[]}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=st({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx($b,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Vb,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(GC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(s3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx(eJe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ce,{onClick:()=>p(),children:t("profiles.retry")})]}):i.jsx(XZe,{onSuccess:g,t})]}),a==="local"&&i.jsx(KZe,{}),a==="kprofiles"&&i.jsx(VZe,{}),i.jsx(YZe,{})]})}const Uy={Droplet:$C,Flame:gme,Ruler:Qfe,Sparkles:hb,Square:vl,Cable:Jde,Wrench:Df,Calendar:ra,Timer:Lu,Cog:zhe,Fan:fX,Zap:nd,Wind:kX,Thermometer:JC,Layers:fi,Box:Ja,Target:_X,RefreshCw:Ar,Settings:f0,Filter:qC,CircleDot:vhe};function dv(t){return t&&Uy[t]||Df}function Pg(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function j2(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function nJe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a||h?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function rJe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=dv(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",f=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Pg(Math.abs(p),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Pg(p,"days",a)}):a("maintenance.timeLeft",{duration:Pg(p,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Pg(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Pg(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Pg(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(ra,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||nJe(t.maintenance_type_name,t.printer_model);return p?i.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:i.jsx(Xr,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Tn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Wn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(aa,{className:"w-3 h-3"}),f()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(In,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),i.jsxs(Ce,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(so,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function aJe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,g)=>v.is_due&&!g.is_due?-1:!v.is_due&&g.is_due?1:v.is_warning&&!g.is_warning?-1:!v.is_warning&&g.is_warning?1:v.maintenance_type_id-g.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(wt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Tn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Wn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(aa,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Pn,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Lu,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ce,{size:"sm",onClick:x,children:s("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Pf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=dv(p.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),i.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(_t,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>i.jsx(rJe,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function iJe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[g,y]=w.useState("hours"),[_,N]=w.useState(!1),[k,A]=w.useState(""),[M,C]=w.useState("100"),[j,P]=w.useState("hours"),[E,U]=w.useState("Wrench"),[L,B]=w.useState(""),[D,$]=w.useState(new Set),[G,z]=w.useState(null),[W,X]=w.useState(null),ae=w.useMemo(()=>t?t.map(O=>({id:O.printer_id,name:O.printer_name})):[],[t]),H=O=>t?t.filter(R=>R.maintenance_items.some(q=>q.maintenance_type_id===O)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(q=>q.maintenance_type_id===O)?.id})):[],K=O=>{if(!t)return[];const R=new Set(H(O).map(q=>q.printerId));return ae.filter(q=>!R.has(q.id))},[te,Z]=w.useState(null),[ve,ce]=w.useState(""),[ee,je]=w.useState(""),[he,oe]=w.useState("hours"),[_e,ie]=w.useState("Wrench"),[ze,V]=w.useState(""),Y=O=>{Z(O),ce(O.name),je(O.default_interval_hours.toString()),oe(O.interval_type||"hours"),ie(O.icon||"Wrench"),V(O.wiki_url||"")},me=()=>{te&&ve.trim()&&parseFloat(ee)>0&&(a(te.id,{name:ve.trim(),default_interval_hours:parseFloat(ee),interval_type:he,icon:_e,wiki_url:ze.trim()||null}),Z(null))},Q=(O,R,q)=>{const J=parseFloat(x);if(!isNaN(J)&&J>0){const fe=Math.abs(J-R)<.01?null:J;n(O,{custom_interval_hours:fe,custom_interval_type:g!==q?g:null})}p(null)},se=O=>{O.preventDefault(),k.trim()&&parseFloat(M)>0&&D.size>0&&(r({name:k.trim(),default_interval_hours:parseFloat(M),interval_type:j,icon:E,wiki_url:L.trim()||null},Array.from(D)),A(""),C("100"),P("hours"),B(""),$(new Set),N(!1))},de=O=>{$(R=>{const q=new Set(R);return q.has(O)?q.delete(O):q.add(O),q})},Le=t?.map(O=>({printerId:O.printer_id,printerName:O.printer_name,items:O.maintenance_items.sort((R,q)=>R.maintenance_type_id-q.maintenance_type_id)})).sort((O,R)=>O.printerName.localeCompare(R.printerName))||[],Ne=e.filter(O=>O.is_system),be=e.filter(O=>!O.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),i.jsxs(Ce,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[i.jsx(Gn,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),_&&i.jsx(wt,{className:"mb-6",children:i.jsx(_t,{className:"py-4",children:i.jsxs("form",{onSubmit:se,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),i.jsx("input",{type:"text",value:k,onChange:O=>A(O.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),i.jsxs("select",{value:j,onChange:O=>{P(O.target.value),O.target.value==="days"?C("30"):C("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),i.jsx("input",{type:"number",value:M,onChange:O=>C(O.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Uy).map(O=>{const R=Uy[O];return i.jsx("button",{type:"button",onClick:()=>U(O),className:`p-2 rounded-lg transition-colors ${E===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(R,{className:"w-4 h-4"})},O)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:L,onChange:O=>B(O.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map(O=>i.jsx("button",{type:"button",onClick:()=>de(O.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${D.has(O.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:O.name},O.id))}),D.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>{N(!1),$(new Set)},children:h("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!k.trim()||D.size===0,children:h("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[Ne.map(O=>{const R=dv(O.icon),q=O.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:O.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[q==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),j2(O.default_interval_hours,q,h)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&X(O)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]})},O.id)}),be.map(O=>{const R=dv(O.icon),q=O.interval_type||"hours";if(te?.id===O.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:ve,onChange:Ie=>ce(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:he,onChange:Ie=>oe(Ie.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:ee,onChange:Ie=>je(Ie.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Uy).map(Ie=>{const Ke=Uy[Ie];return i.jsx("button",{type:"button",onClick:()=>ie(Ie),className:`p-1.5 rounded transition-colors ${_e===Ie?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(Ke,{className:"w-3.5 h-3.5"})},Ie)})}),i.jsx("input",{type:"url",value:ze,onChange:Ie=>V(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{size:"sm",onClick:me,disabled:!ve.trim(),children:h("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>Z(null),children:h("common.cancel")})]})]})},O.id);const fe=H(O.id),le=K(O.id),Be=G===O.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:O.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[q==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),j2(O.default_interval_hours,q,h)]})]}),i.jsxs("button",{onClick:()=>z(Be?null:O.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${fe.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:h("maintenance.printersAssignedClick",{count:fe.length}),children:[i.jsx(gr,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:fe.length}),i.jsx(Pn,{className:`w-3 h-3 transition-transform ${Be?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>Y(O),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Pf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:O.name}))&&s(O.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]}),Be&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),fe.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:fe.map(Ie=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[Ie.printerName,i.jsx("button",{onClick:()=>Ie.itemId&&u(Ie.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},Ie.printerId))}),le.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),le.map(Ie=>i.jsxs("button",{onClick:()=>c(Ie.id,O.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",Ie.name]},Ie.id))]})]})]},O.id)})]})]}),Le.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:Le.map(O=>i.jsx(wt,{children:i.jsxs(_t,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:O.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:O.items.map(R=>{const q=dv(R.maintenance_type_icon),J=e.find(Ke=>Ke.id===R.maintenance_type_id),fe=J?.default_interval_hours||R.interval_hours,le=J?.interval_type||"hours",Be=R.interval_type||"hours",Ie=f===R.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(q,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),Ie?i.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?i.jsx(ra,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Lu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:g,onChange:Ke=>y(Ke.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:x,onChange:Ke=>v(Ke.target.value),onKeyDown:Ke=>{Ke.key==="Enter"&&Q(R.id,fe,le),Ke.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ce,{size:"sm",onClick:()=>Q(R.id,fe,le),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(R.id),v(R.interval_hours.toString()),y(Be))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[Be==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),j2(R.interval_hours,Be,h),i.jsx(Pf,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},O.printerId))})]}),Le.length===0&&i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx(Wn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),W&&i.jsx(gn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:W.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(W.id),X(null)},onCancel:()=>X(null)})]})}function sJe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r}=Ir(),[a,s]=w.useState("status"),{data:o,isLoading:l}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=Je({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),u=st({mutationFn:({id:M,notes:C})=>ne.performMaintenance(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=st({mutationFn:({id:M,data:C})=>ne.updateMaintenanceItem(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=st({mutationFn:({id:M,data:C})=>ne.updateMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),f=st({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),p=st({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),x=st({mutationFn:({printerId:M,hours:C})=>ne.setPrinterHours(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=st({mutationFn:({printerId:M,typeId:C})=>ne.assignMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),g=st({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),y=M=>{u.mutate({id:M})},_=(M,C)=>{d.mutate({id:M,data:{enabled:C}})},N=(M,C)=>{x.mutate({printerId:M,hours:C})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});const k=o?.reduce((M,C)=>M+C.due_count,0)||0,A=o?.reduce((M,C)=>M+C.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[k>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:k})}),k>0&&A>0&&" · ",A>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:A})}),k===0&&A===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,C)=>{const j=M.due_count*10+M.warning_count,P=C.due_count*10+C.warning_count;return j!==P?P-j:M.printer_name.localeCompare(C.printer_name)}).map(M=>i.jsx(aJe,{overview:M,onPerform:y,onToggle:_,onSetHours:N,hasPermission:r,t},M.printer_id)):i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-16",children:[i.jsx(Df,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(iJe,{overview:o,types:c||[],onUpdateInterval:(M,C)=>d.mutate({id:M,data:C}),onAddType:async(M,C)=>{const j=await ne.createMaintenanceType(M);for(const P of C)await ne.assignMaintenanceType(P,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,C)=>h.mutate({id:M,data:C}),onDeleteType:M=>f.mutate(M),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(M,C)=>v.mutate({printerId:M,typeId:C}),onRemoveItem:M=>g.mutate(M),hasPermission:r,t})]})}const aK=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Qie({project:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||aK[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,g]=w.useState(t?.status||"active"),[y,_]=w.useState(t?.tags||""),[N,k]=w.useState(t?.due_date?.split("T")[0]||""),[A,M]=w.useState(t?.priority||"normal"),C=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:A,...t&&{status:v}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:C,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.description")}),i.jsx("textarea",{value:l,onChange:j=>c(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:a("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:aK.map(j=>i.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetPlates")}),i.jsx("input",{type:"number",value:h,onChange:j=>f(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetParts")}),i.jsx("input",{type:"number",value:p,onChange:j=>x(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.tagsLabel")}),i.jsx("input",{type:"text",value:y,onChange:j=>_(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.dueDate")}),i.jsx("input",{type:"date",value:N,onChange:j=>k(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.priority")}),i.jsxs("select",{value:A,onChange:j=>M(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"low",children:a("projects.priorityLow")}),i.jsx("option",{value:"normal",children:a("projects.priorityNormal")}),i.jsx("option",{value:"high",children:a("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:a("projects.priorityUrgent")})]})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.status")}),i.jsxs("select",{value:v,onChange:j=>g(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"active",children:a("projects.statusActive")}),i.jsx("option",{value:"completed",children:a("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:a("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a(t?"common.save":"projects.create")})]})]})]})})}function oJe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:ub,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Wn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:gs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[i.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:i.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&i.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&i.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),y=[...new Set(g)];return v.length===0&&y.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),y.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),y.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[i.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>h(!d),children:i.jsx(Th,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),i.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),h(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),h(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(js,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Wn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(ni,{className:"w-6 h-6"})}),x.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Tn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(fi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(ni,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(i3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function lJe(){const{t}=Ot(),e=rc(),n=en(),{showToast:r}=an(),{hasPermission:a}=Ir(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=Je({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ne.getProjects(u==="all"?void 0:u)}),v=st({mutationFn:B=>ne.createProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:B=>{r(B.message,"error")}}),g=st({mutationFn:({id:B,data:D})=>ne.updateProject(B,D),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:B=>{r(B.message,"error")}}),y=st({mutationFn:B=>ne.deleteProject(B),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:B=>{f(null),r(B.message,"error")}}),_=st({mutationFn:B=>ne.importProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:B=>{r(B.message,"error")}}),N=w.useRef(null),k=async()=>{try{const B=await ne.getProjects(),D=await Promise.all(B.map(async W=>await ne.exportProjectJson(W.id))),$=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),G=URL.createObjectURL($),z=document.createElement("a");z.href=G,z.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,z.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(B){r(B.message,"error")}},A=()=>{N.current?.click()},M=async B=>{const D=B.target.files?.[0];if(D){try{if(D.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(D),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await D.text(),z=JSON.parse(G),W=Array.isArray(z)?z:[z];for(const X of W)await _.mutateAsync(X);W.length>1&&r(t("projects.toast.multipleImported",{count:W.length}),"success")}}catch($){r(`${t("projects.toast.importFailed")}: ${$.message}`,"error")}B.target.value=""}},C=B=>{l?g.mutate({id:l.id,data:B}):v.mutate(B)},j=B=>{c(B),o(!0)},P=B=>{e(`/projects/${B.id}`)},E=B=>{f(B)},U=()=>{h!==null&&y.mutate(h)},L=p?.reduce((B,D)=>(B[D.status]=(B[D.status]||0)+1,B.all=(B.all||0)+1,B),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:M,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(gs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:A,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(da,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ce,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Gn,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Wn},{key:"completed",label:t("projects.statusCompleted"),icon:ub},{key:"archived",label:t("projects.statusArchived"),icon:js},{key:"all",label:t("common.all"),icon:gs}].map(({key:B,label:D,icon:$})=>i.jsxs("button",{onClick:()=>d(B),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===B?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx($,{className:"w-4 h-4"}),i.jsx("span",{children:D}),L[B]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[B]})]},B))}),x?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(gs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ce,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Gn,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(B=>i.jsx(oJe,{project:B,onClick:()=>P(B),onEdit:()=>j(B),onDelete:()=>E(B.id),hasPermission:a,t},B.id))}),h!==null&&i.jsx(gn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>f(null)}),s&&i.jsx(Qie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:v.isPending||g.isPending,t})]})}function cJe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function uJe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function dJe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function iK({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(wt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function hJe({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(ni,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>i.jsxs(Ks,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(ni,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(mi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mJe({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Tn,{className:"w-3 h-3"}),a]})}function fJe(t){return t?mb(t,{year:"numeric",month:"short",day:"numeric"}):""}function D2(t,e){if(!t)return null;const n=hi(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function pJe(){const{id:t}=l0(),e=rc(),{t:n}=Ot(),r=en(),{showToast:a}=an(),{hasPermission:s}=Ir(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=Je({queryKey:["project",f],queryFn:()=>ne.getProject(f),enabled:f>0}),{data:g,isLoading:y}=Je({queryKey:["project-archives",f],queryFn:()=>ne.getProjectArchives(f),enabled:f>0}),{data:_,isLoading:N}=Je({queryKey:["project-bom",f],queryFn:()=>ne.getProjectBOM(f),enabled:f>0}),{data:k,isLoading:A}=Je({queryKey:["project-timeline",f],queryFn:()=>ne.getProjectTimeline(f,20),enabled:f>0}),{data:M}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:C}=Je({queryKey:["project-folders",f],queryFn:()=>ne.getLibraryFoldersByProject(f),enabled:f>0}),j=rl(M?.currency||"USD"),P=M?.time_format||"system",E=st({mutationFn:we=>ne.updateProject(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:we=>{a(we.message,"error")}}),U=()=>{h(p?.notes||""),u(!0)},L=()=>{E.mutate({notes:d})},B=()=>{u(!1),h("")},[D,$]=w.useState(""),[G,z]=w.useState(1),[W,X]=w.useState(""),[ae,H]=w.useState(""),[K,te]=w.useState(""),[Z,ve]=w.useState(!1),[ce,ee]=w.useState(!1),[je,he]=w.useState(null),[oe,_e]=w.useState(""),[ie,ze]=w.useState(1),[V,Y]=w.useState(""),[me,Q]=w.useState(""),[se,de]=w.useState(""),[Le,Ne]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),be=st({mutationFn:we=>ne.createBOMItem(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),$(""),z(1),X(""),H(""),te(""),ve(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:we=>a(we.message,"error")}),O=st({mutationFn:({itemId:we,data:qe})=>ne.updateBOMItem(f,we,qe),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),he(null)},onError:we=>a(we.message,"error")}),R=st({mutationFn:we=>ne.deleteBOMItem(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:we=>a(we.message,"error")}),q=we=>{we.preventDefault(),D.trim()&&be.mutate({name:D.trim(),quantity_needed:G,unit_price:W?parseFloat(W):void 0,sourcing_url:ae.trim()||void 0,remarks:K.trim()||void 0})},J=we=>{const qe=we.is_complete?0:we.quantity_needed;O.mutate({itemId:we.id,data:{quantity_acquired:qe}})},fe=(we,qe)=>{Ne({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:qe}),onConfirm:()=>{Ne(Ee=>({...Ee,isOpen:!1})),R.mutate(we)}})},le=we=>{he(we),_e(we.name),ze(we.quantity_needed),Y(we.unit_price?.toString()||""),Q(we.sourcing_url||""),de(we.remarks||"")},Be=we=>{we.preventDefault(),!(!je||!oe.trim())&&O.mutate({itemId:je.id,data:{name:oe.trim(),quantity_needed:ie,unit_price:V?parseFloat(V):void 0,sourcing_url:me.trim()||void 0,remarks:se.trim()||void 0}})},Ie=()=>{he(null)},Ke=async()=>{try{const{blob:we,filename:qe}=await ne.exportProjectZip(Number(f)),Ee=URL.createObjectURL(we),tt=document.createElement("a");tt.href=Ee,tt.download=qe||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,tt.click(),URL.revokeObjectURL(Ee),a(n("projectDetail.toast.projectExported"),"success")}catch(we){a(we.message,"error")}},Oe=st({mutationFn:()=>ne.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:we=>a(we.message,"error")}),pe=we=>Rf(we,P,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ce,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const xe=p.stats,ke=xe?.progress_percent??0,ge=xe?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(Ks,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(pi,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:p.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(_F,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),i.jsx(dJe,{status:p.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:Ke,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(da,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ce,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&i.jsx(wt,{children:i.jsxs(_t,{className:"p-4 space-y-4",children:[p.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[xe?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(ke,100)}%`,backgroundColor:ke>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:ke.toFixed(0)})}),xe?.remaining_prints!=null&&xe.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:xe.remaining_prints})})]})]}),p.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[xe?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(ge,100)}%`,backgroundColor:ge>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:ge.toFixed(0)})}),xe?.remaining_parts!=null&&xe.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:xe.remaining_parts})})]})]})]})}),xe&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(wt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(ni,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[xe.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),xe.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:xe.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:xe.completed_prints})})]})]})})}),i.jsx(iK,{icon:Wn,label:n("projectDetail.stats.printTime"),value:cJe(xe.total_print_time_hours),color:"text-yellow-400"}),i.jsx(iK,{icon:gr,label:n("projectDetail.stats.filamentUsed"),value:uJe(xe.total_filament_grams),color:"text-purple-400"})]}),xe&&(xe.estimated_cost>0||p.budget)&&i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,xe.estimated_cost.toFixed(2)]})]}),xe.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[xe.total_energy_kwh.toFixed(3)," kWh",xe.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,xe.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),i.jsxs("p",{className:`text-lg font-semibold ${p.budget-xe.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-xe.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(Sme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),i.jsx("div",{className:"space-y-2",children:p.children.map(we=>i.jsxs(Ks,{to:`/projects/${we.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:we.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:we.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${we.status==="completed"?"bg-status-ok/20 text-status-ok":we.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:we.status})]}),we.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[we.progress_percent.toFixed(0),"%"]})]},we.id))})]})}),p.parent_id&&p.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(Ks,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(mJe,{priority:p.priority,t:n})]}),p.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ra,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:fJe(p.due_date)}),D2(p.due_date,n)&&i.jsxs("span",{className:`text-xs ${D2(p.due_date,n).color}`,children:["(",D2(p.due_date,n).label,")"]})]}),p.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vh,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((we,qe)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:we.trim()},qe))})]})]}),i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:B,disabled:E.isPending,children:[i.jsx(Lt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ce,{size:"sm",onClick:L,disabled:E.isPending,children:[E.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ps,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:U,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Pf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(QR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Zl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(Ks,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),C&&C.length>0?i.jsx("div",{className:"space-y-2",children:C.map(we=>i.jsxs(Ks,{to:`/files?folder=${we.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Zl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:we.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:we.file_count})})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},we.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(wX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),xe&&xe.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:xe.bom_completed_items,total:xe.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(we=>we.is_complete)&&i.jsx("button",{onClick:()=>ee(!ce),className:`text-xs px-2 py-1 rounded transition-colors ${ce?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ce?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!Z&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>ve(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(Gn,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),Z&&i.jsxs("form",{onSubmit:q,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:D,onChange:we=>$(we.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:G,onChange:we=>z(parseInt(we.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:W,onChange:we=>X(we.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:ae,onChange:we=>H(we.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:K,onChange:we=>te(we.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>ve(!1),children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!D.trim()||be.isPending,children:be.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(we=>!ce||!we.is_complete).map(we=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${we.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:je?.id===we.id?i.jsxs("form",{onSubmit:Be,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:oe,onChange:qe=>_e(qe.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:ie,onChange:qe=>ze(parseInt(qe.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:V,onChange:qe=>Y(qe.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:me,onChange:qe=>Q(qe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:se,onChange:qe=>de(qe.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:Ie,children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!oe.trim()||O.isPending,children:O.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&J(we),disabled:O.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${we.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:we.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${we.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[we.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",we.quantity_needed]})]}),we.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(we.unit_price*we.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&le(we),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&fe(we.id,we.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),we.sourcing_url&&i.jsxs("a",{href:we.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:qe=>qe.stopPropagation(),children:[i.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(we.sourcing_url).hostname.replace("www.","")}catch{return we.sourcing_url}})()})]}),we.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:we.remarks})]})]})},we.id)),_.some(we=>we.unit_price!==null)&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[j,_.reduce((we,qe)=>we+(qe.unit_price||0)*qe.quantity_needed,0).toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(db,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),A?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):k&&k.length>0?i.jsx("div",{className:"space-y-3",children:k.slice(0,10).map((we,qe)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${we.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":we.event_type==="print_failed"?"bg-status-error/20 text-status-error":we.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[we.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),we.event_type==="print_failed"&&i.jsx(mi,{className:"w-4 h-4"}),we.event_type==="print_started"&&i.jsx(gr,{className:"w-4 h-4"}),we.event_type==="queued"&&i.jsx(i3,{className:"w-4 h-4"}),we.event_type==="project_created"&&i.jsx(Gn,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:we.title}),we.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:we.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:pe(we.timestamp)})]})]},qe))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>Oe.mutate(),disabled:Oe.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Oe.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Yl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),xe&&(xe.queued_prints>0||xe.in_progress_prints>0)&&i.jsx(wt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(i3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(Ks,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[xe.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:xe.in_progress_prints})}),xe.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:xe.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(ni,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:g?.length||0})]})}),y?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(hJe,{archives:g||[],t:n})]}),o&&i.jsx(Qie,{t:n,project:{...p,archive_count:xe?.total_archives||0,total_items:xe?.total_items||0,completed_count:xe?.completed_prints||0,failed_count:xe?.failed_prints||0,queue_count:xe?.queued_prints||0,progress_percent:xe?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:we=>E.mutate(we),isLoading:E.isPending}),Le.isOpen&&i.jsx(gn,{title:Le.title,message:Le.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Le.onConfirm,onCancel:()=>Ne(we=>({...we,isOpen:!1}))})]})}function gJe({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function bJe({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(it,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function xJe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>i.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[i.jsx(Zl,{className:"w-4 h-4"}),h.name,h.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ce,{onClick:()=>a(l),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function yJe({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:d}=Je({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(jh,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(uX,{className:"w-4 h-4"}),a("fileManager.project")]}),i.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(js,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:x.name})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(hf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&i.jsxs(Ce,{variant:"danger",onClick:f,disabled:r,children:[i.jsx(ek,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{onClick:h,disabled:!l||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function vJe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[a,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),g=w.useRef(null),y=$=>{$.preventDefault(),l(!0)},_=$=>{$.preventDefault(),l(!1)},N=$=>{$.preventDefault(),l(!1);const G=Array.from($.dataTransfer.files);A(G)},k=$=>{$.target.files&&A(Array.from($.target.files))},A=$=>{const G=$.map(z=>({file:z,status:"pending",isZip:z.name.toLowerCase().endsWith(".zip"),is3mf:z.name.toLowerCase().endsWith(".3mf")}));s(z=>[...z,...G])},M=$=>{s(G=>G.filter((z,W)=>W!==$))},C=a.some($=>$.isZip&&$.status==="pending"),j=a.some($=>$.file.name.toLowerCase().endsWith(".stl")&&$.status==="pending"),P=a.some($=>$.is3mf&&$.status==="pending"),E=async()=>{if(a.length!==0){u(!0);for(let $=0;$<a.length;$++)if(a[$].status==="pending"){s(G=>G.map((z,W)=>W===$?{...z,status:"uploading"}:z));try{if(a[$].isZip){const G=await ne.extractZipFile(a[$].file,t,d,f,x);s(z=>z.map((W,X)=>X===$?{...W,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:W))}else await ne.uploadLibraryFile(a[$].file,t,x),s(G=>G.map((z,W)=>W===$?{...z,status:"success"}:z))}catch(G){s(z=>z.map((W,X)=>X===$?{...W,status:"error",error:G instanceof Error?G.message:"Upload failed"}:W))}}u(!1),n(),e()}},U=a.filter($=>$.status==="pending").length,L=a.filter($=>$.status==="success").length,B=a.filter($=>$.status==="error").length,D=a.length>0&&U===0&&!c;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Lt,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:y,onDragLeave:_,onDrop:N,onClick:()=>g.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Ra,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:g,type:"file",multiple:!0,className:"hidden",onChange:k}),C&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(js,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:$=>h($.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:f,onChange:$=>p($.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),P&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(gr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||C)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ju,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(C&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:x,onChange:$=>v($.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),a.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:a.map(($,G)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[$.isZip?i.jsx(js,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(VC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:$.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[($.file.size/1024/1024).toFixed(2)," MB",$.isZip&&$.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),$.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:$.extractedCount})]})]})]}),$.status==="pending"&&i.jsx("button",{onClick:()=>M(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Lt,{className:"w-4 h-4 text-bambu-gray"})}),$.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),$.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),$.status==="error"&&i.jsx("span",{title:$.error,children:i.jsx(mi,{className:"w-4 h-4 text-red-500"})})]},G))}),D&&i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:L}),B>0&&i.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:B})]})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:r(D?"common.close":"common.cancel")}),!D&&i.jsx(Ce,{onClick:E,disabled:U===0||c,children:c?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",U>0?`(${U})`:""]})})]})]})})}function Zie({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[x?i.jsx("button",{onClick:g=>{g.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(pi,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Zl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[i.jsx(jh,{className:"w-3 h-3"}),t.project_name?i.jsx(uX,{className:"w-3 h-3"}):i.jsx(js,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(jh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Th,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(jh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&i.jsx("div",{children:t.children.map(g=>i.jsx(Zie,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},g.id))})]})}function aF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function wJe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[g,y]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(hf,{className:"w-12 h-12 text-bambu-gray/30"}),i.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ul(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Wn,{className:"w-3 h-3"}),Qs(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(gr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>y(!g),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Th,{className:"w-4 h-4 text-bambu-gray"})}),g&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),i.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&aF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(gr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&aF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Wn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(Ja,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(da,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ju,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(a(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function SJe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Ir(),[l]=BC(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(null),[M,C]=w.useState(null),[j,P]=w.useState(null),[E,U]=w.useState(null),[L,B]=w.useState(null),[D,$]=w.useState(null),[G,z]=w.useState({}),[W,X]=w.useState(null),[ae,H]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[K,te]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[Z,ve]=w.useState(()=>{const Ue=localStorage.getItem("library-sidebar-width");return Ue?parseInt(Ue,10):256}),[ce,ee]=w.useState(!1),je=w.useRef(null);w.useEffect(()=>{if(!ce)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ue=yt=>{if(!je.current)return;const Gt=je.current.parentElement?.getBoundingClientRect();if(!Gt)return;const Cn=yt.clientX-Gt.left,vr=Math.min(500,Math.max(200,Cn));ve(vr)},bt=()=>{ee(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(Z))};return document.addEventListener("mousemove",Ue),document.addEventListener("mouseup",bt),()=>{document.removeEventListener("mousemove",Ue),document.removeEventListener("mouseup",bt),document.body.style.userSelect="",document.body.style.cursor=""}},[ce,Z]);const[he,oe]=w.useState(""),[_e,ie]=w.useState("all"),[ze,V]=w.useState(""),[Y,me]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Q,se]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),de=xne();w.useEffect(()=>{const Ue=l.get("folder");if(Ue){const bt=parseInt(Ue,10);h(bt)}},[l]);const{data:Le}=Je({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:Ne,isLoading:be}=Je({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:O,isLoading:R}=Je({queryKey:["library-files",d],queryFn:()=>ne.getLibraryFiles(d,d===null)}),{data:q}=Je({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:J}=Je({queryKey:["users"],queryFn:()=>ne.getUsers()}),fe=w.useMemo(()=>{if(!O)return[];const Ue=new Set(O.map(bt=>bt.file_type));return Array.from(Ue).sort()},[O]),le=w.useMemo(()=>{if(!O)return[];let Ue=[...O];if(he.trim()){const bt=he.toLowerCase();Ue=Ue.filter(yt=>yt.filename.toLowerCase().includes(bt)||yt.print_name&&yt.print_name.toLowerCase().includes(bt))}if(_e!=="all"&&(Ue=Ue.filter(bt=>bt.file_type===_e)),ze.trim()){const bt=ze.toLowerCase();Ue=Ue.filter(yt=>yt.created_by_username&&yt.created_by_username.toLowerCase().includes(bt))}return Ue.sort((bt,yt)=>{let Gt=0;switch(Y){case"name":Gt=(bt.print_name||bt.filename).localeCompare(yt.print_name||yt.filename);break;case"date":Gt=new Date(bt.created_at).getTime()-new Date(yt.created_at).getTime();break;case"size":Gt=bt.file_size-yt.file_size;break;case"type":Gt=bt.file_type.localeCompare(yt.file_type);break;case"prints":Gt=bt.print_count-yt.print_count;break}return Q==="asc"?Gt:-Gt}),Ue},[O,he,_e,ze,Y,Q]),Be=w.useMemo(()=>{if(!q||!Le)return!1;const Ue=(Le.library_disk_warning_gb||5)*1024*1024*1024;return q.disk_free_bytes<Ue},[q,Le]),Ie=st({mutationFn:Ue=>ne.createLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ue=>n(Ue.message,"error")}),Ke=st({mutationFn:Ue=>ne.deleteLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===M?.id&&h(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),Oe=st({mutationFn:Ue=>ne.deleteLibraryFile(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Ue=>Ue.filter(bt=>bt!==M?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),pe=st({mutationFn:Ue=>ne.bulkDeleteLibrary(Ue,[]),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:bt.length}),"success"),p([]),C(null)},onError:Ue=>{C(null),n(Ue.message,"error")}}),xe=st({mutationFn:({fileIds:Ue,folderId:bt})=>ne.moveLibraryFiles(Ue,bt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ue=>n(Ue.message,"error")}),ke=st({mutationFn:({id:Ue,data:bt})=>ne.updateLibraryFolder(Ue,bt),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const yt=bt.data.project_id===0&&bt.data.archive_id===0;n(t(yt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ue=>n(Ue.message,"error")}),ge=st({mutationFn:({id:Ue,filename:bt})=>ne.updateLibraryFile(Ue,{filename:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ue=>{$(null),n(Ue.message,"error")}}),we=st({mutationFn:({id:Ue,name:bt})=>ne.updateLibraryFolder(Ue,{name:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ue=>{$(null),n(Ue.message,"error")}}),qe=st({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Date.now(),yt={};Ue.results.forEach(Gt=>{Gt.success&&(yt[Gt.file_id]=bt)}),z(Gt=>({...Gt,...yt}))}Ue.succeeded>0&&Ue.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ue.succeeded}),"success"):Ue.succeeded>0&&Ue.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ue.succeeded,failed:Ue.failed}),"success"):Ue.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),Ee=st({mutationFn:Ue=>ne.batchGenerateStlThumbnails({file_ids:[Ue]}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Ue.results[0]?.file_id;bt&&z(yt=>({...yt,[bt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),tt=w.useCallback(Ue=>{const bt=Ue.toLowerCase();return bt.endsWith(".gcode")||bt.includes(".gcode.")},[]),De=w.useMemo(()=>O?O.filter(Ue=>f.includes(Ue.id)&&tt(Ue.filename)):[],[O,f,tt]),We=w.useCallback(Ue=>{p(bt=>bt.includes(Ue)?bt.filter(yt=>yt!==Ue):[...bt,Ue])},[]),Ae=w.useCallback(()=>{le.length>0&&p(le.map(Ue=>Ue.id))},[le]),Re=w.useCallback(()=>{p([])},[]),$e=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ht=Ue=>{ne.downloadLibraryFile(Ue).catch(bt=>{console.error("Library file download failed:",bt)})},At=()=>{M&&(M.type==="file"?Oe.mutate(M.id):M.type==="folder"?Ke.mutate(M.id):M.type==="bulk"&&pe.mutate(f))},Dt=Ke.isPending||Oe.isPending||pe.isPending,It=Ue=>{H(Ue),localStorage.setItem("library-view-mode",Ue)},kt=be||R;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Zl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>It("grid"),className:`p-1.5 rounded transition-colors ${ae==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(h0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>It("list"),className:`p-1.5 rounded transition-colors ${ae==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(WC,{className:"w-4 h-4"})})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>qe.mutate(),disabled:qe.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[qe.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ju,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(vme,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Be&&q&&Le&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ul(q.disk_free_bytes),total:ul(q.disk_total_bytes),threshold:Le.library_disk_warning_gb})})]})]}),q&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(VC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:q.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Zl,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:q.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Vb,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ul(q.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${Be?"text-amber-500":"text-white"}`,children:ul(q.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:Ue=>h(Ue.target.value?parseInt(Ue.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),Ne&&(()=>{const Ue=(bt,yt=0)=>{const Gt=[];for(const Cn of bt)Gt.push({id:Cn.id,name:Cn.name,fileCount:Cn.file_count,depth:yt}),Cn.children.length>0&&Gt.push(...Ue(Cn.children,yt+1));return Gt};return Ue(Ne).map(bt=>i.jsxs("option",{value:bt.id,children:["│ ".repeat(bt.depth),"📂 ",bt.name," ",bt.fileCount>0?`(${bt.fileCount})`:""]},bt.id))})()]})}),i.jsxs("div",{ref:je,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${Z}px`},children:[i.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${ce?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ue=>{Ue.preventDefault(),ee(!0)},onDoubleClick:()=>{ve(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${ce?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const Ue=!K;te(Ue),localStorage.setItem("library-wrap-folders",String(Ue))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${K?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(K?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[i.jsx(hf,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),Ne?.map(Ue=>i.jsx(Zie,{folder:Ue,selectedFolderId:d,onSelect:h,onDelete:bt=>C({type:"folder",id:bt}),onLink:A,onRename:bt=>$({type:"folder",id:bt.id,name:bt.name}),wrapNames:K,hasPermission:r,t},Ue.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[O&&O.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:he,onChange:Ue=>oe(Ue.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(qC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:_e,onChange:Ue=>ie(Ue.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),fe.map(Ue=>i.jsx("option",{value:Ue,children:Ue.toUpperCase()},Ue))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:ze,onChange:Ue=>V(Ue.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${ze?"pr-7":""}`,style:ze?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),ze&&i.jsx("button",{onClick:()=>V(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Lt,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:J?.map(Ue=>i.jsx("option",{value:Ue.username},Ue.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:Y,onChange:Ue=>{const bt=Ue.target.value;me(bt),localStorage.setItem("library-sort-field",bt)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>se(Ue=>{const bt=Ue==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",bt),bt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Q==="asc"?"fileManager.ascending":"fileManager.descending"),children:Q==="asc"?i.jsx(Ide,{className:"w-4 h-4 text-white"}):i.jsx(Ede,{className:"w-4 h-4 text-white"})})]}),(he||_e!=="all"||ze)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:le.length,total:O.length})})]}),le.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===le.length&&f.length>0?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(vl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Ae,children:[i.jsx(oo,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[De.length===1&&i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>U(De[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(io,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),De.length===1&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>B(De[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Wn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(Mfe,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>{f.length===1?C({type:"file",id:f[0]}):C({type:"bulk",id:0,count:f.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(Lt,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),kt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):O?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(hf,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Gn,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):le.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(xr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ce,{variant:"secondary",onClick:()=>{oe(""),ie("all")},children:t("fileManager.clearFilters")})]}):ae==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:le.map(Ue=>i.jsx(wJe,{file:Ue,isSelected:f.includes(Ue.id),isMobile:de,t,onSelect:We,onDelete:bt=>C({type:"file",id:bt}),onDownload:ht,onAddToQueue:bt=>{const yt=O?.find(Gt=>Gt.id===bt);yt&&B(yt)},onPrint:P,onPreview3d:X,onRename:bt=>$({type:"file",id:bt.id,name:bt.filename}),onGenerateThumbnail:bt=>Ee.mutate(bt.id),thumbnailVersion:G[Ue.id],hasPermission:r,canModify:s,authEnabled:o},Ue.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),le.map(Ue=>i.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Ue.id)?"bg-bambu-green/10":""}`,onClick:()=>We(Ue.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ue.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ue.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ue.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(hf,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ue.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:Ue.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:Ue.print_name||Ue.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ue.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(td,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:Ue.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ue.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ue.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ue.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ue.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ul(Ue.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:Ue.print_count>0?`${Ue.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:bt=>bt.stopPropagation(),children:[aF(Ue.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&P(Ue),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(gr,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&B(Ue)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Wn,{className:"w-4 h-4"})})]}),(Ue.file_type==="3mf"||Ue.file_type==="gcode"||Ue.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&X(Ue),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(Ja,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&ht(Ue.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(da,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&$({type:"file",id:Ue.id,name:Ue.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ue.created_by_id),children:i.jsx($a,{className:"w-4 h-4"})}),Ue.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&Ee.mutate(Ue.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ee.isPending||!s("library","update",Ue.created_by_id),children:i.jsx(Ju,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",Ue.created_by_id)&&C({type:"file",id:Ue.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ue.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ue.created_by_id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},Ue.id))]})})]})]}),x&&i.jsx(gJe,{parentId:d,onClose:()=>v(!1),onSave:Ue=>Ie.mutate(Ue),isLoading:Ie.isPending,t}),g&&Ne&&i.jsx(xJe,{folders:Ne,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Ue=>xe.mutate({fileIds:f,folderId:Ue}),isLoading:xe.isPending,t}),_&&i.jsx(vJe,{folderId:d,onClose:()=>N(!1),onUploadComplete:$e,t}),k&&i.jsx(yJe,{folder:k,onClose:()=>A(null),onLink:Ue=>ke.mutate({id:k.id,data:Ue}),isLoading:ke.isPending,t}),M&&i.jsx(gn,{title:M.type==="folder"?t("fileManager.deleteFolder"):M.type==="bulk"?t("fileManager.deleteFilesCount",{count:M.count}):t("fileManager.deleteFile"),message:M.type==="folder"?t("fileManager.deleteFolderConfirm"):M.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:M.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Dt,loadingText:t("fileManager.deleting"),onConfirm:At,onCancel:()=>C(null)}),j&&i.jsx(Xu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>P(null),onSuccess:()=>{P(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),E&&i.jsx(Xu,{mode:"reprint",libraryFileId:E.id,archiveName:E.print_name||E.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&i.jsx(Xu,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),W&&i.jsx(g4,{libraryFileId:W.id,title:W.print_name||W.filename,fileType:W.file_type,onClose:()=>X(null)}),D&&i.jsx(bJe,{type:D.type,currentName:D.name,onClose:()=>$(null),onSave:Ue=>{D.type==="file"?ge.mutate({id:D.id,filename:Ue}):we.mutate({id:D.id,name:Ue})},isLoading:ge.isPending||we.isPending,t})]})}const R2=5,_Je=2e3,NJe=3e4,CJe=5e3;function kJe(){const{t}=Ot(),e=en(),{showToast:n}=an(),{hasPermission:r}=Ir(),{printerId:a}=l0(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(0),[M,C]=w.useState(!1),[j,P]=w.useState(0),[E,U]=w.useState(1),[L,B]=w.useState({x:0,y:0}),[D,$]=w.useState(!1),[G,z]=w.useState({x:0,y:0}),[W,X]=w.useState(null),[ae,H]=w.useState(null),K=w.useRef(null),te=w.useRef(null),Z=w.useRef(null),ve=w.useRef(null),ce=w.useRef(null),{data:ee}=Je({queryKey:["printer",s],queryFn:()=>ne.getPrinter(s),enabled:s>0}),{data:je}=Je({queryKey:["printerStatus",s],queryFn:()=>ne.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),he=st({mutationFn:xe=>ne.setChamberLight(s,xe),onMutate:async xe=>{await e.cancelQueries({queryKey:["printerStatus",s]});const ke=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],ge=>({...ge,chamber_light:xe})),{previousStatus:ke}},onSuccess:(xe,ke)=>{n(`Chamber light ${ke?"on":"off"}`)},onError:(xe,ke,ge)=>{ge?.previousStatus&&e.setQueryData(["printerStatus",s],ge.previousStatus),n(xe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(je?.state==="RUNNING"||je?.state==="PAUSE")&&(je?.printable_objects_count??0)>=2;w.useEffect(()=>(ee&&(document.title=`${ee.name} - Camera`),()=>{document.title="Bambuddy"}),[ee]);const _e=w.useRef(!1);w.useEffect(()=>{const xe=`/api/v1/printers/${s}/camera/stop`;_e.current=!1;const ke=()=>{if(s>0&&!_e.current){_e.current=!0;const qe={},Ee=rd();Ee&&(qe.Authorization=`Bearer ${Ee}`),fetch(xe,{method:"POST",keepalive:!0,headers:qe}).catch(()=>{})}},ge=()=>{ke()};window.addEventListener("beforeunload",ge);const we=K.current;return()=>{window.removeEventListener("beforeunload",ge),we&&(we.src=""),ke()}},[s]),w.useEffect(()=>{if(f&&!g){const ke=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(ke)}},[o,f,x,g]),w.useEffect(()=>{const xe=()=>{const ke=!!document.fullscreenElement;N(ke),U(1),B({x:0,y:0}),o==="stream"&&!g&&(K.current&&(K.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",xe),()=>document.removeEventListener("fullscreenchange",xe)},[o,g]),w.useEffect(()=>{let xe;const ke=()=>{clearTimeout(xe),xe=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",ke),()=>{clearTimeout(xe),window.removeEventListener("resize",ke)}},[]),w.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),ce.current&&clearInterval(ce.current)},[]);const ie=w.useCallback(()=>{if(k>=R2){C(!1),h(!0);return}const xe=Math.min(_Je*Math.pow(2,k),NJe);C(!0),P(Math.ceil(xe/1e3)),ve.current=setInterval(()=>{P(ke=>ke<=1?(ve.current&&clearInterval(ve.current),0):ke-1)},1e3),Z.current=setTimeout(()=>{A(ke=>ke+1),C(!1),p(!0),h(!1),K.current&&(K.current.src=""),v(Date.now())},xe)},[k]);w.useEffect(()=>{if(o!=="stream"||f||M||g){ce.current&&(clearInterval(ce.current),ce.current=null);return}return ce.current=setInterval(async()=>{try{const xe=await ne.getCameraStatus(s);(xe.stalled||!xe.active&&!d)&&(console.log(`Stream issue detected: stalled=${xe.stalled}, active=${xe.active}, reconnecting...`),ce.current&&(clearInterval(ce.current),ce.current=null),p(!1),ie())}catch{}},CJe),()=>{ce.current&&(clearInterval(ce.current),ce.current=null)}},[o,f,d,M,g,s,ie]);const ze=()=>{p(!1),o==="stream"&&k<R2?ie():h(!0)},V=()=>{if(p(!1),h(!1),A(0),C(!1),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&!localStorage.getItem("cameraWindowState")){const xe=K.current,ke=xe.naturalWidth,ge=xe.naturalHeight;if(ke>0&&ge>0){const Ee=window.outerWidth-window.innerWidth,tt=window.outerHeight-window.innerHeight,De=ke+16+Ee,We=ge+45+16+tt;try{window.resizeTo(De,We)}catch{}}}},Y=()=>{if(s>0){const xe={},ke=rd();ke&&(xe.Authorization=`Bearer ${ke}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:xe}).catch(()=>{})}},me=xe=>{o===xe||g||(y(!0),p(!0),h(!1),A(0),C(!1),U(1),B({x:0,y:0}),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&(K.current.src=""),o==="stream"&&Y(),setTimeout(()=>{l(xe),v(Date.now()),y(!1)},100))},Q=()=>{g||(y(!0),p(!0),h(!1),A(0),C(!1),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&(K.current.src=""),o==="stream"&&Y(),setTimeout(()=>{v(Date.now()),y(!1)},100))},se=()=>{te.current&&(document.fullscreenElement?document.exitFullscreen():te.current.requestFullscreen())},de=()=>{U(xe=>Math.min(xe+.5,4))},Le=()=>{U(xe=>{const ke=Math.max(xe-.5,1);return ke===1&&B({x:0,y:0}),ke})},Ne=xe=>{xe.preventDefault(),xe.deltaY<0?de():Le()},be=xe=>{E>1&&(xe.preventDefault(),$(!0),z({x:xe.clientX-L.x,y:xe.clientY-L.y}))},O=w.useCallback(()=>{if(!te.current)return{x:300,y:200};const xe=te.current.getBoundingClientRect(),ke=xe.width*(E-1)/2,ge=xe.height*(E-1)/2;return{x:Math.max(50,ke),y:Math.max(50,ge)}},[E]),R=xe=>{if(D&&E>1){const ke=xe.clientX-G.x,ge=xe.clientY-G.y,we=O();B({x:Math.max(-we.x,Math.min(we.x,ke)),y:Math.max(-we.y,Math.min(we.y,ge))})}},q=()=>{$(!1)},J=xe=>{if(xe.length<2)return 0;const ke=xe[0].clientX-xe[1].clientX,ge=xe[0].clientY-xe[1].clientY;return Math.sqrt(ke*ke+ge*ge)},fe=xe=>xe.length<2?{x:xe[0].clientX,y:xe[0].clientY}:{x:(xe[0].clientX+xe[1].clientX)/2,y:(xe[0].clientY+xe[1].clientY)/2},le=xe=>{xe.touches.length===2?(xe.preventDefault(),X(J(xe.touches)),H(fe(xe.touches))):xe.touches.length===1&&E>1&&(xe.preventDefault(),$(!0),z({x:xe.touches[0].clientX-L.x,y:xe.touches[0].clientY-L.y}))},Be=xe=>{if(xe.touches.length===2&&W!==null){xe.preventDefault();const ke=J(xe.touches),ge=ke/W;U(qe=>{const Ee=Math.max(1,Math.min(4,qe*ge));return Ee===1&&B({x:0,y:0}),Ee}),X(ke);const we=fe(xe.touches);if(ae){const qe=O();B(Ee=>({x:Math.max(-qe.x,Math.min(qe.x,Ee.x+(we.x-ae.x))),y:Math.max(-qe.y,Math.min(qe.y,Ee.y+(we.y-ae.y)))}))}H(we)}else if(xe.touches.length===1&&D&&E>1){xe.preventDefault();const ke=xe.touches[0].clientX-G.x,ge=xe.touches[0].clientY-G.y,we=O();B({x:Math.max(-we.x,Math.min(we.x,ke)),y:Math.max(-we.y,Math.min(we.y,ge))})}},Ie=xe=>{xe.touches.length<2&&(X(null),H(null)),xe.touches.length===0&&$(!1)},Ke=()=>{U(1),B({x:0,y:0})},Oe=g?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,pe=f||g||M;return s?i.jsxs("div",{ref:te,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(cb,{className:"w-4 h-4"}),ee?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>me("stream"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>me("snapshot"),disabled:pe,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>he.mutate(!je?.chamber_light),disabled:!je?.connected||he.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${je?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(lL,{on:je?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!oe||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(hk,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:Q,disabled:pe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Ar,{className:`w-4 h-4 text-bambu-gray ${pe?"animate-spin":""}`})}),i.jsx("button",{onClick:se,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(xX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(bfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:Ne,onMouseMove:R,onMouseUp:q,onMouseLeave:q,onTouchStart:le,onTouchMove:Be,onTouchEnd:Ie,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||g)&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Ar,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(jf,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:k+1,max:R2})}),i.jsx("button",{onClick:Q,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Tn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:Q,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:K,src:Oe,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${E}) translate(${L.x/E}px, ${L.y/E}px)`,cursor:E>1?D?"grabbing":"grab":"default"},onError:Oe?ze:void 0,onLoad:Oe?V:void 0,onMouseDown:be,draggable:!1},x),i.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[i.jsx("button",{onClick:Le,disabled:E<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(jF,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:Ke,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(E*100),"%"]}),i.jsx("button",{onClick:de,disabled:E>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(EF,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(cL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function AJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function TJe(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function MJe(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function PJe(){const{printerId:t}=l0(),[e]=BC(),{t:n}=Ot(),r=en(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>AJe(e),[e]),c=MJe(l.size),{data:u}=Je({queryKey:["printer",a],queryFn:()=>ne.getPrinter(a),enabled:a>0}),{data:d}=Je({queryKey:["printerStatus",a],queryFn:()=>ne.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:h}=Je({queryKey:["settings"],queryFn:ne.getSettings}),f=h?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=k=>{try{const A=JSON.parse(k.data);A.type==="printer_status"&&A.printer_id===a&&r.setQueryData(["printerStatus",a],A.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const p=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const x=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,g=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:p},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(gr,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:TJe(d,n)}),l.showProgress&&x&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),x&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(fi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Lu,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Qs(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Wn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",DF(d.remaining_time,f,n)]})]})]})]}),!x&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function EJe(){const{t}=Ot(),{id:e}=l0(),{mode:n}=tp(),{data:r,isLoading:a,error:s}=Je({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Tn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function sK(){const{id:t}=l0(),e=rc(),n=en(),{t:r}=Ot(),{showToast:a}=an(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,h]=w.useState([]),[f,p]=w.useState(""),[x,v]=w.useState(!1),{data:g,isLoading:y}=Je({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=Je({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&g&&!x&&(l(g.name),u(g.description||""),h(g.permissions),v(!0));const k=st({mutationFn:z=>ne.createGroup(z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),A=st({mutationFn:z=>ne.updateGroup(Number(t),z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),M=k.isPending||A.isPending,C=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?A.mutate({name:o!==g?.name?o:void 0,description:c,permissions:d}):k.mutate({name:o,description:c||void 0,permissions:d})},j=z=>{h(W=>W.includes(z)?W.filter(X=>X!==z):[...W,z])},P=(z,W)=>{const X=z.permissions.map(ae=>ae.value);h(ae=>{const H=ae.filter(K=>!X.includes(K));return W?[...H,...X]:H})},E=z=>z.permissions.every(W=>d.includes(W.value)),U=z=>{const W=z.permissions.filter(X=>d.includes(X.value)).length;return W>0&&W<z.permissions.length},L=()=>{_&&h(_.all_permissions)},B=()=>{h([])},D=f.toLowerCase(),$=w.useMemo(()=>_?D?_.categories.map(z=>({...z,permissions:z.permissions.filter(W=>W.label.toLowerCase().includes(D))})).filter(z=>z.permissions.length>0):_.categories:[],[_,D]),G=_?.all_permissions.length??0;return y||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx(_F,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:z=>l(z.target.value),disabled:s&&g?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",G]}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:L,children:r("groups.editor.selectAll")}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:B,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:f,onChange:z=>p(z.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),$.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:$.map(z=>{const W=_.categories.find(te=>te.name===z.name),X=W.permissions.filter(te=>d.includes(te.value)).length,ae=W.permissions.length,H=E(W),K=U(W);return i.jsxs(wt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>P(W,!H),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${H?"bg-bambu-green border-bambu-green":K?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[H&&i.jsx(aa,{className:"w-3 h-3 text-white"}),K&&!H&&i.jsx(_1,{className:"w-3 h-3 text-white"})]}),i.jsx(l3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:z.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[X,"/",ae]})]}),i.jsx("div",{className:"p-3 space-y-1",children:z.permissions.map(te=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(te.value),onChange:()=>j(te.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:te.label})]},te.value))})]},z.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ce,{onClick:C,disabled:M||!o.trim(),children:M?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const oK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function jJe(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const DJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],RJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],hv=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Jie=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],FJe=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],lK=[...Jie,...FJe],ese="bambuddy-recent-colors",LJe=8,OJe=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Ib(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of hv)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of hv){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function IJe(t,e){const n=new Set(RJe);for(const r of t){const{brand:a}=Ib(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Ib(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function zJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function UJe(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=zJe(n);if(r.length>0)return r}return OJe}function BJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function HJe(){try{const t=localStorage.getItem(ese);if(t)return JSON.parse(t)}catch{}return[]}function $Je(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,LJe);try{localStorage.setItem(ese,JSON.stringify(r))}catch{}return r}function F2(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Ib(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function VJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:h,onQuantityChange:f,errors:p}){const{t:x}=Ot(),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,M]=w.useState(!1),[C,j]=w.useState(""),[P,E]=w.useState(""),[U,L]=w.useState(""),[B,D]=w.useState(String(t.label_weight)),[$,G]=w.useState(!1),z=w.useRef(null),W=w.useRef(null),X=w.useRef(null),ae=w.useRef(null);w.useEffect(()=>{const ce=ee=>{z.current&&!z.current.contains(ee.target)&&g(!1),ae.current&&!ae.current.contains(ee.target)&&M(!1),W.current&&!W.current.contains(ee.target)&&_(!1),X.current&&!X.current.contains(ee.target)&&k(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[]);const H=w.useMemo(()=>{if(!a)return l;const ce=a.toLowerCase();return l.filter(ee=>ee.displayName.toLowerCase().includes(ce)||ee.code.toLowerCase().includes(ce))},[l,a]),K=w.useMemo(()=>{if(!C)return c;const ce=C.toLowerCase();return c.filter(je=>je.toLowerCase().includes(ce)).sort((je,he)=>{const oe=je.toLowerCase()===ce,_e=he.toLowerCase()===ce;return oe&&!_e?-1:!oe&&_e?1:je.localeCompare(he)})},[c,C]),te=w.useMemo(()=>{if(!P)return hv;const ce=P.toLowerCase();return hv.filter(ee=>ee.toLowerCase().includes(ce))},[P]),Z=w.useMemo(()=>{if(!U)return u;const ce=U.toLowerCase();return u.filter(je=>je.toLowerCase().includes(ce)).sort((je,he)=>{const oe=je.toLowerCase()===ce,_e=he.toLowerCase()===ce;return oe&&!_e?-1:!oe&&_e?1:je.localeCompare(he)})},[U,u]);w.useEffect(()=>{$||D(String(t.label_weight))},[t.label_weight,$]);const ve=ce=>{e("slicer_filament",ce.code),s(ce.displayName),g(!1);const ee=Ib(ce.name);ee.material&&e("material",ee.material),ee.brand&&e("brand",ee.brand),ee.variant&&e("subtype",ee.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-3 h-3 animate-spin"})," ",x("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx($b,{className:"w-3 h-3 text-bambu-green"})," ",x("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(Mhe,{className:"w-3 h-3"})," ",x("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:z,children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:x("inventory.searchPresets"),value:a,onChange:ce=>{s(ce.target.value),g(!0)},onFocus:()=>{g(!0),s("")}}),v&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:H.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noPresetsFound")}):H.map(ce=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${o?.code===ce.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>ve(ce),children:[i.jsx("span",{className:"truncate",children:ce.displayName}),i.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:ce.code})]},ce.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[x("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),p?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:ae,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:x("inventory.selectMaterial"),value:A?U:t.material,onChange:ce=>{L(ce.target.value),M(!0)},onFocus:()=>{M(!0),L("")}}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),A&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[Z.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):Z.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",ce),M(!1),L("")},children:ce},ce)),U&&!Z.includes(U)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",U),M(!1),L("")},children:x("inventory.useCustomMaterial",{material:U})})]})]}),p?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:W,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:x("inventory.searchBrand"),value:y?C:t.brand,onChange:ce=>{j(ce.target.value),_(!0)},onFocus:()=>{_(!0),j("")}}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),y&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[K.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):K.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",ce),_(!1),j("")},children:ce},ce)),C&&!K.includes(C)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",C),_(!1),j("")},children:x("inventory.useCustomBrand",{brand:C})})]})]}),p?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:X,children:[i.jsx("input",{type:"text",value:N?P:t.subtype,onChange:ce=>{E(ce.target.value),k(!0)},onFocus:()=>{k(!0),E("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[te.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):te.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",ce),k(!1),E("")},children:ce},ce)),P&&!hv.some(ce=>ce.toLowerCase()===P.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",P),k(!1),E("")},children:x("inventory.useCustomBrand",{brand:P})})]})]}),p?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:B,min:0,onFocus:()=>G(!0),onChange:ce=>D(ce.target.value),onBlur:()=>{G(!1);const ce=B.trim(),ee=Number(ce);if(!ce||!Number.isFinite(ee)||ee<0){D(String(t.label_weight));return}const je=Math.round(ee);e("label_weight",je),D(String(je))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:h,min:1,max:100,onChange:ce=>{const ee=Math.max(1,Math.min(100,parseInt(ce.target.value)||1));f(ee)}})]})]})}function qJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Ot(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,_)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:y})},p=w.useMemo(()=>{if(a.length===0)return[];const y=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!_)return[];const k=y?y.toLowerCase().split(/[\s\-_]+/).filter(C=>C.length>=2):[],A=C=>{if(k.length===0)return!0;const j=C.toLowerCase();return k.some(P=>j.includes(P))};if(y&&!_){const C=a.filter(j=>A(j.manufacturer));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}const M=_&&N?`${_} ${N}`:"";if(M){const C=a.filter(P=>A(P.manufacturer)&&P.material?.toLowerCase()===M);if(C.length>0)return C.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6),manufacturer:P.manufacturer,material:typeof P.material=="string"?P.material:void 0}));const j=M.replace(/\+$/,"");if(j!==M){const P=a.filter(E=>A(E.manufacturer)&&E.material?.toLowerCase()===j);if(P.length>0)return P.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6),manufacturer:E.manufacturer,material:typeof E.material=="string"?E.material:void 0}))}}if(_){const C=a.filter(j=>A(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(_)));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),x=w.useMemo(()=>{if(!c)return p;if(p.length===0)return[];const y=c.toLowerCase();return p.filter(N=>N.name.toLowerCase().includes(y)||(N.manufacturer?.toLowerCase().includes(y)??!1)||(N.material?.toLowerCase().includes(y)??!1))},[c,p]),v=p.length>0,g=w.useMemo(()=>c?lK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?lK:Jie,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Wn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:y=>u(y.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name})},`${y.hex}-${y.name}-${y.manufacturer??""}`)),x.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(yl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(Pn,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.name})},y.hex)),g.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:y=>e("color_name",y.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:y=>{const _=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const _=y.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function GJe({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Ot(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const v=g=>{d.current&&!d.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(g=>g.weight===e);if(r){const g=t.find(y=>y.id===r);if(g&&g.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const f=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(v)||g.weight.toString().includes(v))},[t,c]),p=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),x=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(g=>g.id===r);if(v)return v.name}return p.length>0?p[0].name:""},[o,c,r,t,p]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(m0,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:h,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:x,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:f.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):f.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const g=parseInt(v.target.value);!isNaN(g)&&g>=0&&n(g)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function WJe({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Ot(),{showToast:s}=an(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,h]=w.useState(""),[f,p]=w.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+x;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{f||h(String(x))},[f,x]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(GJe,{catalog:n,value:t.core_weight,onChange:g=>e("core_weight",g),catalogId:t.core_weight_catalog_id,onCatalogIdChange:g=>e("core_weight_catalog_id",g)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>p(!0),onChange:g=>{h(g.target.value)},onBlur:()=>{p(!1);const g=d.trim(),y=Number(g);if(!g||!Number.isFinite(y)||y<0||y>t.label_weight){h(String(x));return}const _=Math.round(y);e("weight_used",Math.max(0,t.label_weight-_)),h(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:g=>{l(g.target.value)},onBlur:()=>{u(!1);const g=o.trim(),y=Number(g),_=t.core_weight,N=t.core_weight+t.label_weight;if(!g||!Number.isFinite(y)||y<_||y>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const k=Math.round(y),A=Math.max(0,Math.min(t.label_weight,k-t.core_weight));e("weight_used",Math.max(0,t.label_weight-A)),l(String(k))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:g=>{const y=g.target.value===""?null:parseFloat(g.target.value);e("cost_per_kg",y)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:g=>e("note",g.target.value)})]})]})}function KJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Ot(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,g=`${f}:${x??"null"}`;r(y=>{const _=new Set(y);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const k=N.split(":");`${k[0]}:${k[2]}`===g&&_.delete(N)}_.add(v)}return _})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>F2(y,t)),g=new Map;for(const y of v){const _=`${y.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(y)}for(const[y,_]of g)if(_.length>0){const k=[..._].sort((A,M)=>M.k_value-A.k_value)[0];f.add(`${p.id}:${k.cali_idx}:${y}`)}}r(f)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>F2(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(hb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=a.has(String(f.id)),v=p.filter(k=>F2(k,t)),g=v.length,y=v.some(k=>k.extruder_id!==void 0&&k.extruder_id!==null&&k.extruder_id>0),_=v.filter(k=>k.extruder_id===1),N=v.filter(k=>k.extruder_id===0||k.extruder_id===void 0||k.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(f.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[x?i.jsx(Pn,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:f.name}),g>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[g," ",o(g!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?g===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(k=>h(f,k))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(k=>h(f,k))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(k=>h(f,k))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function XJe(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const YJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function QJe({spoolId:t}){const{t:e}=Ot(),n=en(),{showToast:r}=an(),{data:a,isLoading:s}=Je({queryKey:["spool-usage",t],queryFn:()=>ne.getSpoolUsageHistory(t)}),o=st({mutationFn:()=>ne.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Wn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:XJe(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:YJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function ZJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Ot(),o=en(),{showToast:l}=an(),c=!!n,[u,d]=w.useState(oK),[h,f]=w.useState({}),[p,x]=w.useState("filament"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(1),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState([]),[U,L]=w.useState(""),[B,D]=w.useState([]),[$,G]=w.useState([]),[z,W]=w.useState([]),[X,ae]=w.useState([]),[H,K]=w.useState([]),[te,Z]=w.useState(new Set),[ve,ce]=w.useState(new Set),ee=r.length>0?r:H,je=w.useMemo(()=>te.size,[te]);w.useEffect(()=>{ae(HJe())},[]),w.useEffect(()=>{t&&((async()=>{j(!0);try{const fe=await ne.getCloudStatus();if(M(fe.is_authenticated),fe.is_authenticated){const le=await ne.getFilamentPresets();E(le)}}catch(fe){console.error("Failed to fetch cloud presets:",fe),M(!1)}finally{j(!1)}})(),ne.getSpoolCatalog().then(D).catch(console.error),ne.getColorCatalog().then(W).catch(console.error),ne.getLocalPresets().then(fe=>G(fe.filament)).catch(console.error),r.length===0&&(async()=>{try{const fe=await ne.getPrinters(),le=await Promise.all(fe.map(Ie=>ne.getPrinterStatus(Ie.id).catch(()=>null))),Be=[];for(let Ie=0;Ie<fe.length;Ie++){const Ke=fe[Ie],pe=le[Ie]?.connected??!1;let xe=[];if(pe)try{xe=(await ne.getKProfiles(Ke.id)).profiles.map(ge=>({cali_idx:ge.slot_id,filament_id:ge.filament_id,setting_id:ge.setting_id||"",name:ge.name,k_value:parseFloat(ge.k_value)||0,n_coef:parseFloat(ge.n_coef)||0,extruder_id:ge.extruder_id,nozzle_diameter:ge.nozzle_diameter}))}catch{}Be.push({printer:{...Ke,connected:pe},calibrations:xe})}K(Be)}catch(fe){console.error("Failed to fetch printer calibrations:",fe)}})())},[t,r.length]);const he=w.useMemo(()=>UJe(P,new Set,$),[P,$]),oe=w.useMemo(()=>{const J=IJe(P,$),fe=z.map(Be=>Be.manufacturer?.trim()).filter(Be=>!!Be),le=new Set([...J,...fe]);return Array.from(le).sort((Be,Ie)=>Be.localeCompare(Ie))},[P,$,z]),_e=w.useMemo(()=>{const J=z.map(le=>le.material?.trim()).filter(le=>!!le),fe=new Set([...DJe,...J]);return Array.from(fe).sort((le,Be)=>le.localeCompare(Be))},[z]),ie=w.useMemo(()=>{const J=[];for(const fe of z){const le=fe.manufacturer?.trim(),Be=fe.material?.trim();le&&Be&&J.push({brand:le,material:Be})}for(const fe of P){const le=Ib(fe.name);le.brand&&le.material&&J.push({brand:le.brand,material:le.material})}for(const fe of $){const le=Ib(fe.name),Be=fe.filament_vendor?.trim()||le.brand,Ie=le.material;Be&&Ie&&J.push({brand:Be,material:Ie})}return J},[P,z,$]),ze=w.useMemo(()=>{const J=new Map;for(const fe of ie){const le=fe.brand.toLowerCase(),Be=fe.material.toLowerCase();J.has(le)||J.set(le,new Set),J.get(le).add(Be)}return J},[ie]),V=w.useMemo(()=>{const J=new Map;for(const fe of ie){const le=fe.brand.toLowerCase(),Be=fe.material.toLowerCase();J.has(Be)||J.set(Be,new Set),J.get(Be).add(le)}return J},[ie]),Y=w.useMemo(()=>{if(!u.material)return oe;const J=u.material.toLowerCase(),fe=V.get(J);return!fe||fe.size===0?oe:oe.filter(le=>fe.has(le.toLowerCase()))},[oe,u.material,V]),me=w.useMemo(()=>{if(!u.brand)return _e;const J=u.brand.toLowerCase(),fe=ze.get(J);return!fe||fe.size===0?_e:_e.filter(le=>fe.has(le.toLowerCase()))},[_e,u.brand,ze]),Q=w.useMemo(()=>BJe(u.slicer_filament,he),[u.slicer_filament,he]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),L(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const J=new Set;for(const fe of n.k_profiles)fe.cali_idx!==null&&fe.cali_idx!==void 0&&J.add(`${fe.printer_id}:${fe.cali_idx}:${fe.extruder??"null"}`);Z(J)}else Z(new Set);else d(oK),L(""),Z(new Set),_(!1),k(1);f({}),x("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&ee.length>0&&ce(new Set(ee.map(J=>String(J.printer.id))))},[t,ee]);const se=(J,fe)=>{d(le=>({...le,[J]:fe})),J==="weight_used"&&g(!0),h[J]&&f(le=>({...le,[J]:void 0}))},de=J=>{ae(fe=>$Je(J,fe))},Le=st({mutationFn:J=>ne.createSpool(J),onSuccess:async J=>{te.size>0&&J?.id&&await O(J.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:J=>{l(J.message,"error")}}),Ne=st({mutationFn:({data:J,qty:fe})=>ne.bulkCreateSpools(J,fe),onSuccess:async J=>{if(te.size>0)for(const fe of J)await O(fe.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:J.length}),"success"),e()},onError:J=>{l(J.message,"error")}}),be=st({mutationFn:J=>ne.updateSpool(n.id,J),onSuccess:async()=>{n?.id&&await O(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:J=>{l(J.message,"error")}}),O=async J=>{if(te.size===0){try{await ne.saveSpoolKProfiles(J,[])}catch{}return}const fe=[];for(const le of te){const[Be,Ie,Ke]=le.split(":"),Oe=parseInt(Be),pe=parseInt(Ie),xe=Ke==="null"?0:parseInt(Ke),ke=ee.find(ge=>ge.printer.id===Oe);if(ke){const ge=ke.calibrations.find(we=>we.cali_idx===pe);ge&&fe.push({printer_id:Oe,extruder:xe,nozzle_diameter:ge.nozzle_diameter||"0.4",k_value:ge.k_value,name:ge.name||null,cali_idx:ge.cali_idx,setting_id:ge.setting_id||null})}}if(fe.length>0)try{await ne.saveSpoolKProfiles(J,fe)}catch(le){console.error("Failed to save K-profiles:",le)}};if(w.useEffect(()=>{if(!t)return;const J=fe=>{fe.key==="Escape"&&e()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[t,e]),!t)return null;const R=()=>{const J=jJe(u,y);if(!J.isValid){f(J.errors),(J.errors.slicer_filament||J.errors.material||J.errors.brand||J.errors.subtype)&&x("filament");return}const fe=Q?.displayName||U||null,le={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:fe,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(le.weight_used=u.weight_used),c?be.mutate(le):N>1?Ne.mutate({data:le,qty:N}):Le.mutate(le)},q=Le.isPending||Ne.isPending||be.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Lt,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nd,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!y),y||x("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${y?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${y?"translate-x-4":"translate-x-0.5"}`})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>x("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(XC,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!y&&i.jsxs("button",{onClick:()=>x("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Bde,{className:"w-4 h-4"}),s("inventory.paProfileTab"),je>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:je})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:p==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(VJe,{formData:u,updateField:se,cloudAuthenticated:A,loadingCloudPresets:C,presetInputValue:U,setPresetInputValue:L,selectedPresetOption:Q,filamentOptions:he,availableBrands:Y,availableMaterials:me,quickAdd:y,quantity:N,onQuantityChange:k,errors:h})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(qJe,{formData:u,updateField:se,recentColors:X,onColorUsed:de,catalogColors:z})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(WJe,{formData:u,updateField:se,spoolCatalog:B,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(QJe,{spoolId:n.id})})]}):i.jsx(KJe,{formData:u,updateField:se,printersWithCalibrations:ee,selectedProfiles:te,setSelectedProfiles:Z,expandedPrinters:ve,setExpandedPrinters:ce})}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ce,{onClick:R,disabled:q,children:q?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})}function JJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Ot(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(k=>({...k})))},[t,n]),w.useEffect(()=>{if(!t)return;const k=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,e]),!t)return null;const h=k=>{l(A=>A.map((M,C)=>C===k?{...M,visible:!M.visible}:M))},f=(k,A)=>{A<0||A>=o.length||l(M=>{const C=[...M],[j]=C.splice(k,1);return C.splice(A,0,j),C})},p=(k,A)=>{d.current=A,u(A),k.dataTransfer.effectAllowed="move"},x=(k,A)=>{k.preventDefault(),k.dataTransfer.dropEffect="move";const M=d.current;M!==null&&M!==A&&(f(M,A),d.current=A,u(A))},v=k=>{k.preventDefault()},g=()=>{d.current=null,u(null)},y=()=>{l(r.map(k=>({...k})))},_=()=>{a(o),e()},N=o.filter(k=>k.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:k=>k.stopPropagation(),children:i.jsxs(_t,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((k,A)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${k.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>p(M,A),onDragOver:M=>x(M,A),onDrop:v,onDragEnd:g,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Eh,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:k.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>f(A,A-1),disabled:A===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx(yl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>f(A,A+1),disabled:A===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(Pn,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>h(A),className:`p-1.5 rounded transition-colors ${k.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:k.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:k.visible?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(u0,{className:"w-4 h-4"})})]},k.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ce,{variant:"secondary",onClick:y,className:"mr-auto",children:[i.jsx(so,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ce,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ce,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function cK(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const tse="bambuddy-inventory-columns",m1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"cost_per_kg",label:"Cost/kg",visible:!1}];function eet(){try{const t=localStorage.getItem(tse);if(t){const e=JSON.parse(t),n=new Set(m1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=m1.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return m1.map(t=>({...t}))}function tet(t){try{localStorage.setItem(tse,JSON.stringify(t))}catch{}}function Pc(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const net={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function L2(t,e="system"){if(!t)return"-";const n=hi(t);return n?u3(n,e):"-"}const ret={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),cost_per_kg:t=>t("inventory.costPerKg")},iF={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:L2(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:L2(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?L2(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:b4(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=m4(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:Pc(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:Pc(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Pc(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Pc(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"})},O2={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128;return`${n.printer_name||""} ${m4(n.ams_id,n.tray_id,a,r)}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),stock:t=>t.slicer_filament?1:0,cost_per_kg:t=>t.cost_per_kg??0},sF="bambuddy-inventory-sort";function aet(){try{const t=localStorage.getItem(sF);if(t)return JSON.parse(t)}catch{}return null}function iet(t){try{t?localStorage.setItem(sF,JSON.stringify(t)):localStorage.removeItem(sF)}catch{}}function set(){const{t}=Ot(),e=en(),{showToast:n}=an(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,g]=w.useState("all"),[y,_]=w.useState(""),[N,k]=w.useState("table"),[A,M]=w.useState(aet),[C,j]=w.useState(eet),[P,E]=w.useState(!1),[U,L]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[B,D]=w.useState(new Set),[$,G]=w.useState(0),[z,W]=w.useState(()=>{try{const Oe=localStorage.getItem("bambuddy-inventory-pageSize");if(Oe){const pe=Number(Oe);if([15,30,50,100,-1].includes(pe))return pe}}catch{}return 15}),{data:X}=Je({queryKey:["settings"],queryFn:ne.getSettings}),ae=X?.date_format||"system",{data:H,isLoading:K}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),refetchInterval:3e4}),{data:te}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4}),Z=st({mutationFn:Oe=>ne.deleteSpool(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),ve=st({mutationFn:Oe=>ne.archiveSpool(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),ce=st({mutationFn:Oe=>ne.restoreSpool(Oe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),ee=w.useMemo(()=>{if(!H)return null;let Oe=0,pe=0,xe=0,ke=0;const ge={};for(const we of H){if(we.archived_at)continue;ke++;const qe=Math.max(0,we.label_weight-we.weight_used);Oe+=qe,pe+=we.weight_used,(we.label_weight>0?qe/we.label_weight*100:0)<20&&xe++;const tt=we.material||"Unknown";ge[tt]||(ge[tt]={count:0,weight:0}),ge[tt].count++,ge[tt].weight+=qe}return{totalWeight:Oe,totalConsumed:pe,lowStock:xe,byMaterial:ge,totalSpools:ke}},[H]),je=te?.length??0,he=rl(X?.currency||"USD"),oe=w.useMemo(()=>{const Oe={};for(const pe of te||[])Oe[pe.spool_id]=pe;return Oe},[te]),_e=w.useMemo(()=>ee?Object.entries(ee.byMaterial).sort((Oe,pe)=>pe[1].weight-Oe[1].weight).slice(0,4):[],[ee]),ie=w.useMemo(()=>{let Oe=H||[];if(l==="active"?Oe=Oe.filter(pe=>!pe.archived_at):Oe=Oe.filter(pe=>!!pe.archived_at),u==="used"?Oe=Oe.filter(pe=>pe.weight_used>0):u==="new"&&(Oe=Oe.filter(pe=>pe.weight_used===0)),h&&(Oe=Oe.filter(pe=>pe.material===h)),p&&(Oe=Oe.filter(pe=>pe.brand===p)),v==="stock"?Oe=Oe.filter(pe=>!pe.slicer_filament):v==="configured"&&(Oe=Oe.filter(pe=>!!pe.slicer_filament)),y){const pe=y.toLowerCase();Oe=Oe.filter(xe=>xe.brand?.toLowerCase().includes(pe)||xe.material.toLowerCase().includes(pe)||xe.color_name?.toLowerCase().includes(pe)||xe.subtype?.toLowerCase().includes(pe)||xe.note?.toLowerCase().includes(pe)||xe.slicer_filament_name?.toLowerCase().includes(pe))}return Oe},[H,l,u,h,p,v,y]),ze=()=>G(0),V=[...new Set(H?.map(Oe=>Oe.material)||[])].sort(),Y=[...new Set(H?.map(Oe=>Oe.brand).filter(Boolean)||[])].sort(),me=l!=="active"||u!=="all"||!!h||!!p||v!=="all"||!!y,Q=Oe=>{j(Oe),tet(Oe)},se=w.useMemo(()=>C.filter(Oe=>Oe.visible).map(Oe=>Oe.id),[C]),de=Oe=>{O2[Oe]&&(M(pe=>{let xe;return pe?.column===Oe?xe=pe.direction==="asc"?{column:Oe,direction:"desc"}:null:xe={column:Oe,direction:"asc"},iet(xe),xe}),ze())},Le=w.useMemo(()=>{if(!A)return ie;const Oe=O2[A.column];return Oe?[...ie].sort((xe,ke)=>{const ge=Oe(xe,oe),we=Oe(ke,oe);return ge<we?A.direction==="asc"?-1:1:ge>we?A.direction==="asc"?1:-1:0}):ie},[ie,A,oe]),Ne=w.useMemo(()=>{if(!U)return Le.map(ke=>({type:"single",spool:ke}));const Oe=new Map;for(const ke of Le)if(!(ke.weight_used>0||oe[ke.id])){const ge=cK(ke),we=Oe.get(ge);we?we.push(ke):Oe.set(ge,[ke])}const pe=[],xe=new Set;for(const ke of Le){if(ke.weight_used>0||oe[ke.id]){pe.push({type:"single",spool:ke});continue}const ge=cK(ke);if(xe.has(ge))continue;xe.add(ge);const we=Oe.get(ge);we.length===1?pe.push({type:"single",spool:we[0]}):pe.push({type:"group",key:ge,spools:we,representative:we[0]})}return pe},[Le,U,oe]),be=z===-1,O=Ne.length,R=be?O||1:z,q=Math.max(1,Math.ceil(O/R)),J=be?0:Math.min($,q-1),fe=be?Ne:Ne.slice(J*R,(J+1)*R),le=()=>{const Oe=!U;L(Oe),D(new Set),ze();try{localStorage.setItem("bambuddy-inventory-group",String(Oe))}catch{}},Be=Oe=>{D(pe=>{const xe=new Set(pe);return xe.has(Oe)?xe.delete(Oe):xe.add(Oe),xe})},Ie=Oe=>{W(Oe),G(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Oe))}catch{}},Ke=()=>{c("active"),d("all"),f(""),x(""),g("all"),_(""),ze()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(ni,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(Ce,{onClick:()=>a({spool:null}),children:[i.jsx(Gn,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),ee&&!K&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(ni,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Pc(ee.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[ee.totalSpools," ",ee.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(MF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Pc(ee.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(fi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:_e.map(([Oe,pe])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${net[Oe]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Oe," ",i.jsx("span",{className:"opacity-70",children:Pc(pe.weight,!0)})]},Oe))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(gr,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:je}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${ee.lowStock>0?"text-yellow-400":"text-white"}`,children:ee.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:y,onChange:Oe=>{_(Oe.target.value),ze()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),y&&i.jsx("button",{onClick:()=>{_(""),ze()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[N==="table"&&i.jsxs("button",{onClick:()=>E(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(Bhe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("button",{onClick:le,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${U?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:t("inventory.groupSimilar"),children:[i.jsx(Fme,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>k("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Mpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>k("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(h0,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),ze()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(ni,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),ze()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(js,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),ze()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Wn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{g("all"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsx("button",{onClick:()=>{g("stock"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),i.jsx("button",{onClick:()=>{g("configured"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:h,onChange:Oe=>{f(Oe.target.value),ze()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),V.map(Oe=>i.jsx("option",{value:Oe,children:Oe},Oe))]}),i.jsxs("select",{value:p,onChange:Oe=>{x(Oe.target.value),ze()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),Y.map(Oe=>i.jsx("option",{value:Oe,children:Oe},Oe))]}),me&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:Ke,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Lt,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Le.length," ",Le.length!==1?t("inventory.spools"):t("inventory.spool"),U&&O<Le.length&&` (${O} ${t("inventory.groupedRows")})`]})]}),K?i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):N==="cards"?fe.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:fe.map(Oe=>{if(Oe.type==="group"){const{key:we,spools:qe,representative:Ee}=Oe,tt=Ee.rgba?`#${Ee.rgba.substring(0,6)}`:"#808080",De=B.has(we);return i.jsxs("div",{className:"col-span-full",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer",onClick:()=>Be(we),children:[i.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:tt},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:b4(Ee.color_name,Ee.rgba)||"-"})}),i.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Pn,{className:`w-4 h-4 text-bambu-gray transition-transform ${De?"":"-rotate-90"}`}),i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[Ee.material,Ee.subtype?` ${Ee.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:Ee.brand||"-"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:Pc(Ee.label_weight)}),i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:t("inventory.groupedSpools",{count:qe.length})})]})]})]}),De&&i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4",children:qe.map(We=>{const Ae=Math.max(0,We.label_weight-We.weight_used),Re=We.label_weight>0?Ae/We.label_weight*100:0,$e=We.rgba?`#${We.rgba.substring(0,6)}`:"#808080";return i.jsx(uK,{spool:We,remaining:Ae,pct:Re,colorStyle:$e,onClick:()=>a({spool:We}),t},We.id)})})]},`group-${we}`)}const pe=Oe.spool,xe=Math.max(0,pe.label_weight-pe.weight_used),ke=pe.label_weight>0?xe/pe.label_weight*100:0,ge=pe.rgba?`#${pe.rgba.substring(0,6)}`:"#808080";return i.jsx(uK,{spool:pe,remaining:xe,pct:ke,colorStyle:ge,onClick:()=>a({spool:pe}),t},pe.id)})}),i.jsx(oet,{pageIndex:J,pageSize:z,totalRows:O,totalPages:q,onPageChange:G,onPageSizeChange:Ie,t})]}):i.jsx(dK,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}):fe.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[se.map(Oe=>{const pe=!!O2[Oe],xe=A?.column===Oe;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Oe==="remaining"?"min-w-[150px]":""} ${pe?"cursor-pointer hover:text-bambu-green transition-colors":""} ${xe?"text-bambu-green":"text-bambu-gray"}`,onClick:pe?()=>de(Oe):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[ret[Oe]?.(t)??Oe,pe&&(xe?A.direction==="asc"?i.jsx(Mf,{className:"w-3 h-3"}):i.jsx(lb,{className:"w-3 h-3"}):i.jsx(NF,{className:"w-3 h-3 opacity-30"}))]})},Oe)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:fe.map(Oe=>{if(Oe.type==="group"){const{key:ge,spools:we,representative:qe}=Oe,Ee=B.has(ge),tt=Math.max(0,qe.label_weight-qe.weight_used),De=qe.label_weight>0?tt/qe.label_weight*100:0;return i.jsx(cet,{spools:we,representative:qe,remaining:tt,pct:De,isExpanded:Ee,onToggle:()=>Be(ge),onEdit:We=>a({spool:We}),onArchive:We=>o({type:"archive",spoolId:We}),onDelete:We=>o({type:"delete",spoolId:We}),visibleColumns:se,assignmentMap:oe,currencySymbol:he,dateFormat:ae,t},`group-${ge}`)}const pe=Oe.spool,xe=Math.max(0,pe.label_weight-pe.weight_used),ke=pe.label_weight>0?xe/pe.label_weight*100:0;return i.jsx(nse,{spool:pe,remaining:xe,pct:ke,onEdit:()=>a({spool:pe}),onRestore:()=>ce.mutate(pe.id),onArchive:()=>o({type:"archive",spoolId:pe.id}),onDelete:()=>o({type:"delete",spoolId:pe.id}),visibleColumns:se,assignmentMap:oe,currencySymbol:he,dateFormat:ae,t},pe.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:be?`${O} ${t(O!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",J*R+1," ",t("inventory.to")," ",Math.min((J+1)*R,O)," ",t("inventory.of")," ",O," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:z,onChange:Oe=>Ie(Number(Oe.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Oe=>i.jsx("option",{value:Oe,children:Oe},Oe)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!be&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>G(0),disabled:J===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(dX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>G(Oe=>Math.max(0,Oe-1)),disabled:J===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",J+1," ",t("inventory.of")," ",q]}),i.jsx("button",{onClick:()=>G(Oe=>Math.min(q-1,Oe+1)),disabled:J>=q-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>G(q-1),disabled:J>=q-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(hX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(dK,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(ZJe,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:he}),s&&i.jsx(gn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?Z.mutate(s.spoolId):ve.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(JJe,{isOpen:P,onClose:()=>E(!1),columns:C,defaultColumns:m1,onSave:Q})]})}function oet({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(dX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(hX,{className:"w-4 h-4"})})]})]})]})}function uK({spool:t,remaining:e,pct:n,colorStyle:r,onClick:a,t:s}){return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:a,children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:b4(t.color_name,t.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[t.material,t.subtype?` ${t.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:s("inventory.remaining")}),i.jsxs("span",{children:[Math.round(n),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${n>50?"bg-bambu-green":n>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(n,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Pc(t.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?Pc(t.weight_used):"-"})]})]}),t.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:t.note,children:t.note})]})]})}function nse({spool:t,remaining:e,pct:n,onEdit:r,onRestore:a,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,currencySymbol:u,dateFormat:d,t:h}){return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:r,children:[l.map(f=>i.jsx("td",{className:"py-3 px-4",children:iF[f]?.({spool:t,remaining:e,pct:n,assignmentMap:c,currencySymbol:u,dateFormat:d,t:h})},f)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:f=>f.stopPropagation(),children:[i.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:h("inventory.editSpool"),children:i.jsx(ef,{className:"w-4 h-4"})}),t.archived_at?i.jsx("button",{onClick:a,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:h("inventory.restore"),children:i.jsx(so,{className:"w-4 h-4"})}):i.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:h("inventory.archive"),children:i.jsx(js,{className:"w-4 h-4"})}),i.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:h("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})}function cet({spools:t,representative:e,remaining:n,pct:r,isExpanded:a,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:u,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p}){return i.jsxs(i.Fragment,{children:[i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5",onClick:s,children:[u.map((x,v)=>i.jsx("td",{className:"py-3 px-4",children:v===0?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pn,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"":"-rotate-90"}`}),iF[x]?.({spool:e,remaining:n,pct:r,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p})]}):x==="id"?i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:p("inventory.groupedSpools",{count:t.length})}):iF[x]?.({spool:e,remaining:n,pct:r,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p})},x)),i.jsx("td",{className:"py-3 px-4",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(x=>`#${x.id}`).join(", ")})})]}),a&&t.map(x=>{const v=Math.max(0,x.label_weight-x.weight_used),g=x.label_weight>0?v/x.label_weight*100:0;return i.jsx(nse,{spool:x,remaining:v,pct:g,onEdit:()=>o(x),onRestore:()=>{},onArchive:()=>l(x.id),onDelete:()=>c(x.id),visibleColumns:u,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p},x.id)})]})}function dK({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(xr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(Ce,{onClick:e,children:[i.jsx(ni,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const hK=["DEBUG","INFO","WARNING","ERROR"],I2={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},uet={DEBUG:HC,INFO:Zs,WARNING:Tn,ERROR:Ba};function det(){const t=en(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:g}=Je({queryKey:["application-logs",l,s],queryFn:()=>Kg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=st({mutationFn:()=>Kg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const _=C=>{a(j=>{const P=new Set(j);return P.has(C)?P.delete(C):P.add(C),P})},N=C=>{const j=C.split(" ");return j.length>=2?j[1]:C},k=w.useMemo(()=>x?.entries??[],[x?.entries]),A=w.useMemo(()=>[...k].reverse(),[k]),M=({level:C})=>{const j=uet[C]||Zs;return i.jsx(j,{className:`w-3.5 h-3.5 ${I2[C]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(HC,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[h&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(yl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(Pn,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[i.jsx(vl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!0),g()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(io,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||k.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>g(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Ar,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:C=>n(C.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(xr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:C=>o(C.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Lt,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),hK.map((C,j)=>i.jsx("button",{onClick:()=>c(C),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===hK.length-1?"rounded-r":""} ${l===C?`${I2[C]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:C},C))]})]})]}),i.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:k.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:A.map((C,j)=>{const P=r.has(j),E=C.message.includes(`
  8312. `);return i.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${P?"bg-bambu-dark-secondary/30":""}`,onClick:()=>E&&_(j),children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:N(C.timestamp)}),i.jsx("span",{className:"shrink-0",children:i.jsx(M,{level:C.level})}),i.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:C.logger_name,children:["[",C.logger_name,"]"]}),i.jsx("span",{className:`flex-1 ${I2[C.level]||"text-white/80"} ${!P&&E?"truncate":""}`,children:P?i.jsx("pre",{className:"whitespace-pre-wrap break-all",children:C.message}):C.message.split(`
  8313. `)[0]}),E&&i.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:P?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Pn,{className:"w-3.5 h-3.5"})})]})},j)})})}),i.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:h?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):i.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function het(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function ka({icon:t,label:e,value:n,subValue:r,color:a="text-bambu-green"}){return i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${a}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function mK({percent:t,color:e="bg-bambu-green"}){return i.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function rh({title:t,icon:e,children:n}){return i.jsxs(wt,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(e,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function met(){const{t}=Ot(),e=en(),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=Je({queryKey:["systemInfo"],queryFn:ne.getSystemInfo,refetchInterval:3e4}),{data:f}=Je({queryKey:["debugLogging"],queryFn:Kg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:p}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:x}=Je({queryKey:["library-stats"],queryFn:ne.getLibraryStats}),v=p?.time_format||"system",g=async()=>{l(!0);try{const k=await Kg.setDebugLogging(!f?.enabled);e.setQueryData(["debugLogging"],k)}catch(k){console.error("Failed to toggle debug logging:",k)}finally{l(!1)}},y=async()=>{r(null),s(!0);try{await Kg.downloadSupportBundle()}catch(k){r(k instanceof Error?k.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return i.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",N=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return i.jsxs("div",{className:"p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),i.jsxs("button",{onClick:()=>d(),disabled:h,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[i.jsx(Ar,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),i.jsx(rh,{title:t("system.application","Application"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.version","Version"),value:`v${c.app.version}`}),i.jsx(ka,{icon:Wn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),i.jsx(ka,{icon:Um,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),i.jsx(rh,{title:t("support.title","Support & Troubleshooting"),icon:Bme,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(HC,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),f?.enabled&&f.duration_seconds!==null&&i.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(f.duration_seconds/60),"m ",f.duration_seconds%60,"s)"]})]})]})]}),i.jsxs("button",{onClick:g,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${f?.enabled?"bg-amber-500/20 text-amber-400 hover:bg-amber-500/30":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30"} disabled:opacity-50`,children:[o&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),f?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:i.jsx(da,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),i.jsxs("button",{onClick:y,disabled:a||!f?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:f?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[a&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!f?.enabled&&i.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),i.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),i.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),i.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),i.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),i.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),i.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),i.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),i.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),i.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),i.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),i.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),i.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),i.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),i.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),i.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),i.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], and serial numbers with [SERIAL].")})]}),i.jsx(det,{})]})}),i.jsxs(rh,{title:t("system.database","Database"),icon:Ec,children:[i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(ka,{icon:js,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),i.jsx(ka,{icon:ub,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),i.jsx(ka,{icon:mi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),i.jsx(ka,{icon:it,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:gr,label:t("system.printers","Printers"),value:c.database.printers}),i.jsx(ka,{icon:XC,label:t("system.filaments","Filaments"),value:c.database.filaments}),i.jsx(ka,{icon:gs,label:t("system.projects","Projects"),value:c.database.projects}),i.jsx(ka,{icon:fl,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[i.jsx(ka,{icon:Wn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),i.jsx(ka,{icon:js,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),i.jsxs(rh,{title:t("system.connectedPrinters","Connected Printers"),icon:gr,children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[i.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),i.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?i.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(k=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),i.jsx("span",{className:"font-medium text-white",children:k.name})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[i.jsx("span",{children:k.model}),i.jsx("span",{className:`px-2 py-0.5 rounded ${k.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":k.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:k.state})]})]},k.id))}):i.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),i.jsx(rh,{title:t("system.storage","Storage"),icon:Vb,children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),i.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),i.jsx(mK,{percent:c.storage.disk_percent_used,color:_}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:js,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),i.jsx(ka,{icon:Ec,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Zl,label:t("system.fileManagerStorage","File Manager"),value:het(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsx(rh,{title:t("system.memory","Memory"),icon:yfe,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),i.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),i.jsx(mK,{percent:c.memory.percent_used,color:N}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),i.jsx(rh,{title:t("system.cpu","CPU"),icon:Og,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:Og,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:Og,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(rh,{title:t("system.systemDetails","System Details"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),i.jsx(ka,{icon:Og,label:t("system.architecture","Architecture"),value:c.system.architecture}),i.jsx(ka,{icon:Um,label:t("system.python","Python"),value:c.system.python_version}),i.jsx(ka,{icon:Wn,label:t("system.bootTime","Boot Time"),value:Rf(c.system.boot_time,v)})]})})]})}function fet(){const t=rc(),{t:e}=Ot(),{login:n}=Ir(),{showToast:r}=an(),{mode:a}=tp(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[h,f]=w.useState(""),{data:p}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),x=st({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=st({mutationFn:_=>ne.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),d(!1),f("")},onError:_=>{r(_.message,"error")}}),g=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}x.mutate()},y=_=>{if(_.preventDefault(),!h){r("Please enter your email address","error");return}v.mutate(h)};return i.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:g,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:p?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),i.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:p?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),i.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:x.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:x.isPending?e("login.signingIn"):e("login.signIn")})}),p?.advanced_auth_enabled&&i.jsx("div",{className:"text-center",children:i.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:i.jsxs(wt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(bv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Lt,{className:"w-5 h-5"})})]})}),i.jsx(_t,{children:p?.advanced_auth_enabled?i.jsxs("form",{onSubmit:y,className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),i.jsx("input",{id:"forgot-email",type:"email",required:!0,value:h,onChange:_=>f(_.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("login.emailPlaceholder")||"your.email@example.com"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Ce,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[i.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),i.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[i.jsx("li",{children:e("login.resetStep1")}),i.jsx("li",{children:e("login.resetStep2")}),i.jsx("li",{children:e("login.resetStep3")}),i.jsx("li",{children:e("login.resetStep4")})]})]}),i.jsx(Ce,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function pet(){const t=rc(),{t:e}=Ot(),{showToast:n}=an(),{mode:r}=tp(),{refreshAuth:a}=Ir(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),p=st({mutationFn:()=>ne.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await a(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),x=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==h){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}p.mutate()};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),i.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&i.jsxs("div",{className:"space-y-4 mt-4",children:[i.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-sm text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),i.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&i.jsxs("div",{children:[i.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),i.jsx("input",{id:"confirm-password",type:"password",value:h,onChange:v=>f(v.target.value),className:"block w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:p.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:p.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}const get=[{to:"/spoolbuddy",icon:m0,labelKey:"spoolbuddy.nav.dashboard",end:!0},{to:"/spoolbuddy/ams",icon:Og,labelKey:"spoolbuddy.nav.ams"},{to:"/spoolbuddy/inventory",icon:ni,labelKey:"spoolbuddy.nav.inventory"},{to:"/spoolbuddy/printers",icon:gr,labelKey:"spoolbuddy.nav.printers"},{to:"/spoolbuddy/settings",icon:f0,labelKey:"spoolbuddy.nav.settings"}];function bet({isKiosk:t}){const{t:e}=Ot();return i.jsxs("nav",{className:"h-[48px] bg-bg-secondary border-b border-bambu-dark-tertiary flex items-center px-2 gap-1",children:[!t&&i.jsx(Zm,{to:"/",className:"flex items-center gap-1 px-3 h-[40px] rounded-lg text-text-secondary hover:text-white hover:bg-bambu-dark-tertiary text-[13px]",children:i.jsx(_F,{size:16})}),i.jsx("div",{className:"flex items-center gap-1 px-2",children:i.jsx("span",{className:"text-bambu-green font-bold text-[15px]",children:"SpoolBuddy"})}),i.jsx("div",{className:"flex items-center gap-1 flex-1",children:get.map(({to:n,icon:r,labelKey:a,end:s})=>i.jsxs(Zm,{to:n,end:s,className:({isActive:o})=>`flex items-center gap-1.5 px-4 h-[40px] rounded-lg text-[13px] font-medium transition-colors ${o?"bg-bambu-green text-white":"text-text-secondary hover:text-white hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(r,{size:16}),i.jsx("span",{children:e(a)})]},n))})]})}function xet({weightGrams:t,stable:e,nfcOk:n,deviceOnline:r}){const{t:a}=Ot();return i.jsxs("div",{className:"h-[40px] bg-bg-secondary border-t border-bambu-dark-tertiary flex items-center px-4 text-[13px]",children:[i.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(m0,{size:14,className:"text-text-secondary"}),i.jsx("span",{className:"text-text-primary font-mono",children:t!==null?`${t.toFixed(1)}g`:"---"}),t!==null&&i.jsx("span",{className:`w-2 h-2 rounded-full ${e?"bg-green-500":"bg-yellow-500 animate-pulse"}`})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(yX,{size:14,className:"text-text-secondary"}),i.jsx("span",{className:n?"text-green-500":"text-text-muted",children:a(n?"spoolbuddy.status.nfcReady":"spoolbuddy.status.nfcOff")})]}),!r&&i.jsx("span",{className:"text-red-400 text-[12px]",children:a("spoolbuddy.status.offline")})]}),i.jsx("span",{className:"text-text-muted text-[12px]",children:"SpoolBuddy"})]})}const yet={view:"idle",weight:null,tag:null,spool:null,deviceOnline:!1};function vet(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.payload};case"TAG_MATCHED":return{...t,view:"tag_known",tag:e.payload.tag,spool:e.payload.spool};case"TAG_UNKNOWN":return{...t,view:"tag_unknown",tag:e.payload,spool:null};case"TAG_REMOVED":return{...t,view:"idle",tag:null,spool:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null};default:return t}}function wet(){const[t,e]=w.useReducer(vet,yet),n=w.useCallback(l=>{const c=l.detail;e({type:"WEIGHT_UPDATE",payload:{weight_grams:c.weight_grams,stable:c.stable,raw_adc:c.raw_adc??null,device_id:c.device_id}})},[]),r=w.useCallback(l=>{const c=l.detail;e({type:"TAG_MATCHED",payload:{tag:{tag_uid:c.tag_uid,device_id:c.device_id},spool:c.spool}})},[]),a=w.useCallback(l=>{const c=l.detail;e({type:"TAG_UNKNOWN",payload:{tag_uid:c.tag_uid,sak:c.sak,tag_type:c.tag_type,device_id:c.device_id}})},[]),s=w.useCallback(()=>{e({type:"TAG_REMOVED"})},[]),o=w.useCallback(l=>{l.detail.type==="spoolbuddy_online"?e({type:"DEVICE_ONLINE"}):e({type:"DEVICE_OFFLINE"})},[]);return w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",a),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-device-status",o),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",a),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-device-status",o)}),[n,r,a,s,o]),t}function _et(){const[t]=BC(),e=t.get("kiosk")==="1"||window.innerHeight<=600,n=wet();return i.jsxs("div",{className:"w-[1024px] h-[600px] mx-auto flex flex-col bg-bg-primary overflow-hidden",style:{touchAction:"manipulation"},children:[i.jsx(bet,{isKiosk:e}),i.jsx("main",{className:"flex-1 overflow-hidden",children:i.jsx(HK,{context:n})}),i.jsx(xet,{weightGrams:n.weight?.weight_grams??null,stable:n.weight?.stable??!1,nfcOk:n.deviceOnline,deviceOnline:n.deviceOnline})]})}function Net({weightGrams:t,stable:e,onTare:n,onCalibrate:r}){const{t:a}=Ot();return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full px-4",children:[i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("span",{className:"text-[72px] font-bold text-text-primary leading-none",style:{fontVariantNumeric:"tabular-nums"},children:t!==null?t.toFixed(1):"---"}),i.jsx("span",{className:"text-[24px] text-text-secondary mt-1",children:"g"}),i.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[i.jsx("span",{className:`w-3 h-3 rounded-full ${t===null?"bg-bambu-gray":e?"bg-green-500":"bg-yellow-500 animate-pulse"}`}),i.jsx("span",{className:"text-[16px] text-text-secondary",children:a(t===null?"spoolbuddy.weight.noReading":e?"spoolbuddy.weight.stable":"spoolbuddy.weight.measuring")})]})]}),i.jsxs("div",{className:"w-full flex gap-3 pb-4",children:[i.jsx(Ce,{variant:"secondary",className:"flex-1 h-[64px] text-[16px]",onClick:n,children:a("spoolbuddy.weight.tare")}),i.jsx(Ce,{variant:"secondary",className:"flex-1 h-[64px] text-[16px]",onClick:r,children:a("spoolbuddy.weight.calibrate")})]})]})}function Cet({spool:t}){const{t:e}=Ot(),n=Math.max(0,t.label_weight-t.weight_used),r=t.label_weight>0?Math.round(n/t.label_weight*100):0,a=t.rgba?`#${t.rgba.substring(0,6)}`:"#808080",s=t.subtype?`${t.material} ${t.subtype}`:t.material;return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"w-[48px] h-[48px] rounded-full border-2 border-bambu-dark-tertiary flex-shrink-0",style:{backgroundColor:a}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("h3",{className:"text-[18px] font-semibold text-text-primary truncate",children:s}),i.jsx("p",{className:"text-[14px] text-text-secondary truncate",children:[t.brand,t.color_name].filter(Boolean).join(" - ")})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex justify-between text-[14px]",children:[i.jsx("span",{className:"text-text-secondary",children:e("spoolbuddy.spool.remaining")}),i.jsxs("span",{className:"text-text-primary font-medium",children:[n,"g (",r,"%)"]})]}),i.jsx("div",{className:"w-full h-3 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${r}%`,backgroundColor:r>20?"var(--accent)":r>5?"#f59e0b":"#ef4444"}})})]})]})}function ket({tagUid:t,sak:e,tagType:n,onLinkExisting:r,onCreateNew:a}){const{t:s}=Ot();return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full px-6",children:[i.jsx(Tn,{size:48,className:"text-yellow-500 mb-4"}),i.jsx("h3",{className:"text-[24px] font-semibold text-text-primary mb-2",children:s("spoolbuddy.tag.unknownTitle")}),i.jsx("p",{className:"text-[14px] text-text-secondary mb-1 font-mono",children:t}),n&&i.jsxs("p",{className:"text-[13px] text-text-muted mb-6",children:[n,e!==void 0?` (SAK: 0x${e.toString(16).toUpperCase().padStart(2,"0")})`:""]}),i.jsxs("div",{className:"w-full space-y-3 max-w-[320px]",children:[i.jsx(Ce,{variant:"primary",className:"w-full h-[64px] text-[16px]",onClick:r,children:s("spoolbuddy.tag.linkExisting")}),i.jsx(Ce,{variant:"secondary",className:"w-full h-[64px] text-[16px]",onClick:a,children:s("spoolbuddy.tag.createNew")})]})]})}function Aet({onUpdateWeight:t,onEditSpool:e,onAssignAms:n,onViewHistory:r}){const{t:a}=Ot(),s=[{icon:Og,label:a("spoolbuddy.actions.assignAms"),onClick:n,variant:"primary"},{icon:m0,label:a("spoolbuddy.actions.updateWeight"),onClick:t,variant:"secondary"},{icon:_pe,label:a("spoolbuddy.actions.editSpool"),onClick:e,variant:"secondary"},{icon:db,label:a("spoolbuddy.actions.viewHistory"),onClick:r,variant:"secondary"}];return i.jsx("div",{className:"grid grid-cols-2 gap-3",children:s.map(({icon:o,label:l,onClick:c,variant:u})=>i.jsxs(Ce,{variant:u,className:"h-[64px] text-[14px] flex-col gap-1",onClick:c,children:[i.jsx(o,{size:20}),i.jsx("span",{children:l})]},l))})}function Tet(){const t=IK(),{t:e}=Ot(),{showToast:n}=an(),r=st({mutationFn:o=>$y.updateSpoolWeight(o.spool_id,o.weight_grams),onSuccess:()=>n(e("spoolbuddy.actions.weightUpdated"),"success"),onError:()=>n(e("common.error"),"error")}),a=()=>{t.spool&&t.weight&&r.mutate({spool_id:t.spool.id,weight_grams:t.weight.weight_grams})},s=async()=>{if(t.weight?.device_id)try{await $y.tare(t.weight.device_id),n(e("spoolbuddy.weight.tareQueued"),"success")}catch{n(e("common.error"),"error")}};return i.jsxs("div",{className:"flex h-[512px]",children:[i.jsx("div",{className:"w-[512px] border-r border-bambu-dark-tertiary",children:i.jsx(Net,{weightGrams:t.weight?.weight_grams??null,stable:t.weight?.stable??!1,rawAdc:t.weight?.raw_adc??null,onTare:s,onCalibrate:()=>{}})}),i.jsxs("div",{className:"w-[512px] p-6 overflow-y-auto",children:[t.view==="idle"&&i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[i.jsxs("div",{className:"flex gap-4 mb-6",children:[i.jsx(m0,{size:48,className:"text-text-muted"}),i.jsx(yX,{size:48,className:"text-text-muted"})]}),i.jsx("p",{className:"text-[24px] text-text-secondary max-w-[360px]",children:e("spoolbuddy.dashboard.idleMessage")})]}),t.view==="tag_known"&&t.spool&&i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsx("div",{className:"flex-1",children:i.jsx(Cet,{spool:t.spool})}),i.jsx(Aet,{onUpdateWeight:a,onEditSpool:()=>{},onAssignAms:()=>{},onViewHistory:()=>{}})]}),t.view==="tag_unknown"&&t.tag&&i.jsx(ket,{tagUid:t.tag.tag_uid,sak:t.tag.sak,tagType:t.tag.tag_type,onLinkExisting:()=>{},onCreateNew:()=>{}})]})]})}function Met({material:t,colorHex:e,remaining:n,isEmpty:r,onClick:a}){const s=e?`#${e.substring(0,6)}`:"#808080";return i.jsx("button",{onClick:a,className:"w-[120px] h-[120px] rounded-xl border border-bambu-dark-tertiary bg-bg-secondary flex flex-col items-center justify-center gap-2 active:bg-bambu-dark-tertiary transition-colors",children:r?i.jsx("span",{className:"text-text-muted text-[13px]",children:"Empty"}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-[48px] h-[48px] rounded-full border-2 border-bambu-dark-tertiary",style:{backgroundColor:s}}),i.jsx("span",{className:"text-text-primary text-[13px] font-medium truncate max-w-[100px]",children:t||"---"}),n!==null&&n>=0&&i.jsx("div",{className:"w-[80px] h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full bg-bambu-green",style:{width:`${Math.min(100,n)}%`}})})]})})}function Pet(){const{t}=Ot(),[e,n]=w.useState(null),{data:r}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),a=r||[],s=e??a[0]?.id??null,{data:o}=Je({queryKey:["printerStatus",s],enabled:s!==null}),c=o?.ams?.ams;return i.jsxs("div",{className:"h-[512px] p-4 overflow-y-auto",children:[i.jsx("div",{className:"mb-4",children:i.jsx("select",{value:s??"",onChange:u=>n(Number(u.target.value)),className:"h-[48px] w-full bg-bg-secondary border border-bambu-dark-tertiary rounded-lg px-4 text-text-primary text-[14px]",children:a.map(u=>i.jsx("option",{value:u.id,children:u.name},u.id))})}),c?i.jsx("div",{className:"space-y-6",children:c.map((u,d)=>{const h=u.tray;if(!h)return null;const f=String.fromCharCode(65+d);return i.jsxs("div",{children:[i.jsxs("h3",{className:"text-[16px] font-semibold text-text-primary mb-2",children:["AMS-",f]}),i.jsx("div",{className:"flex gap-2",children:h.map((p,x)=>{const v=p.tray_type,g=p.tray_color,y=p.remain,_=!v||v==="";return i.jsx(Met,{material:v||null,colorHex:g||null,colorName:null,remaining:y??null,isEmpty:_,onClick:()=>{}},x)})})]},d)})}):i.jsx("div",{className:"flex items-center justify-center h-[300px]",children:i.jsx("p",{className:"text-text-muted text-[16px]",children:t("spoolbuddy.ams.noData")})})]})}function Eet(){const{t}=Ot(),[e,n]=w.useState(""),{data:r,isLoading:a}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools()}),o=(r||[]).filter(l=>{if(!e)return!0;const c=e.toLowerCase();return l.material.toLowerCase().includes(c)||l.brand?.toLowerCase().includes(c)||l.color_name?.toLowerCase().includes(c)});return i.jsxs("div",{className:"h-[512px] flex flex-col p-4",children:[i.jsxs("div",{className:"flex gap-2 mb-4",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(xr,{size:16,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-muted"}),i.jsx("input",{type:"text",value:e,onChange:l=>n(l.target.value),placeholder:t("spoolbuddy.inventory.search"),className:"w-full h-[48px] bg-bg-secondary border border-bambu-dark-tertiary rounded-lg pl-10 pr-4 text-text-primary text-[14px] placeholder:text-text-muted"})]}),i.jsxs(Ce,{variant:"primary",className:"h-[48px] px-4",children:[i.jsx(Gn,{size:18}),i.jsx("span",{className:"ml-1",children:t("common.add")})]})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto",children:[i.jsx("div",{className:"grid grid-cols-2 gap-2",children:o.map(l=>{const c=Math.max(0,l.label_weight-l.weight_used),u=l.label_weight>0?Math.round(c/l.label_weight*100):0,d=l.rgba?`#${l.rgba.substring(0,6)}`:"#808080",h=l.subtype?`${l.material} ${l.subtype}`:l.material;return i.jsxs("button",{className:"flex items-center gap-3 p-4 bg-bg-secondary rounded-xl border border-bambu-dark-tertiary active:bg-bambu-dark-tertiary transition-colors text-left",children:[i.jsx("div",{className:"w-[32px] h-[32px] rounded-full border-2 border-bambu-dark-tertiary flex-shrink-0",style:{backgroundColor:d}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-[14px] font-semibold text-text-primary truncate",children:h}),i.jsx("p",{className:"text-[12px] text-text-secondary truncate",children:[l.brand,l.color_name].filter(Boolean).join(" - ")}),i.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[i.jsxs("span",{className:"text-[12px] text-text-muted",children:[c,"g"]}),i.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full bg-bambu-green",style:{width:`${u}%`}})})]})]})]},l.id)})}),o.length===0&&!a&&i.jsx("div",{className:"flex items-center justify-center h-[200px]",children:i.jsx("p",{className:"text-text-muted text-[14px]",children:t("spoolbuddy.inventory.empty")})})]})]})}function jet(){const{t}=Ot(),{data:e}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),n=e||[];return i.jsxs("div",{className:"h-[512px] p-4 overflow-y-auto space-y-2",children:[n.map(r=>i.jsx(Det,{printer:r},r.id)),n.length===0&&i.jsx("div",{className:"flex items-center justify-center h-[300px]",children:i.jsx("p",{className:"text-text-muted text-[16px]",children:t("spoolbuddy.printers.noPrinters")})})]})}function Det({printer:t}){const{data:e}=Je({queryKey:["printerStatus",t.id]}),n=e,r=n?.online===!0,a=n?.mc_percent,s=n?.nozzle_temper,o=n?.bed_temper;return i.jsxs("div",{className:"p-4 bg-bg-secondary rounded-xl border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${r?"bg-green-500":"bg-bambu-gray"}`}),i.jsx("h3",{className:"text-[16px] font-semibold text-text-primary",children:t.name})]}),i.jsx("span",{className:`text-[13px] px-2 py-0.5 rounded ${r?"bg-green-500/20 text-green-400":"bg-bambu-dark-tertiary text-text-muted"}`,children:r?"Online":"Offline"})]}),i.jsxs("div",{className:"flex items-center gap-3 text-[13px] text-text-secondary",children:[i.jsx("span",{children:t.model}),i.jsx("span",{children:t.ip_address}),a!==void 0&&a>0&&i.jsxs("span",{children:["Print: ",a,"%"]}),s!==void 0&&o!==void 0&&r&&i.jsxs("span",{children:[Math.round(s),"° / ",Math.round(o),"°"]})]})]})}function Ret(){const t=IK(),{t:e}=Ot(),{showToast:n}=an(),r=en(),[a,s]=w.useState("500"),{data:o}=Je({queryKey:["spoolbuddy-devices"],queryFn:$y.getDevices}),c=(o||[])[0],u=c?.device_id??t.weight?.device_id,d=st({mutationFn:()=>$y.tare(u),onSuccess:()=>{n(e("spoolbuddy.settings.tareQueued"),"success"),r.invalidateQueries({queryKey:["spoolbuddy-devices"]})},onError:()=>n(e("common.error"),"error")}),h=st({mutationFn:()=>$y.setCalibrationFactor(u,parseFloat(a),t.weight?.raw_adc??0),onSuccess:()=>{n(e("spoolbuddy.settings.calibrated"),"success"),r.invalidateQueries({queryKey:["spoolbuddy-devices"]})},onError:()=>n(e("common.error"),"error")}),f=p=>{const x=Math.floor(p/3600),v=Math.floor(p%3600/60);return`${x}h ${v}m`};return i.jsxs("div",{className:"h-[512px] p-4 overflow-y-auto space-y-4",children:[i.jsxs("section",{children:[i.jsx("h2",{className:"text-[18px] font-semibold text-text-primary mb-3",children:e("spoolbuddy.settings.scaleCalibration")}),i.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-bambu-dark-tertiary p-4 space-y-4",children:[i.jsxs("div",{className:"flex justify-between text-[14px]",children:[i.jsx("span",{className:"text-text-secondary",children:e("spoolbuddy.settings.currentWeight")}),i.jsx("span",{className:"text-text-primary font-mono",children:t.weight?`${t.weight.weight_grams.toFixed(1)}g (raw: ${t.weight.raw_adc??"---"})`:"---"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsxs("span",{className:"text-[14px] text-text-secondary",children:[e("spoolbuddy.settings.tareOffset"),": ",c?.tare_offset??"---"]}),i.jsx(Ce,{variant:"secondary",className:"h-[48px] px-6",onClick:()=>d.mutate(),disabled:!u||d.isPending,children:e("spoolbuddy.weight.tare")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-[14px] text-text-secondary whitespace-nowrap",children:[e("spoolbuddy.settings.knownWeight"),":"]}),i.jsx("input",{type:"number",value:a,onChange:p=>s(p.target.value),className:"h-[48px] w-[120px] bg-bg-primary border border-bambu-dark-tertiary rounded-lg px-3 text-text-primary text-[14px] text-right"}),i.jsx("span",{className:"text-[14px] text-text-secondary",children:"g"}),i.jsx(Ce,{variant:"secondary",className:"h-[48px] px-6 ml-auto",onClick:()=>h.mutate(),disabled:!u||!t.weight?.raw_adc||h.isPending,children:e("spoolbuddy.weight.calibrate")})]})]})]}),i.jsxs("section",{children:[i.jsx("h2",{className:"text-[18px] font-semibold text-text-primary mb-3",children:e("spoolbuddy.settings.nfcReader")}),i.jsx("div",{className:"bg-bg-secondary rounded-xl border border-bambu-dark-tertiary p-4",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${c?.nfc_ok?"bg-green-500":"bg-bambu-gray"}`}),i.jsx("span",{className:"text-[14px] text-text-primary",children:c?.nfc_ok?e("spoolbuddy.settings.nfcConnected"):e("spoolbuddy.settings.nfcDisconnected")})]})})]}),c&&i.jsxs("section",{children:[i.jsx("h2",{className:"text-[18px] font-semibold text-text-primary mb-3",children:e("spoolbuddy.settings.deviceInfo")}),i.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-bambu-dark-tertiary p-4 text-[14px] space-y-2",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary",children:e("spoolbuddy.settings.deviceId")}),i.jsx("span",{className:"text-text-primary font-mono",children:c.device_id})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary",children:"IP"}),i.jsx("span",{className:"text-text-primary",children:c.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary",children:e("spoolbuddy.settings.uptime")}),i.jsx("span",{className:"text-text-primary",children:f(c.uptime_s)})]}),c.firmware_version&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-text-secondary",children:e("spoolbuddy.settings.firmware")}),i.jsx("span",{className:"text-text-primary",children:c.firmware_version})]})]})]})]})}function Fet(){const t=w.useRef(null),e=w.useRef(null),n=en(),[r,a]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),h=w.useRef(()=>{}),f=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const _=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{h.current(N),u.current.length>0?setTimeout(_,16):d.current=!1}):d.current=!1};_()},[]),p=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(N);let A=null;k.onopen=()=>{console.log("[WebSocket] Connected"),a(!0),A=window.setInterval(()=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"ping"}))},3e4)},k.onmessage=M=>{try{const C=JSON.parse(M.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=M=>{console.log("[WebSocket] Closed",M.code,M.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=M=>{console.error("[WebSocket] Error",M),k.close()},t.current=k},[f]),x=w.useCallback((_,N)=>{const k=l.current.get(_)||{};l.current.set(_,{...k,...N}),c.current||(c.current=window.setTimeout(()=>{const A=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{A.forEach((M,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...M};return P.wifi_signal==null&&j?.wifi_signal!=null&&(P.wifi_signal=j.wifi_signal),P})})})},100))},[n]),v=w.useCallback(_=>{s.current.add(_),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let k=0;N.forEach(A=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[A]})})},k),k+=500})},3e3)},[n]),g=w.useCallback(_=>{switch(_.type){case"printer_status":_.printer_id!==void 0&&_.data&&x(_.printer_id,_.data);break;case"print_start":_.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",_.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:_.printer_id,printer_name:_.printer_name,message:_.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:_.printer_id,ams_id:_.ams_id,tray_id:_.tray_id,tag_uid:_.tag_uid,tray_uuid:_.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:_.data||{}}));break;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:_}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:_})),v("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:_}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:_}));break;case"spoolbuddy_online":case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-device-status",{detail:_})),v("spoolbuddy-devices");break}},[n,v,x]);w.useEffect(()=>{h.current=g},[g]),w.useEffect(()=>(p(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[p]);const y=w.useCallback(_=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(_))},[]);return{isConnected:r,sendMessage:y}}const Let=new bde({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function fK({children:t}){return Fet(),i.jsx(i.Fragment,{children:t})}function pK({children:t}){const{authEnabled:e,loading:n,user:r}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function z2({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(ob,{to:"/",replace:!0}):i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Oet({children:t}){const{authEnabled:e,loading:n}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Iet(){return i.jsx(fge,{children:i.jsx(Sge,{children:i.jsx(xde,{client:Let,children:i.jsx(vge,{children:i.jsx(Oue,{children:i.jsxs(hue,{children:[i.jsx(Nr,{path:"/setup",element:i.jsx(Oet,{children:i.jsx(pet,{})})}),i.jsx(Nr,{path:"/login",element:i.jsx(fet,{})}),i.jsx(Nr,{path:"/camera/:printerId",element:i.jsx(kJe,{})}),i.jsx(Nr,{path:"/overlay/:printerId",element:i.jsx(PJe,{})}),i.jsxs(Nr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(_et,{})})}),children:[i.jsx(Nr,{path:"spoolbuddy",element:i.jsx(Tet,{})}),i.jsx(Nr,{path:"spoolbuddy/ams",element:i.jsx(Pet,{})}),i.jsx(Nr,{path:"spoolbuddy/inventory",element:i.jsx(Eet,{})}),i.jsx(Nr,{path:"spoolbuddy/printers",element:i.jsx(jet,{})}),i.jsx(Nr,{path:"spoolbuddy/settings",element:i.jsx(Ret,{})})]}),i.jsxs(Nr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(kge,{})})}),children:[i.jsx(Nr,{index:!0,element:i.jsx(C$e,{})}),i.jsx(Nr,{path:"archives",element:i.jsx(hYe,{})}),i.jsx(Nr,{path:"queue",element:i.jsx(YQe,{})}),i.jsx(Nr,{path:"stats",element:i.jsx(uZe,{})}),i.jsx(Nr,{path:"profiles",element:i.jsx(tJe,{})}),i.jsx(Nr,{path:"maintenance",element:i.jsx(sJe,{})}),i.jsx(Nr,{path:"projects",element:i.jsx(lJe,{})}),i.jsx(Nr,{path:"projects/:id",element:i.jsx(pJe,{})}),i.jsx(Nr,{path:"inventory",element:i.jsx(set,{})}),i.jsx(Nr,{path:"files",element:i.jsx(SJe,{})}),i.jsx(Nr,{path:"settings",element:i.jsx(z2,{children:i.jsx(BZe,{})})}),i.jsx(Nr,{path:"groups/new",element:i.jsx(z2,{children:i.jsx(sK,{})})}),i.jsx(Nr,{path:"groups/:id/edit",element:i.jsx(z2,{children:i.jsx(sK,{})})}),i.jsx(Nr,{path:"users",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(Nr,{path:"groups",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(Nr,{path:"system",element:i.jsx(met,{})}),i.jsx(Nr,{path:"external/:id",element:i.jsx(EJe,{})})]})]})})})})})})}lle.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(Iet,{})}));